title,body,link,tags,view_count,is_answered,score,answer_count
Unit testing internal methods in VS2017 .NET Standard library,"<p>I am currently playing around with the latest Visual Studio 2017 Release Candidate by creating a .NET Standard 1.6 library. I am using xUnit to unit test my code and was wondering if you can still test internal methods in VS2017.</p>
<p>I remember that you could add a line in AssemblyInfo.cs class in VS2015 that would enable specified projects to see internal methods:</p>
<pre><code>[assembly:InternalsVisibleTo(&quot;MyTests&quot;)]
</code></pre>
<p>As there is no AssemblyInfo.cs class in VS2017 .NET Standard projects, I was wondering if you can still unit test internal methods?</p>
",https://stackoverflow.com/questions/42235401/unit-testing-internal-methods-in-vs2017-net-standard-library,"['c#', 'unit-testing', 'visual-studio-2017', '.net-standard']",49392,TRUE,178,5
Unit testing Room and LiveData,"<p>I'm currently developing an app using the newly <a href=""https://developer.android.com/topic/libraries/architecture/index.html"" rel=""noreferrer"">Android Architecture Components</a>. Specifically, I'm implementing a Room Database that returns a <code>LiveData</code> object on one of its queries. Insertion and querying work as expected, however I have an issue testing the query method using a unit test.</p>
<p>Here is the DAO I'm trying to test:</p>
<p><strong>NotificationDao.kt</strong></p>
<pre><code>@Dao
interface NotificationDao {

    @Insert
    fun insertNotifications(vararg notifications: Notification): List&lt;Long&gt;

    @Query(&quot;SELECT * FROM notifications&quot;)
    fun getNotifications(): LiveData&lt;List&lt;Notification&gt;&gt;
}
</code></pre>
<p>As you can tell, the query function returns a <code>LiveData</code> object, if I change this to be just a <code>List</code>, <code>Cursor</code>, or basically whatever then I get the expected result, which is the data inserted in the Database.</p>
<p>The issue is that the following test will always fail because the <code>value</code> of the <code>LiveData</code> object is always <code>null</code>:</p>
<p><strong>NotificationDaoTest.kt</strong></p>
<pre><code>lateinit var db: SosafeDatabase
lateinit var notificationDao: NotificationDao

@Before
fun setUp() {
    val context = InstrumentationRegistry.getTargetContext()
    db = Room.inMemoryDatabaseBuilder(context, SosafeDatabase::class.java).build()
    notificationDao = db.notificationDao()
}

@After
@Throws(IOException::class)
fun tearDown() {
    db.close()
}

@Test
fun getNotifications_IfNotificationsInserted_ReturnsAListOfNotifications() {
    val NUMBER_OF_NOTIFICATIONS = 5
    val notifications = Array(NUMBER_OF_NOTIFICATIONS, { i -&gt; createTestNotification(i) })
    notificationDao.insertNotifications(*notifications)

    val liveData = notificationDao.getNotifications()
    val queriedNotifications = liveData.value
    if (queriedNotifications != null) {
        assertEquals(queriedNotifications.size, NUMBER_OF_NOTIFICATIONS)
    } else {
        fail()
    }
}

private fun createTestNotification(id: Int): Notification {
    //method omitted for brevity 
}
</code></pre>
<p>So the question is: <em>Does anyone knows of a better way to perform unit tests that involve LiveData objects?</em></p>
",https://stackoverflow.com/questions/44270688/unit-testing-room-and-livedata,"['android', 'unit-testing', 'kotlin', 'android-room', 'android-architecture-components']",22821,TRUE,69,6
angular 4 unit testing error `TypeError: ctor is not a constructor`,"<p>I am trying to test my route resolver and while testing I got <code>TypeError: ctor is not a constructor</code> and no idea why it happen while typescript compile time no error.</p>

<pre><code>TypeError: ctor is not a constructor
TypeError: ctor is not a constructor
    at _createClass (http://localhost:9877/_karma_webpack_/vendor.bundle.js:42355:26)
    at _createProviderInstance$1 (http://localhost:9877/_karma_webpack_/vendor.bundle.js:42330:26)
    at resolveNgModuleDep (http://localhost:9877/_karma_webpack_/vendor.bundle.js:42315:17)
    at _createClass (http://localhost:9877/_karma_webpack_/vendor.bundle.js:42362:26)
    at _createProviderInstance$1 (http://localhost:9877/_karma_webpack_/vendor.bundle.js:42330:26)
    at resolveNgModuleDep (http://localhost:9877/_karma_webpack_/vendor.bundle.js:42315:17)
    at NgModuleRef_.webpackJsonp../node_modules/@angular/core/@angular/core.es5.js.NgModuleRef_.get (http://localhost:9877/_karma_webpack_/vendor.bundle.js:43401:16)
    at TestBed.webpackJsonp../node_modules/@angular/core/@angular/core/testing.es5.js.TestBed.get (http://localhost:9877/_karma_webpack_/vendor.bundle.js:48412:47)
    at http://localhost:9877/_karma_webpack_/vendor.bundle.js:48418:61
    at Array.map (native)
</code></pre>
",https://stackoverflow.com/questions/44597532/angular-4-unit-testing-error-typeerror-ctor-is-not-a-constructor,"['angular', 'karma-runner', 'angular-routing']",37018,TRUE,97,5
Angular 2 unit testing - @ViewChild is undefined,"<p>I am writing an Angular 2 unit test. I have a <code>@ViewChild</code> subcomponent that I need to recognize after the component initializes. In this case it's a <code>Timepicker</code> component from the ng2-bootstrap library, though the specifics shouldn't matter. After I <code>detectChanges()</code> the subcomponent instance is still undefined.</p>
<p>Pseudo-code:</p>
<pre class=""lang-js prettyprint-override""><code>@Component({
    template: `
        &lt;form&gt;
            &lt;timepicker
                #timepickerChild
                [(ngModel)]=&quot;myDate&quot;&gt;
            &lt;/timepicker&gt;
        &lt;/form&gt;
    `
})
export class ExampleComponent implements OnInit {
    @ViewChild('timepickerChild') timepickerChild: TimepickerComponent;
    public myDate = new Date();
}
    
// Spec
describe('Example Test', () =&gt; {
    let exampleComponent: ExampleComponent;
    let fixture: ComponentFixture&lt;ExampleComponent&gt;;

    beforeEach(() =&gt; {
        TestBed.configureTestingModel({
            // ... whatever needs to be configured
        });
        fixture = TestBed.createComponent(ExampleComponent);
    });

    it('should recognize a timepicker'. async(() =&gt; {
        fixture.detectChanges();
        const timepickerChild: Timepicker = fixture.componentInstance.timepickerChild;
        console.log('timepickerChild', timepickerChild)
    }));
});
</code></pre>
<p>The pseudo-code works as expected until you reach the console log. The <code>timepickerChild</code> is undefined. Why is this happening?</p>
",https://stackoverflow.com/questions/42724179/angular-2-unit-testing-viewchild-is-undefined,"['unit-testing', 'angular', 'angular2-template', 'ng2-bootstrap']",47909,TRUE,60,7
Realm Unit Testing,"<p>I am trying to unit test Realm and its interactions but things are not going too well. I have included all dependencies and keep getting vague failures, below is my code for the <code>Helper</code> class which is a wrapper over <code>Realm</code>. </p>

<p>Questions</p>

<ol>
<li><p>Is this the correct way of testing Realm?</p></li>
<li><p>How can I test data that is in the app's sandbox, can that data only be tested by UI/Instrumentation tests?</p></li>
<li><p>I am getting an error currently (below) and before I was getting a ""Powermock zero args constructor doesn't exist""</p></li>
</ol>

<p><a href=""https://github.com/Zohaib-AHussain/RealmUnitTesting"" rel=""noreferrer"">GitHub repo</a></p>

<p>Below is the current code I have for my Unit test:</p>

<pre><code>@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21, application = CustomApplicationTest.class)
@PowerMockIgnore({""org.mockito.*"", ""org.robolectric.*"", ""android.*"", ""javax.crypto."",""java.security.*""})
@SuppressStaticInitializationFor(""io.realm.internal.Util"")
@PrepareForTest({Realm.class, RealmConfiguration.class,
    RealmQuery.class, RealmResults.class, RealmCore.class, RealmLog.class})
public class DatabaseHelperTest {

@Rule
public PowerMockRule rule = new PowerMockRule();

private DatabaseHelper dB;

private Realm realmMock;


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

    mockStatic(Realm.class);
    mockStatic(RealmConfiguration.class);
    mockStatic(RealmCore.class);
    mock(DatabaseHelper.class);

    final Realm mockRealm = PowerMockito.mock(Realm.class);
    realmMock = mockRealm;

    final RealmConfiguration mockRealmConfig = PowerMockito.mock(RealmConfiguration.class);

    doNothing().when(RealmCore.class);
    RealmCore.loadLibrary(any(Context.class));

    whenNew(RealmConfiguration.class).withAnyArguments().thenReturn(mockRealmConfig);
    when(Realm.getInstance(any(RealmConfiguration.class))).thenReturn(mockRealm);
    when(Realm.getDefaultInstance()).thenReturn(mockRealm);

    when(Realm.getDefaultInstance()).thenReturn(realmMock);

    when(realmMock.createObject(Person.class)).thenReturn(new Person());

    Person person = new Person();
    person.setId(""2"");
    person.setName(""Jerry"");
    person.setAge(""25"");

    Person person2 = new Person();
    person.setId(""3"");
    person.setName(""Tom"");
    person.setAge(""22"");

    List&lt;Person&gt; personsList = new ArrayList&lt;&gt;();
    personsList.add(person);
    personsList.add(person2);

    RealmQuery&lt;Person&gt; personRealmQuery = mockRealmQuery();
    when(realmMock.where(Person.class)).thenReturn(personRealmQuery);

    RealmResults&lt;Person&gt; personRealmResults = mockRealmResults();
    when(realmMock.where(Person.class).findAll()).thenReturn(personRealmResults);
    when(personRealmResults.iterator()).thenReturn(personsList.iterator());
    when(personRealmResults.size()).thenReturn(personsList.size());

    when(realmMock.copyFromRealm(personRealmResults)).thenReturn(personsList);

    realmMock = mockRealm;
    dB = new DatabaseHelper(realmMock);
}


@Test
public void insertingPerson(){
    doCallRealMethod().when(realmMock).executeTransaction(any(Realm.Transaction.class));

    Person person = mock(Person.class);
    when(realmMock.createObject(Person.class)).thenReturn(person);

    dB.putPersonData();

    verify(realmMock, times(1)).createObject(Person.class);
    verify(person, times(1)).setId(anyString());
}


@Test
public void testExistingData(){
    List&lt;Person&gt; personList = dB.getPersonList();
    //NPE if checking person object properties i.e name, id. Only list size is available why?
    Assert.assertEquals(2, personList.size());

}

@SuppressWarnings(""unchecked"")
private &lt;T extends RealmObject&gt; RealmQuery&lt;T&gt; mockRealmQuery() {
    return mock(RealmQuery.class);
}

@SuppressWarnings(""unchecked"")
private &lt;T extends RealmObject&gt; RealmResults&lt;T&gt; mockRealmResults() {
    return mock(RealmResults.class);
}
</code></pre>

<p>Error:</p>

<pre><code>org.mockito.exceptions.misusing.NotAMockException: 
Argument passed to verify() is of type Realm$$EnhancerByMockitoWithCGLIB$$317bc746 and is not a mock!
Make sure you place the parenthesis correctly!
See the examples of correct verifications:
verify(mock).someMethod();
verify(mock, times(10)).someMethod();
verify(mock, atLeastOnce()).someMethod();

at com.appstronomy.realmunittesting.db.DatabaseHelperTest.insertingPerson(DatabaseHelperTest.java:133)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
</code></pre>
",https://stackoverflow.com/questions/42195245/realm-unit-testing,"['android', 'unit-testing', 'mockito', 'realm', 'powermockito']",10496,TRUE,10,2
Unit testing a Kotlin coroutine with delay,"<p>I'm trying to unit test a Kotlin coroutine that uses <code>delay()</code>. For the unit test I don't care about the <code>delay()</code>, it's just slowing the test down. I'd like to run the test in some way that doesn't actually delay when <code>delay()</code> is called.</p>

<p>I tried running the coroutine using a custom context which delegates to CommonPool:</p>

<pre><code>class TestUiContext : CoroutineDispatcher(), Delay {
    suspend override fun delay(time: Long, unit: TimeUnit) {
        // I'd like it to call this
    }

    override fun scheduleResumeAfterDelay(time: Long, unit: TimeUnit, continuation: CancellableContinuation&lt;Unit&gt;) {
        // but instead it calls this
    }

    override fun dispatch(context: CoroutineContext, block: Runnable) {
        CommonPool.dispatch(context, block)
    }
}
</code></pre>

<p>I was hoping I could just return from my context's <code>delay()</code> method, but instead it's calling my <code>scheduleResumeAfterDelay()</code> method, and I don't know how to delegate that to the default scheduler.</p>
",https://stackoverflow.com/questions/47171302/unit-testing-a-kotlin-coroutine-with-delay,"['android', 'unit-testing', 'kotlin', 'android-testing', 'kotlin-coroutines']",30121,TRUE,43,4
Xamarin Forms Unit Testing,"<p>What is the approach to write unit tests for Xamarin Forms application (as opposed to Xamarin Traditional which is Xamarin.Android, Xamarin.IOS, or Xamarin.UWP)?</p>

<p>Can anyone provide a good explanation for Unit Tests in Xamarin.Forms vs Unit Tests in Xamarin Traditional?</p>

<p>A good explanation article how to implement Xamarin.Forms tests and are they even needed or should we write Unit Tests for each platform instead?</p>

<p>I have read a number of articles out there but I haven't found one that starts from creating the unit test project type in Visual Studio to writing and running the tests.  </p>

<p>They mostly start somewhere in the middle discussing DI or ServiceLocator (like this one <a href=""http://arteksoftware.com/unit-testing-with-xamarin-forms-dependencyservice/"" rel=""noreferrer"">http://arteksoftware.com/unit-testing-with-xamarin-forms-dependencyservice/</a>).  </p>

<p>Or, on the other hand, they mix Xamarin.Forms with Xamarin.Android (or IOS) unit testing (like this one: <a href=""http://www.dsibinski.pl/2017/03/unit-testing-xamarin-application/"" rel=""noreferrer"">http://www.dsibinski.pl/2017/03/unit-testing-xamarin-application/</a>).</p>

<p>Or, they mix Portable vs Shared like in the case of this one <a href=""http://www.alteridem.net/2015/12/21/testing-xamarin-projects-using-nunit-3/"" rel=""noreferrer"">http://www.alteridem.net/2015/12/21/testing-xamarin-projects-using-nunit-3/</a>.</p>

<p>What I understand so far is that I could use regular Unit Test project in VS and use either MSTest or NUnit.  Or, I can write platform specific unit tests for each platform.</p>

<p>All of this is very confusing because authors seem to mix the terms all over the place.</p>

<p>A detailed answer with supporting examples would be highly appreciated as I am entirely a beginner in this area.</p>
",https://stackoverflow.com/questions/44873933/xamarin-forms-unit-testing,"['c#', 'unit-testing', 'visual-studio-2015', 'xamarin.forms']",14314,TRUE,14,2
Unit testing React click outside component,"<p>Using the code from <a href=""https://stackoverflow.com/a/42234988/766958"">this answer</a> to solve clicking outside of a component:</p>

<pre><code>componentDidMount() {
    document.addEventListener('mousedown', this.handleClickOutside);
}

componentWillUnmount() {
    document.removeEventListener('mousedown', this.handleClickOutside);
}

setWrapperRef(node) {
    this.wrapperRef = node;
}

handleClickOutside(event) {
    if (this.wrapperRef &amp;&amp; !this.wrapperRef.contains(event.target)) {
        this.props.actions.something() // Eg. closes modal
    }
}
</code></pre>

<p>I can't figure out how to unit test the unhappy path so the alert isn't run, what i've got so far:</p>

<pre><code>it('Handles click outside of component', () =&gt; {
  props = {
    actions: {
      something: jest.fn(),
    }
  }
  const wrapper = mount(
    &lt;Component {... props} /&gt;,
  )
  expect(props.actions.something.mock.calls.length).toBe(0)

  // Happy path should trigger mock

  wrapper.instance().handleClick({
    target: 'outside',
  })

  expect(props.actions.something.mock.calls.length).toBe(1)  //true

  // Unhappy path should not trigger mock here ???

  expect(props.actions.something.mock.calls.length).toBe(1)
})
</code></pre>

<p>I've tried:</p>

<ul>
<li>sending through <code>wrapper.html()</code></li>
<li><code>.find</code>ing a node and sending through (doesn't mock a <code>event.target</code>)</li>
<li><code>.simulate</code>ing <code>click</code> on an element inside (doesn't trigger event listener)</li>
</ul>

<p>I'm sure i'm missing something small but I couldn't find an example of this anywhere.</p>
",https://stackoverflow.com/questions/45046728/unit-testing-react-click-outside-component,"['javascript', 'unit-testing', 'reactjs', 'jestjs', 'enzyme']",28164,TRUE,31,5
Correct unit testing,"<p>I started using unit and functionality test with this project and because of this I have some questions:</p>

<p>Im working with the symfony php framework. And I have a doctrine like LDAP ORM service.</p>

<p>Furthermore I have a user repository (as a service) which depends on the LDAP ORM service, the logger and a validation service.</p>

<p>Now I want to write a unit test for the addUser function of the UserRepo.
It will internally call: getNewUidNumber, userToEntities, doesUserExist and getUserByUid.</p>

<p>My question is:
Should I mock all these internal function to just test the addUser function? Would that be against the unit test idea (just test the API).</p>

<p>Or should I just mock the LDAP ORM service, the Logger, and the validation  service, so that the class calls all internal functions? But this would cause a huge test function with a lot of mocking because I have to mock the repositories for all internal repositories calls.</p>

<p>Or should I start the symfony kernel and use the ServiceContainer to use the ORM LDAP service with a real test database. But wouldn't that be a functionally test and not a unit test?
I heard that its bad to have so many dependencies in a test. So I thought it would be bad to use the whole serviceContainer.</p>

<p>Adduser:</p>

<pre><code>public function addUser(User $user)
{
    $pbnlAccount = $this-&gt;userToEntities($user);

    if(!$this-&gt;doesUserExist($user)) {
        $pbnlAccount-&gt;setUidNumber($this-&gt;getNewUidNumber());
        $this-&gt;ldapEntityManager-&gt;persist($pbnlAccount);
        $this-&gt;ldapEntityManager-&gt;flush();
    }
    else {
        throw new UserAlreadyExistException(""The user "".$user-&gt;getUid()."" already exists."");
    }

    return $this-&gt;getUserByUid($user-&gt;getUid());
}
</code></pre>

<p>For more code, like the internal functions:
<a href=""https://gist.github.com/NKPmedia/4a6ee55b6bb96e8af409debd98950678"" rel=""nofollow noreferrer"">https://gist.github.com/NKPmedia/4a6ee55b6bb96e8af409debd98950678</a></p>

<p>Thanks
Paul</p>
",https://stackoverflow.com/questions/46164760/correct-unit-testing,"['php', 'symfony', 'unit-testing', 'ldap', 'phpunit']",183,TRUE,5,3
Unit testing 3dSecure,"<p>We have began working on our payment service and all was going well with the <a href=""https://developers.braintreepayments.com/reference/general/testing/php"" rel=""nofollow noreferrer"">test nonces that Braintree supply</a></p>

<p>We've been using <code>fake-valid-nonce</code> all over the place for our transactions however, we now need to implement 3dsecure which has 0 test nonces meaning all of our tests fail with a <code>Gateway Rejected: three_d_secure</code> error.</p>

<p>Has anyone had any experience with heavy unit testing of Braintree?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/43659532/unit-testing-3dsecure,['braintree'],829,TRUE,4,1
Unit testing Firebase,"<p>I am trying to write unit tests for methods that load and add data from Firebase DB. I have not found any resources to help me with this. can someone point me to a resource or post a sample code? for example, this is my load method</p>

<pre><code>    public ArrayList getGroceryData(final String type) {
   tempBuilder=new ArrayList&lt;&gt;();
     test=false;
    databaseReference.child(""Tasks"").child(type).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                for (DataSnapshot d : dataSnapshot.getChildren()) {
                    tempBuilder.add(d.getValue(Task.class));
                }

                test=true;
               // Dashboard.populatefeed(tempBuilder);
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {

        }

    });

    while(!test);
    test=false;
    return tempBuilder;



}
</code></pre>
",https://stackoverflow.com/questions/44252180/unit-testing-firebase,"['android', 'unit-testing', 'firebase', 'firebase-realtime-database']",660,FALSE,4,0
Angular 2 JWT Unit Testing,"<p>My API calls are authenticated with JWT. I am trying to write code for a service method. All requests has this interceptor:</p>

<pre><code>public interceptBefore(request: InterceptedRequest): InterceptedRequest {
        // Do whatever with request: get info or edit it
        this.slimLoadingBarService.start();
        let currentUser = JSON.parse(localStorage.getItem('currentUser'));
        if (currentUser &amp;&amp; currentUser.data.token) {
            request.options.headers.append('Authorization', 'Bearer ' + currentUser.data.token);
        }
        return request;
    }
</code></pre>

<p>Service method that I want to test:</p>

<pre><code>getAll(page: number, pageSize: number, company: string): Observable&lt;any&gt; {
        return this.http.get(`${this.conf.apiUrl}/jobs`)
            .map((response: Response) =&gt; response.json());
    }
</code></pre>

<p>Started the code for it:</p>

<pre><code>import { MockBackend, MockConnection } from '@angular/http/testing';
import { Http, BaseRequestOptions, Response, ResponseOptions, RequestMethod } from '@angular/http';
import { JobListService } from './job-list.service';
import { inject, TestBed } from '@angular/core/testing/test_bed';
import { JOBLISTMOCK } from '../mocks/job-list.mock';

fdescribe('Service: JobListService', () =&gt; {
    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            providers: [
                JobListService,
                MockBackend,
                BaseRequestOptions,
                {
                    provide: Http,
                    useFactory: (backend: MockBackend, defaultOptions: BaseRequestOptions) =&gt; {
                        return new Http(backend, defaultOptions);
                    },
                    deps: [MockBackend, BaseRequestOptions]
                },
            ]
        });
    });

    it('should create a service', inject([JobListService], (service: JobListService) =&gt; {
        expect(service).toBeTruthy();
    }));

    describe('getAll', () =&gt; {
        it('should return jobs', inject([JobListService, MockBackend], (service: JobListService, backend: MockBackend) =&gt; {
            let response = new ResponseOptions({
                body: JSON.stringify(JOBLISTMOCK)
            });

            const baseResponse = new Response(response);

            backend.connections.subscribe(
                (c: MockConnection) =&gt; c.mockRespond(baseResponse)
            );

            return service.getAll(1, 10, '18').subscribe(data =&gt; {
                expect(data).toEqual(JOBLISTMOCK);
            });
        }));
    });
});
</code></pre>

<p>Do not know how to test it against the interceptor.</p>

<p>PS: As the tests are now, getting an error:</p>

<pre><code>1) should create a service
     JobListService
     TypeError: null is not an object (evaluating 'this.platform.injector') in src/test.ts (line 83858)
_createCompilerAndModule@webpack:///~/@angular/core/testing/test_bed.js:254:0 &lt;- src/test.ts:83858:44

2) should return jobs
     JobListService getAll
     TypeError: null is not an object (evaluating 'this.platform.injector') in src/test.ts (line 83858)
_createCompilerAndModule@webpack:///~/@angular/core/testing/test_bed.js:254:0 &lt;- src/test.ts:83858:44
</code></pre>
",https://stackoverflow.com/questions/42151194/angular-2-jwt-unit-testing,"['javascript', 'angular', 'jasmine', 'karma-jasmine']",2793,TRUE,20,1
Unit testing HttpInterceptor from Angular 4,"<p>Can you tell me how to test the HttpInterceptor provided by the Angular 4. I have created an interceptor as per the examples but not sure how to test it. Below is my interceptor and I want to test if the custom headers are added and when response status is 401 <code>window.location.href</code> is done.</p>

<pre><code>export class MyInterceptor implements HttpInterceptor {

    intercept(req: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
        const headers = new HttpHeaders();
        this.addHeader(headers); // This will add headers

        const changedReq = req.clone({ headers: headers });
        return next.handle(req)
            .catch(err =&gt; {
                if (err instanceof HttpErrorResponse) {
                    switch (err.status) {
                        case 302:
                        case 401:
                            window.location.href = ""http//google.com"";
                            break;             
                        default:
                            throw new Error(this.getErrorMessage(err));
                    }
                }

                return Observable.throw(err);
            });
    }
</code></pre>
",https://stackoverflow.com/questions/46225164/unit-testing-httpinterceptor-from-angular-4,['angular'],25929,TRUE,27,5
Basic unit testing,"<p>I'm an experienced programmer but new to HDL. I'm trying to figure out how to implement basic unit testing for my hardware designs for a class I'm taking. I'm aware of SVUnit, but I need to submit the code so I would prefer to just implement the barebones testing functionality myself. This will also help me learn more.</p>
<p>I'm having trouble figuring out what language constructs to use. All I really need to do is instantiate a component, drive the inputs, then verify the output values. The verification is where I'm stuck. Does that need to go into an always block?</p>
<p>Even pointing me in the right direction for what terms I should be googling would be very helpful. So far I've tried: verilog modelsim unit testing, verilog modelsim self-checking testbench, etc without too much success.</p>
<p>EDIT: Example:
Let's say I have a design for a 1 bit half adder. How would I write a testbench to exercise every possible input combination, and automatically verify that the output is correct?</p>
",https://stackoverflow.com/questions/44270377/basic-unit-testing,['verilog'],1034,FALSE,1,1
Unit testing HttpResponseMessage,"<p>I'm trying to unit test some of my web services. For this, I want to assert some of my <code>HttpResponseMessage</code>s. For this, I'm doing:</p>

<pre><code>[TestMethod()]
public void LoginTest()
{
    HttpResponseMessage response = Request.CreateResponse(_accountController.Login(""testuser"", ""testpw"")); //CODE STOPS RUNNING AT THIS LINE
    Assert.IsTrue(response.IsSuccessStatusCode, ""User unable to log in with correct login info"");
}
</code></pre>

<p>Where <code>Login</code> is a method like:</p>

<pre><code>public IHttpActionResult Login(String userName, String userPassword)
{
    try
    {
        if (userName == null)
            return NotFound();
        //Logging in user etc.
        return Ok();
    }
    catch
    {
        return NotFound();
    }
}
</code></pre>

<p>However, the test always return as failed, even though the <code>Login()</code> returns <code>Ok()</code> when I debug. No apparent errors or exceptions, however, when I debug the test, the output shows things like (I've excluded lines that just show what's <code>Loaded</code> or <code>Unloaded</code>):</p>

<pre><code>The thread 0x1190 has exited with code 0 (0x0).
Exception thrown: 'System.InvalidOperationException' in System.ServiceModel.dll
Exception thrown: 'System.ArgumentNullException' in System.Web.Http.dll
Exception thrown: 'System.Reflection.TargetInvocationException' in mscorlib.dll
Exception thrown: 'Microsoft.VisualStudio.TestPlatform.MSTestFramework.TestFailedException' in Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.dll
Exception thrown: 'Microsoft.VisualStudio.TestPlatform.MSTestFramework.TestFailedException' in Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.dll
The thread 0xaec has exited with code 0 (0x0).
Exception thrown: 'System.InvalidOperationException' in Microsoft.VisualStudio.TestPlatform.TestExecutor.Core.dll
Exception thrown: 'System.ServiceModel.CommunicationObjectAbortedException' in System.ServiceModel.dll
Exception thrown: 'System.ServiceModel.CommunicationObjectAbortedException' in System.ServiceModel.dll
Exception thrown: 'System.ServiceModel.CommunicationObjectAbortedException' in System.ServiceModel.Internals.dll
Exception thrown: 'System.IO.IOException' in System.dll
Exception thrown: 'System.ServiceModel.CommunicationObjectAbortedException' in System.ServiceModel.dll
Exception thrown: 'System.InvalidOperationException' in Microsoft.VisualStudio.TestPlatform.TestExecutor.Core.dll
Exception thrown: 'System.ServiceModel.CommunicationObjectAbortedException' in System.ServiceModel.dll
The program '[9936] vstest.executionengine.x86.exe' has exited with code 0 (0x0).
The program '[4084] TanulmanyiRendszer.Admin.vshost.exe' has exited with code -1 (0xffffffff).
</code></pre>

<p>My guess is that this is not the way you're supposed to convert the <code>IHttpActionResult</code> to <code>HttpResponseMessage</code>. How can I fix this issue?</p>
",https://stackoverflow.com/questions/44095109/unit-testing-httpresponsemessage,"['c#', 'web-services', 'unit-testing', 'asp.net-web-api']",2156,TRUE,1,1
Unit Testing a BroadcastReceiver,"<p>I've been trying to figure out how to unit test my BroadcastReceiver and I have looked at StackOverflow and other websites but I can't find the solution to my problem.</p>

<p>In my mainActivity I have the following two functions:</p>

<pre><code>private void registerNetRcvr(){

    if (!isRcvrRegistered) {        
        isRcvrRegistered = true;
        registerReceiver(receiver, new IntentFilter(""android.net.wifi.STATE_CHANGE""));
        registerReceiver(receiver, new IntentFilter(""android.net.conn.CONNECTIVITY_CHANGE""));
    }
}

private BroadcastReceiver receiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {

        NetworkHandler.NetworkInfo netInfo = NetworkHandler.handleBcastReceiver(context);

        if (netInfo!=null){
            handleInfoChange(netInfo);
        } else {
            handleInfoChange(null);
        }
    }
};
</code></pre>

<p>The registerNetRcvr is called from within the onResume function (and equally I have an unregister called from onPause).</p>

<p>As can be seen from the above, I have a function (handleBcastReceiver) that is called to handle the onReceive event and thus have another class that then has a variety of private functions which are called from this function.</p>

<p>Just to slightly complicate matters... upon the onReceive function being called, as detailed above the 'handleBcastReceiver' function would then need to 'retreive' the correct data... and, as such would make a call to actually retrieve the appropriate system data as follows:</p>

<pre><code>private static NetworkInfo getWiFiNetworkInfo(Context context) {

    ConnectivityManager connManager = (ConnectivityManager)
            context.getSystemService(Context.CONNECTIVITY_SERVICE);
    return connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
}
</code></pre>

<p>I believe that I should emulate the behaviour of the onReceive callback but also I guess emulate what would be returned from the system during the call to getWiFiNetworkInfo.</p>

<p>My thinking is that I should be using RoboElectric to do this as it can shadow the BroadcastReceiver/ConnectivityManager. I've also looked at Mockito however I believe that RoboElectric is what I require for this but I accept that I could well be wrong. As far as I'm aware, RoboElectric allows me to emulate 'the Android system' and Mockito would allow me to mock my own classes.</p>

<p>At present I just can't see how to test the BroadcastReceiver. Additionally I'm not clear upon whether I should be running the emulator to do this or simply 'run' my unit test as the 'shadow' should contain everything I need. Finally, if I was to shadow the BroadcastReceiver, how do I get WIFI to be 'enabled' or 'disabled' through this shadow process? In fact, should I be emulating a BroadcastReceiver or just the ConnectivityManager... I'm genuinely confused!</p>

<p>What I have done so far is to create a BroadcastReceiverTest class within the test section of my app (not the 'androidTest' section). I can do normal simple unit tests on functions, I'm just stuck with how to emulate this 'system' behaviour. </p>

<p>As always, any help is greatly appreciated.</p>
",https://stackoverflow.com/questions/41673085/unit-testing-a-broadcastreceiver,"['android', 'unit-testing', 'mockito', 'robolectric', 'android-broadcastreceiver']",10425,TRUE,9,1
Unit Testing socket.io in Angular,"<p>I am trying to unit test an angular service in my application, which creates socket.io client. My service looks something like this:</p>

<pre><code>export class SocketService {
  private name: string;
  private host: string = window.location.protocol + ""//"" + window.location.hostname + "":3000"";
  socket: io.Socket;

  constructor() { }

  subscribeEvent(name: string): Observable&lt;IJobResp&gt; {
    this.setup(name);
    return new Observable(observer =&gt; {
      this.socket.on('job', val =&gt; observer.next(val))
    })
  }

  private setup(name: string) {
    this.name = name;
    let socketUrl = this.host + ""/"" + this.name;
    this.socket = io.connect(socketUrl);
  }
}
</code></pre>

<p>So to write my test, I am using the mock-socket library to set up a mock socket.io server. Here is what the test looks like:</p>

<pre><code>describe('SocketService', () =&gt; {
  let socket;

  const mockServer = new Server('http://localhost:3000/');
  mockServer.on('connection', server =&gt; {
    mockServer.emit('job', 'test message 1');
  });

  (window as any).io = SocketIO;
  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      providers: [JobService]
    });
  });

  it('should xyz, inject([JobService], fakeAsync((service: JobService) =&gt; {
    service.subscribeEvent('/').subscribe(val =&gt; {
      expect(val).toEqual('test message 1');
    })
  })));
});
</code></pre>

<p>However, that test throws the error:</p>

<blockquote>
  <p>Error: Cannot make XHRs from within a fake async test.</p>
</blockquote>

<p>If I don't have the <code>fakeAsync</code>, then the test passes before the assertion in the <code>subscribe()</code> is processed. </p>

<p>How do I get around this?</p>

<h1>Update:</h1>

<p>Another approach I have tried is to use <code>async</code> e.g.</p>

<pre><code>  it('should subscribe to dwnTime events', async(inject([JobService], (service: JobService) =&gt; {
    service.subscribeEvent('line/602').subscribe(val =&gt; {
      expect(val).toEqual('test 2');
    })
  })));
</code></pre>

<p>Then I get:</p>

<blockquote>
  <p>Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.</p>
</blockquote>

<p>This looks like a timing issue, but I still am not sure why?</p>
",https://stackoverflow.com/questions/44656279/unit-testing-socket-io-in-angular,"['angular', 'unit-testing', 'typescript', 'socket.io', 'jasmine']",3221,TRUE,17,1
Unit testing an agent,"<p>I am trying to test a MailboxProcessor in F#. I want to test that the function f I am giving is actually executed when posting a message.</p>

<p>The original code is using Xunit, but I made an fsx of it that I can execute using fsharpi.</p>

<p>So far I am doing this :</p>

<pre><code>open System 
open FSharp
open System.Threading
open System.Threading.Tasks



module MyModule =

    type Agent&lt;'a&gt; = MailboxProcessor&lt;'a&gt;
    let waitingFor timeOut (v:'a)= 
        let cts = new CancellationTokenSource(timeOut|&gt; int)
        let tcs = new TaskCompletionSource&lt;'a&gt;()
        cts.Token.Register(fun (_) -&gt;  tcs.SetCanceled()) |&gt; ignore
        tcs ,Async.AwaitTask tcs.Task

    type MyProcessor&lt;'a&gt;(f:'a-&gt;unit) =
        let agent = Agent&lt;'a&gt;.Start(fun inbox -&gt; 
             let rec loop() = async {

                let! msg = inbox.Receive()
                // some more complex should be used here
                f msg
                return! loop() 
             }
             loop()
        )

        member this.Post(msg:'a) = 
            agent.Post msg


open MyModule

let myTest =
    async {

        let (tcs,waitingFor) = waitingFor 5000 0

        let doThatWhenMessagepostedWithinAgent msg =
            tcs.SetResult(msg)

        let p = new MyProcessor&lt;int&gt;(doThatWhenMessagepostedWithinAgent)

        p.Post 3

        let! result = waitingFor

        return result

    }

myTest 
|&gt; Async.RunSynchronously
|&gt; System.Console.WriteLine 

//display 3 as expected
</code></pre>

<p>This code works, but it does not look fine to me.</p>

<p>1) is the usage of TaskCompletionSource normal in f# or is  there some dedicated stuff to allow me waiting for a completion?</p>

<p>2) I am using a second argument in the waitingFor function in order to contraint it, I know I could use a type MyType&lt;'a>() to do it, is there another option? I would rather not use a new MyType that I find cumbersome.</p>

<p>3) Is there any other option to test my agent than doing this? the only post I found so far about the subject is this blogpost from 2009 <a href=""http://www.markhneedham.com/blog/2009/05/30/f-testing-asynchronous-calls-to-mailboxprocessor/"">http://www.markhneedham.com/blog/2009/05/30/f-testing-asynchronous-calls-to-mailboxprocessor/</a></p>
",https://stackoverflow.com/questions/41662991/unit-testing-an-agent,"['unit-testing', 'f#', 'mailboxprocessor']",263,TRUE,9,1
Angular2 subject unit testing,"<p>How can I unit test (jasmine) subject.next() in angular2 service?</p>

<p>I am using subject to pass data to its observer written in component after my http call is done. </p>
",https://stackoverflow.com/questions/42455257/angular2-subject-unit-testing,"['angular', 'jasmine']",1205,TRUE,8,1
Unit testing strategy,"<p>I have to admit I'm quite new to unit testing and there is a lot questions for me. 
It's hard to name it but I think it's behaviour test, anyways let me go straight to the example:</p>

<p>I need to test users roles listing to make sure that my endpoint is working correctly and returns all user roles assigned to him.</p>

<p>That means:</p>

<ul>
<li>I need to create user</li>
<li>I need to create role</li>
<li>I need to assign created role to created user</li>
</ul>

<p>As we can see there is three operations that must be excecuted before actual test and I believe that in larger applications such list can grow to much larger number of operations and even complex.</p>

<p>The question is how I should test such endpoints: should I just insert raw data to DB, write some code blocks that would do such preparations.</p>
",https://stackoverflow.com/questions/45669198/unit-testing-strategy,"['rest', 'unit-testing', 'web-api-testing']",28,FALSE,0,1
Unit testing main.py,"<p>Given a simple Flask app in <code>main.py</code>:</p>

<pre><code>from flask import Flask
app = Flask(__name__)

@app.route('/')
def hi():
    return 'hi', 200
</code></pre>

<p>I want to write a unit test for it, but I'm not sure how to import <code>main.py</code> into <code>test.py</code>. I get <code>NameError: name 'app' is not defined</code> for the code below.</p>

<pre><code>import unittest

class MyTestCase(unittest.TestCase):

    def test_hi(self):
        self.app = app.test_client()
        r = self.app.get('/')
        assert b'hi' in r.data
</code></pre>

<p>Is there a way to write this test while keeping the same directory structure (basically <code>main.py</code> and <code>test.py</code> in the same directory)?</p>
",https://stackoverflow.com/questions/42530847/unit-testing-main-py,"['python', 'unit-testing', 'flask']",1193,FALSE,0,1
Unit testing react-helmet code,"<p>I am using react-helmet to add elements to head element. </p>

<pre><code>&lt;Helmet&gt;
     &lt;title&gt;title&lt;/title&gt;
     &lt;meta name=""description"" content=""description"" /&gt;
     &lt;meta name=""keywords"" content=""keywords"" /&gt;
&lt;/Helmet&gt;
</code></pre>

<p>And I am trying to write unit test like this:</p>

<pre><code>it('should render metadata', () =&gt; {
    const wrapper = mount(&lt;Metadata/&gt;);
    // this is not working.
    expect(document.title).to.equal(""title"");
});
</code></pre>
",https://stackoverflow.com/questions/44073960/unit-testing-react-helmet-code,"['javascript', 'unit-testing', 'reactjs', 'react-helmet']",6654,TRUE,15,4
Unit Testing Redux Sagas,"<p>I've followed the documentation for Redux Sagas and created a set of tests, however they seem extremely brittle to me. Whenever I update the logic in any of my sagas, my tests fail. This raises alarm bells in my head and leads me to think that I'm doing something wrong.</p>

<p>Here's an example saga which communicates with an API to load a user's profile and store it in the Redux state:</p>

<pre><code>export function* userAuthCheck() {
    try {
        yield put({ type: START_HTTP });

        const me = yield apply(user, user.me);
        const organisations = yield apply(user, user.organisations, [me.body.data.id]);

        yield put({
            type: USER_AUTH_SUCCESS,
            redirect: true,
            state: {
                account: me.body.data,
                organisations: organisations.body.data,
            },
        });
    } catch (error) {
        yield put({ type: USER_AUTH_REFRESH });
    } finally {
        yield put({ type: COMPLETE_HTTP });
    }
}
</code></pre>

<p>Here's the corresponding test:</p>

<pre><code>it('can successfully call the API', () =&gt; {
    const generator = userAuthCheck();

    expect(generator.next().value).toEqual(put({ type: START_HTTP }));
    expect(generator.next().value).toEqual(call(user.me));

    expect(generator.next().value).toEqual(put({
        type: USER_AUTH_SUCCESS,
        state: { user: undefined },
    }));

    expect(generator.next().value).toEqual(put({ type: COMPLETE_HTTP }));
});
</code></pre>

<p>You might notice that the test will actually fail if run because I've not updated it since I made some recent updates to the saga. This is the sort of thing which started me on this trail of thought.</p>

<p>Is there a better way to test my sagas? Is it possible to run them from start to finish, mock out different API responses and assert that the right things get dispatched into state?</p>

<p>These are the docs I've been following: <a href=""https://redux-saga.github.io/redux-saga/docs/introduction/BeginnerTutorial.html"" rel=""nofollow noreferrer"">https://redux-saga.github.io/redux-saga/docs/introduction/BeginnerTutorial.html</a></p>
",https://stackoverflow.com/questions/42145176/unit-testing-redux-sagas,"['unit-testing', 'reactjs', 'testing', 'redux', 'redux-saga']",2166,TRUE,4,2
Unit Testing with SQLite3,"<p>I am writing unit tests and use SQLite3 with his inmemory mode.</p>

<p>I am doing this because i need is a fresh database for each test so i can run tests in parallel without affecting each other. </p>

<p>But this gets, off course, slower and slower the more tests i have.</p>

<p><strong>Are there any optimisations i can do with sqlite3, another better workflow (e.g. a good mocking library) or another solution do this problem? I need to run raw queries.</strong></p>

<p>Currently i use knexjs but this is related to allmost every data access library.</p>
",https://stackoverflow.com/questions/47439822/unit-testing-with-sqlite3,"['node.js', 'sqlite', 'sequelize.js', 'knex.js', 'bookshelf.js']",4928,TRUE,4,1
Angular 2 unit testing - getting error Failed to load &#39;ng:///DynamicTestModule/module.ngfactory.js&#39;,"<p>I have angular 2 webpack application, all webpack,karma configuration created as per angular.io webpack guide. 
I am not using aot.
I am writing jasmine unit test spec to test my components.
First I tried without async block, in that case , unit test just get execute only till fixture.detectChanges() call, code after that doesn't get executed. Seems like fixture.detectChanges call getting blocked infinitely.</p>

<p>I tried by including code in async block.
Then I get following error.
Error:Failed to execute 'send' on 'XMLHttpRequest' : Failed to load 'ng:///DynamicTestModule​/module.ngfactory.js'</p>

<hr>

<p>Code without async </p>

<pre><code>beforeeach(()=&gt; {
TestBed.configureTestingModule({
imports:[],
declaration :[Mycomp],
providers:[{ provide:MyService, useclass:MyMockService}]
});
 fixture=TestBed.createComponent(Mycomp);
 console.log(' before detect changes'):
 fixture.detectChanges():
 console.log('after detect changes');// this is not getting   
    logged .. karma shows 0 of 1 executed successfully

 });
</code></pre>

<hr>

<p>With async </p>

<pre><code>  beforeeach(async(()=&gt; {
 TestBed.configureTestingModule({
  imports:[],
  declaration :[Mycomp],
  providers:[{ provide:MyService,       useclass:MyMockService}]
  });
   fixture=TestBed.createComponent(Mycomp);
    fixture.detectChanges():
  }));
</code></pre>

<p>getting error Failed to load dynamictestmodule/module.ngfactory.js</p>
",https://stackoverflow.com/questions/44254758/angular-2-unit-testing-getting-error-failed-to-load-ng-dynamictestmodule-m,"['angular', 'webpack', 'karma-runner']",36849,TRUE,64,10
Unit testing Vertx - java.util.concurrent.TimeoutException,"<p>I am trying to unit test a http call from vertx <code>WebClient</code> uing <code>VertxUnitRunner</code> and RXified version of vertx. </p>

<p>The problem is my unit test always fail with a timeout exception. Is there a different way to unit test <code>WebClient</code> http calls? Below is my code:</p>

<pre><code>import io.vertx.core.AsyncResult;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import io.vertx.rxjava.core.Vertx;
import io.vertx.rxjava.core.buffer.Buffer;
import io.vertx.rxjava.core.http.HttpServer;
import io.vertx.rxjava.ext.web.client.HttpResponse;
import io.vertx.rxjava.ext.web.client.WebClient;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import rx.Single;


@RunWith(VertxUnitRunner.class)
public class MyVertxTest {

    private Vertx vertx;
    private WebClient client;

    @Before
    public void setUp() throws Exception {
        vertx = Vertx.vertx();
    }

    @Test
    public void testGetContactDetails(TestContext context) {

        System.out.println(""start"");
        long start = System.currentTimeMillis();
        HttpServer server = vertx.createHttpServer(new HttpServerOptions().setPort(TEST_SERVER_PORT));

        server.requestStream().handler(req -&gt; {
            req.response().setChunked(true).write(""foo bar"").end();
        });

        System.out.println(""created server"");

        try {
            server.listen(9000, ""localhost"", (AsyncResult&lt;HttpServer&gt; ar) -&gt; {

                client = WebClient.wrap(vertx.createHttpClient(new HttpClientOptions()));

                System.out.println(""created client"");

                Single&lt;HttpResponse&lt;Buffer&gt;&gt; single = client
                        .get(9000, ""localhost"", ""/foo"")
                        .rxSend();

                single.subscribe(s -&gt; {
                    System.out.println(""inside subscribe"");
                    context.assertEquals(""foo bar"", s.bodyAsString());
                }, e -&gt; {
                    context.fail(e);
                });
            });

            context.async().await();
            System.out.println(""total time : "" + (System.currentTimeMillis() - start / 1000)+"" seconds);

        } catch (Exception e) {
            context.fail(e);
        } finally {
            server.close();
        }
    }
}
</code></pre>

<p>The test always fails due to timeout after 120 seconds</p>

<p><strong>OUTPUT</strong></p>

<pre><code>start
created server
created client
inside subscribe
total time : 120

java.util.concurrent.TimeoutException
    at io.vertx.ext.unit.impl.TestContextImpl$Step.lambda$run$0(TestContextImpl.java:112)
    at java.lang.Thread.run(Thread.java:745)
</code></pre>
",https://stackoverflow.com/questions/44456260/unit-testing-vertx-java-util-concurrent-timeoutexception,"['unit-testing', 'rx-java', 'vert.x', 'vertx-httpclient']",2490,TRUE,3,2
Unit testing Datetime values,"<p>I have a function that makes use of the current time (<code>now</code>). The Contract as a whole is a Crowdfunding token and the cost of tokens differ depending on the date and time that tokens are purchased. </p>

<p>How does one simulate different times when testing a Smart Contract? For instance, with regards to the code below, I would like to do unit testing to find out if the code for setting price is correct but I can't change the value of <code>now</code>. </p>

<p>Would it be a good solution to simply substitute the <code>now</code> keyword for another temporary testing variable, say <code>now_sim</code> and then manually changing <code>now_sim</code> during simulation?</p>

<pre><code>    if (now &lt; (startTime + 1 days)) {
        currentPrice = safeDiv(safeMul(price, 80), 100);  // 20 % discount (x * 80 / 100)
    } 
    else if (now &lt; (startTime + 2 days)) {
        currentPrice = safeDiv(safeMul(price, 90), 100);  // 10 % discount (x * 90 / 100)
    }
    else if (now &lt; (startTime + 12 days)) {
        // 1 % reduction in the discounted rate from day 2 until day 12 (sliding scale per second)
        // 8640000 is 60 x 60 x 24 x 100 (100 for 1%) (60 x 60 x 24 for seconds per day)
        currentPrice = price - safeDiv(safeMul((startTime + 12 days) - now), price), 8640000);
    }
    else {
        currentPrice = price;
    }
</code></pre>
",https://stackoverflow.com/questions/43250397/unit-testing-datetime-values,"['unit-testing', 'ethereum', 'solidity']",622,TRUE,3,1
Unit Testing with IMongoQueryable,"<p>I am using .NET Core 2.0 and the .NET Core MongoDB driver.</p>

<p>I have created a repository like so:</p>

<pre><code>public interface IRepository&lt;T&gt;
{
    IMongoQueryable&lt;T&gt; Get()
}
</code></pre>

<p>I have done this to give flexibility to whoever uses this to be able to do LINQ much like they would do using EF. The problem is when it comes to unit testing and I'm trying to create an in-memory database so I can check states before and after operation. </p>

<p>Some stuff I tried:</p>

<pre><code>public class InMemoryRepository : IRepository&lt;ConcreteType&gt;
{
    private HashSet&lt;ConcreteType&gt; _data = new HashSet&lt;ConcreteType&gt;();

    public IMongoQueryable&lt;ConcreteType&gt; Get()
    {
        return (IMongoQueryable&lt;ConcreteType&gt;)_data.AsQueryable();
    }
}
</code></pre>

<p>The case doesn't work as the interface for <code>IMongoQueryable</code> is:</p>

<pre><code>public interface IMongoQueryable&lt;T&gt; : IMongoQueryable, IQueryable, IEnumerable, IQueryable&lt;T&gt;, IEnumerable&lt;T&gt;, IAsyncCursorSource&lt;T&gt;
</code></pre>

<p>Another go:</p>

<pre><code>public class InMemoryRepository : IRepository&lt;ConcreteType&gt;
{
    private HashSet&lt;ConcreteType&gt; _data = new HashSet&lt;ConcreteType&gt;();

    public InMemoryRepository()
    {
        _mongoQueryableMock = new Mock&lt;IMongoQueryable&lt;ConcreteType&gt;&gt;();
        _mongoQueryableMock.Setup(m =&gt; m.AsQueryable()).Returns(_data.AsQueryable);
    }

    public IMongoQueryable&lt;ConcreteType&gt; Get()
    {
        return _mongoQueryableMock.Object;
    }
}
</code></pre>

<p>This doesn't work as <code>IMongoQueryable.AsQueryable()</code> is an extension method and I can't mock/setup that.</p>
",https://stackoverflow.com/questions/46035390/unit-testing-with-imongoqueryable,"['c#', 'unit-testing', 'asp.net-core', 'moq', 'mongodb-.net-driver']",5211,TRUE,3,2
google maps unit testing,"

<p>Have the following directive.</p>

<pre class=""lang-js prettyprint-override""><code>import { Directive, ElementRef, EventEmitter, Output } from '@angular/core';
import { NgModel } from '@angular/forms';
import {} from 'googlemaps';
@Directive({
  selector: '[gmap]'
})
export class GmapDirective {

  @Output() addressFromGoogle: EventEmitter&lt;any&gt; = new EventEmitter();
  autocomplete: any;

  constructor(el: ElementRef) {
    this.autocomplete = new google.maps.places.Autocomplete(el.nativeElement, { componentRestrictions: { country: ""us"" } });
    google.maps.event.addListener(this.autocomplete, 'place_changed', () =&gt; {
      this.addressFromGoogle.emit(this.autocomplete.getPlace());
    });
  }
}
</code></pre>

<p>Trying to unit test and get <code>google is not defined</code> How do i provide a global variable to the TestBed ?</p>

<pre class=""lang-js prettyprint-override""><code>describe('GmapDirective', () =&gt; {
  let directive: GmapDirective;
  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [],
      providers: [
        GmapDirective,
        { provide: ElementRef, useClass: MockElementRef },
        {
          provide: google, useValue: {
            google: {
              maps: {
                Animation: {},
                BicyclingLayer: function () { },
                Circle: function () { },
                ControlPosition: {},
                Data: function () { },
                DirectionsRenderer: function () { },
                DirectionsService: function () { },
                DirectionsStatus: {},
                DirectionsTravelMode: {},
                DirectionsUnitSystem: {},
                DistanceMatrixElementStatus: {},
                DistanceMatrixService: function () { },
                DistanceMatrixStatus: {},
                ElevationService: function () { },
                ElevationStatus: {},
                FusionTablesLayer: function () { },
                Geocoder: function () { },
                GeocoderLocationType: {},
                GeocoderStatus: {},
                GroundOverlay: function () { },
                ImageMapType: function () { },
                InfoWindow: function () { },
                KmlLayer: function () { },
                KmlLayerStatus: {},
                LatLng: function () { },
                LatLngBounds: function () { },
                MVCArray: function () { },
                MVCObject: function () { },
                Map: function () {
                  return {
                    setTilt: function () { },
                    mapTypes: {
                      set: function () { }
                    },
                    overlayMapTypes: {
                      insertAt: function () { },
                      removeAt: function () { }
                    }
                  };
                },
                MapTypeControlStyle: {},
                MapTypeId: {
                  HYBRID: '',
                  ROADMAP: '',
                  SATELLITE: '',
                  TERRAIN: ''
                },
                MapTypeRegistry: function () { },
                Marker: function () { },
                MarkerImage: function () { },
                MaxZoomService: function () {
                  return {
                    getMaxZoomAtLatLng: function () { }
                  };
                },
                MaxZoomStatus: {},
                NavigationControlStyle: {},
                OverlayView: function () { },
                Point: function () { },
                Polygon: function () { },
                Polyline: function () { },
                Rectangle: function () { },
                SaveWidget: function () { },
                ScaleControlStyle: {},
                Size: function () { },
                StreetViewCoverageLayer: function () { },
                StreetViewPanorama: function () { },
                StreetViewService: function () { },
                StreetViewStatus: {},
                StrokePosition: {},
                StyledMapType: function () { },
                SymbolPath: {},
                TrafficLayer: function () { },
                TransitLayer: function () { },
                TransitMode: {},
                TransitRoutePreference: {},
                TravelMode: {},
                UnitSystem: {},
                ZoomControlStyle: {},
                __gjsload__: function () { },
                event: {
                  addListener: function () { }
                },
                places: {
                  AutocompleteService: function () {
                    return {
                      getPlacePredictions: function () { }
                    };
                  }
                }
              }
            }
          }
        }
      ],
      declarations: []
    }).compileComponents();
    directive = TestBed.get(GmapDirective);
  }));
  it('should create an instance', () =&gt; {
    expect(directive).toBeTruthy();
  });
});
</code></pre>

<p>Tried the above and it doesn't work since google is not injected (expected to be in the global namespace)</p>
",https://stackoverflow.com/questions/45639387/google-maps-unit-testing,"['angular', 'unit-testing', 'karma-jasmine']",4502,TRUE,3,1
Unit testing spark streaming,"<p>I have this line in scala:</p>

<pre><code>class SparkStreamingService(...){
 val lines: org.apache.spark.streaming.dstream.InputDStream[(String, String)] = KafkaUtils.createDirectStream[String, String, StringDecoder, StringDecoder](
    ssc, kafkaParams, topics)
  lines.foreachRDD { rdd =&gt;
    val df = cassandraSQLContext.read.json(rdd.map(x =&gt; x._2))
    if (!df.rdd.isEmpty()) {
      processDataFrameToLoadService(df)
    }
    else{
      throw new BacSparkStreamingExpception(""The dataframe created from kafka message is empty"")
    }
  }

  ssc.start()
  ssc.awaitTermination()
}
</code></pre>

<p>Is there a way to mock InputDStream in Java? How can I go about unit testing this? Basically I want to mock cassandraSQLContext.read.json(rdd.map(x => x._2)) and then return a custom DF (which I can do), but how do I get past the first 3 lines? 
Currently it just polls for messages and the test never finishes.</p>
",https://stackoverflow.com/questions/43078133/unit-testing-spark-streaming,"['java', 'scala', 'unit-testing', 'apache-spark']",1923,TRUE,3,1
Bug: VS2017 Live Unit Testing - only minus&#39;s - doesn&#39;t work,"<p><strong>TL;DR; Edit 6:</strong> I have narrowed it down and provided 5 steps to reproduce the problem/bug. </p>

<ol>
<li>Create a VS2017 c# Console App (.Net Full Framework)  </li>
<li>Add a method to the Program.cs and make the class public:   </li>
</ol>

<p>&nbsp;</p>

<pre><code>public class Program
{
    static void Main(string[] args)
    {
    }

    public int Add(int a, int b)
    { 
        return a + b;
    }
}
}
</code></pre>

<ol start=""3"">
<li>Right click the <code>Add</code> Method and choose Create Unit Test:</li>
</ol>

<p><a href=""https://i.stack.imgur.com/Uif8Z.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/Uif8Z.png"" alt=""enter image description here""></a></p>

<ol start=""4"">
<li>Use these settings to create a new Unit Test Project with the test:</li>
</ol>

<p><a href=""https://i.stack.imgur.com/v5IXn.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/v5IXn.png"" alt=""enter image description here""></a></p>

<ol start=""5"">
<li>Add a Unit Test</li>
</ol>

<p>&nbsp;</p>

<pre><code>[TestMethod()]
public void AddTest()
{
    Program p = new Program();
    var r = p.Add(1, 2);

    Assert.IsTrue(3 == r);
}
</code></pre>

<ul>
<li>Test Menu > Live Unit Testing > Start</li>
<li>Context menu over the <code>AddTest()</code> > Live Testing > Include</li>
</ul>

<p>Now change the Add's <strong>+</strong> symbol to <strong>-</strong></p>

<p>The Live Unit Testing works, change the  <strong>-</strong> symbol back to a <strong>+</strong> and the Live Test passes!!</p>

<p><strong>Now Add a reference to a Nuget DLL (anyone will do) - Live Unit Testing no longer works!   Or simply close the Solution, re-open it and Live Unit Testing no longer works!</strong></p>

<hr> 

<p>I've setup a MSUnitTest v2 project and started Live Unit Testing. I am using a Web Api 2 .Net project (Full Framework v4.5.2).</p>

<p>I see the Minus signs everywhere but no Tick's or Crosses. </p>

<p>I change code the same as they do in the <a href=""https://www.youtube.com/watch?v=kBlLi4BYCKk"" rel=""noreferrer"">Live Unit Testing in Visual Studio 2017 video</a> and the clocks appear over the minus's but then nothing...</p>

<p><a href=""https://i.stack.imgur.com/bW4KI.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/bW4KI.png"" alt=""enter image description here""></a></p>

<p>The unit test will pass when I debug it:</p>

<p><a href=""https://i.stack.imgur.com/ANh5l.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/ANh5l.png"" alt=""enter image description here""></a></p>

<p>When I hover the mouse over the blue minus's the message is ""Covered by 0 Tests""</p>

<p>I have found that you need the <strong>MSTest.TestAdapter</strong> and <strong>MSTest.TestFramework</strong> as per <a href=""https://developercommunity.visualstudio.com/content/problem/5520/live-unit-test-are-only-showing-minuses-using-micr.html"" rel=""noreferrer"">https://developercommunity.visualstudio.com/content/problem/5520/live-unit-test-are-only-showing-minuses-using-micr.html</a> which I have done and am referencing both V1.18:</p>

<ul>
<li>Microsoft.VisualStudio.TestPlatform.TestFramework</li>
<li>Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions</li>
</ul>

<p>There are a bunch of beta testers who reported the same problem:</p>

<p><a href=""https://developercommunity.visualstudio.com/content/problem/4510/live-unit-testing-doesnt-do-anything-1.html"" rel=""noreferrer"">https://developercommunity.visualstudio.com/content/problem/4510/live-unit-testing-doesnt-do-anything-1.html</a></p>

<p><a href=""https://developercommunity.visualstudio.com/content/problem/2737/live-unit-testing-doesnt-do-anything.html"" rel=""noreferrer"">https://developercommunity.visualstudio.com/content/problem/2737/live-unit-testing-doesnt-do-anything.html</a></p>

<p><a href=""https://developercommunity.visualstudio.com/content/problem/4376/live-unit-testing-doesnt-work.html"" rel=""noreferrer"">https://developercommunity.visualstudio.com/content/problem/4376/live-unit-testing-doesnt-work.html</a></p>

<p><a href=""https://developercommunity.visualstudio.com/content/problem/2527/live-unit-testing-doesnt-work-for-projects-that-im.html"" rel=""noreferrer"">https://developercommunity.visualstudio.com/content/problem/2527/live-unit-testing-doesnt-work-for-projects-that-im.html</a></p>

<p>All posts are resolved or wont fix.</p>

<p>This <a href=""https://stackoverflow.com/questions/43591499/visual-studio-2017-live-unit-testing-does-not-work"">Stackoverflow user got an issue with Live Unit Testing but its a Null Exception</a> problem. I tried the <a href=""https://developercommunity.visualstudio.com/content/problem/56681/unable-to-run-tests.html"" rel=""noreferrer"">solution in comments</a> to remove the Microsoft.VisualStudio.QualityTools.UnitTestFramework from the Gac, when I tried to uninstall from C:\Windows\assembly I got an access denied and uninstalling via a Developer Command Prompt: </p>

<pre><code>GacUtil /u Microsoft.VisualStudio.QualityTools.UnitTestFramework
</code></pre>

<p>Results in:</p>

<blockquote>
  <p>Assembly: Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL
  Unable to uninstall: assembly is required by one or more applications</p>
</blockquote>

<p><strong>Could someone help me get Live Unit Testing to work?</strong></p>

<p><strong>Edit 1:</strong></p>

<p>In VS > Tools > Options > Live Unit testing I turned logging to Verbose.</p>

<p>Looking at the output I saw one warning:</p>

<blockquote>
  <p>[15:48:26.521 Verbose] - TestDriver - TestDiscoverer log message: Warning - Configuration system failed to initialize</p>
</blockquote>

<p>Following a few answers in <a href=""https://stackoverflow.com/questions/6436157/configuration-system-failed-to-initialize"">this</a> I still wasn't able to get rid of the ""Configuration system failed to initialize"" - not sure if this is a red-herring or not, its the only clue I've found so far...</p>

<p><strong>Edit 2:</strong></p>

<p>I ran VS2017 as Admin and that got rid of the ""Configuration system failed to initialize"". Unfortunately running as Admin doesn't make a difference, it still doesn't work but doesn't fail with any exceptions.</p>

<hr>

<p>Here is Verbose log. Its interesting that ""Preparing to start test discovery"" looks like its found the x86 Test I have included.</p>

<p>However, it clearly cannot discover the test; ""Discovered 0 tests""</p>

<pre><code>[16:52:55.110 Verbose] - Aggregator - Calculating the set of tests that cover 1 files  
[16:52:55.110 Verbose] - Aggregator - [Workflow 4] Sending TestRequestEvent with 6 assemblies and 0 tests  
[16:52:55.110 Verbose] - TestDriver - [Workflow 4] Received TestRequestEvent  
[16:52:55.110 Verbose] - TestDriver - [Workflow 4] Preparing to start test discovery (X64: 0, X86: 1).  
[16:52:55.110 Verbose] - TestDriver - [Workflow 4] Start discovering tests from group 0, which contains 1 assemblies.  
[16:52:55.599 Verbose] - TestDriver - [Workflow 4] Finished discovering test from group 0.  
[16:52:55.599 Verbose] - TestDriver - [Workflow 4] Discovered 0 tests from XYZ.API.ClientService\bin\Debug\XYZ.API.ClientService.dll, updating cached data.  
[16:52:55.599 Verbose] - TestDriver - [Workflow 4] Notify Aggregator about completion of test run. (Passed: 0, Failed: 0, Run succeeded: True)  
[16:52:55.599 Verbose] - Aggregator - [Workflow 4] Received TestResponseEvent (TestRunCompleted)  
[16:52:55.599 Verbose] - Aggregator - [Workflow 4] Coverage data for 0 tests was received during this workflow  
[16:52:55.600 Verbose] - BuildManager - Allow to send a single build event.  
[16:52:55.599 Verbose] - Aggregator - Starting coverage aggregation cycle - work list has 3 methods  
[16:52:55.599 Verbose] - Aggregator - Finished coverage aggregation cycle - work list had 3 methods of which 3 methods were defined in 2 open files  
[16:52:55.600 Verbose] - BuildManager - Interrupting build queue -&gt; no new assemblies.  
[16:52:55.600 Verbose] - StatusMargin - Received file coverage result  
[16:52:55.599 Verbose] - Aggregator - Sending FileCoverageResult for 'C:\XYZProjectCollection\XYZ\XYZ.API.ClientService\Repositories\ValueRepository.cs - C:\XYZProjectCollection\Lincoln\XYZ.API.ClientService\XYZ.API.MiscService.csproj'
[16:52:55.599 Verbose] - Aggregator - [Workflow 4] Sending TestRunCompletedEvent  
</code></pre>

<p><strong>Edit 3:</strong></p>

<p>I had a look through ProcessMonitor traces today.. nothing really stood out, I could have missed something but I'm starting to feel this is a bug not a config problem. </p>

<p>I'm working in a really locked down environment so it could be that something was blocked during vs2017 install. I know Unity3D domain is not whitelisted for downloads. Although all core Visual Studio Microsoft stuff is installed. I'm starting to run out of diagnostic troubleshooting strategy's. Any ideas very welcome!</p>

<p><strong>Edit 4:</strong></p>

<p>This morning I decided to get rid of the <code>Microsoft.VisualStudio.QualityTools.UnitTestFramework</code> DLL from the GAC. I did it following <a href=""https://social.msdn.microsoft.com/Forums/en-US/484e9c4a-8d5d-4965-8b1d-a109821ba7da/gac-uninstall?forum=netfx64bit"" rel=""noreferrer"">these instructions to overcome the Access Denied</a>:</p>

<p><a href=""https://i.stack.imgur.com/2noop.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/2noop.png"" alt=""enter image description here""></a></p>

<p>This led to finding one of the potential root causes. I started seeing the Live Unit Testing Logging outputing:</p>

<pre><code>[09:44:59.053 Verbose] - BuildManager - C:\Program Files x86\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(3245,5): error MSB3491: Could not write lines to file ""C:\XYZProjectCollection\Lincoln\.vs\XYZ.API\18528\i\XYZ.API.MiscService\Debug\CoreCompileInputs.cache"". Access to the path 'C:\XYZProjectCollection\Lincoln\.vs\XYZ.API\18528\i\XYZ.API.MiscService\Debug\CoreCompileInputs.cache' is denied.   
[09:44:59.053 Verbose] - BuildManager - C:\Program Files x86\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(4874,5): error MSB3491: Could not write lines to file ""C:\XYZProjectCollection\Lincoln\.vs\XYZ.API\18528\i\XYZ.API.MiscService\Debug\XYZ.API.MiscService.csproj.FileListAbsolute.txt"". Access to the path 'C:\XYZProjectCollection\Lincoln\.vs\XYZ.API\18528\i\XYZ.API.MiscService\Debug\XYZ.API.MiscService.csproj.FileListAbsolute.txt' is denied.
</code></pre>

<p>I gave myself permission to all those directories, just to rule out any permissions issues:</p>

<p><a href=""https://i.stack.imgur.com/4hRzV.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/4hRzV.png"" alt=""enter image description here""></a></p>

<p>This still doesn't work, however it seems I am getting closer as the Live Unit Tests are taking a little longer to <em>not</em> work (ie the clocks that appear on top of the minus's take longer to process).</p>

<p>Then I tried ProcMon again and it showed some interesting logs but no smoking gun.</p>

<p>Here is the current Verbose Log:</p>

<pre><code>[10:22:07.363 Info] - BuildManager - Build completed (succeeded).
[10:22:07.363 Verbose] - BuildManager - Interrupting build queue -&gt; switching 'build' and 'test' directories.
[10:22:07.363 Verbose] - BuildManager - New 'test' directory: C:\XYZProjectCollection\Lincoln\.vs\XYZ.API\18528\1\
[10:22:07.363 Verbose] - BuildManager - New 'build' directory: C:\XYZProjectCollection\Lincoln\.vs\XYZ.API\18528\0\
[10:22:07.363 Verbose] - Aggregator - [Workflow 4] Received BuildEvent.
[10:22:07.363 Verbose] - Aggregator - assembly: C:\XYZProjectCollection\Lincoln\.vs\XYZ.API\18528\t\XYZ.API.Tests\bin\Debug\XYZ.API.Tests.dll
[10:22:07.363 Verbose] - Aggregator - assembly: C:\XYZProjectCollection\Lincoln\.vs\XYZ.API\18528\t\XYZ.API.AccountClientService\bin\Debug\XYZ.API.AccountClientService.dll
[10:22:07.363 Verbose] - Aggregator - assembly: C:\XYZProjectCollection\Lincoln\.vs\XYZ.API\18528\t\XYZ.API\bin\XYZ.API.dll
[10:22:07.363 Verbose] - Aggregator - assembly: C:\XYZProjectCollection\Lincoln\.vs\XYZ.API\18528\t\XYZ.API.Helpers\bin\Debug\XYZ.API.Global.dll
[10:22:07.363 Verbose] - Aggregator - assembly: C:\XYZProjectCollection\Lincoln\.vs\XYZ.API\18528\t\XYZ.API.MiscService\bin\Debug\XYZ.API.MiscService.dll
[10:22:07.363 Verbose] - Aggregator - file: 'C:\XYZProjectCollection\Lincoln\XYZ.API.MiscService\Repositories\ValueRepository.cs - C:\XYZProjectCollection\Lincoln\XYZ.API.MiscService\XYZ.API.MiscService.csproj'
[10:22:07.363 Verbose] - Aggregator - Skip reading spans for assembly C:\XYZProjectCollection\Lincoln\.vs\XYZ.API\18528\t\XYZ.API.Tests\bin\Debug\XYZ.API.Tests.dll with MVID c96c0f4b-b21e-47be-a71e-97ebf8a3d493 since we already have this information from a previous build
[10:22:07.363 Verbose] - Aggregator - Skip reading spans for assembly C:\XYZProjectCollection\Lincoln\.vs\XYZ.API\18528\t\XYZ.API.AccountClientService\bin\Debug\XYZ.API.AccountClientService.dll with MVID 6772f896-04ab-4804-bb18-3ed2c7aeb9b9 since we already have this information from a previous build
[10:22:07.363 Verbose] - Aggregator - Skip reading spans for assembly C:\XYZProjectCollection\Lincoln\.vs\XYZ.API\18528\t\XYZ.API\bin\XYZ.API.dll with MVID 9c862440-c16a-4efe-8574-76e8c1453c4d since we already have this information from a previous build
[10:22:07.363 Verbose] - Aggregator - Skip reading spans for assembly C:\XYZProjectCollection\Lincoln\.vs\XYZ.API\18528\t\XYZ.API.Helpers\bin\Debug\XYZ.API.Global.dll with MVID a8899d5d-4730-46bf-b4f2-3c2b1b75b0b1 since we already have this information from a previous build
[10:22:07.363 Verbose] - Aggregator - Removing MVID f337ca44-aae6-42ca-8df5-3776ff962372 for project C:\XYZProjectCollection\Lincoln\XYZ.API.MiscService\XYZ.API.MiscService.csproj from the file span cache
[10:22:07.363 Verbose] - Aggregator - Adding MVID 8e944276-0eec-43f4-aff3-07e40f8611dc for project C:\XYZProjectCollection\Lincoln\XYZ.API.MiscService\XYZ.API.MiscService.csproj to the file span cache
[10:22:07.363 Verbose] - Aggregator - Calculating the set of tests that cover 0 files
[10:22:07.363 Verbose] - Aggregator - Reading spans for assembly C:\XYZProjectCollection\Lincoln\.vs\XYZ.API\18528\t\XYZ.API.MiscService\bin\Debug\XYZ.API.MiscService.dll with MVID 8e944276-0eec-43f4-aff3-07e40f8611dc
[10:22:07.363 Verbose] - Aggregator - Adding 3 methods from 'C:\XYZProjectCollection\Lincoln\XYZ.API.MiscService\Repositories\ValueRepository.cs - C:\XYZProjectCollection\Lincoln\XYZ.API.MiscService\XYZ.API.MiscService.csproj' to the coverage aggregation work list
[10:22:07.363 Verbose] - Aggregator - Calculating the set of tests that cover 1 files
[10:22:07.363 Verbose] - Aggregator - [Workflow 4] Sending TestRequestEvent with 5 assemblies and 0 tests
[10:22:07.363 Verbose] - TestDriver - [Workflow 4] Received TestRequestEvent
[10:22:07.363 Verbose] - TestDriver - [Workflow 4] Preparing to start test discovery (X64: 0, X86: 1).
[10:22:07.363 Verbose] - TestDriver - [Workflow 4] Start discovering tests from group 0, which contains 1 assemblies.
[10:22:07.834 Verbose] - TestDriver - [Workflow 4] Finished discovering test from group 0.
[10:22:07.834 Verbose] - TestDriver - [Workflow 4] Discovered 0 tests from XYZ.API.MiscService\bin\Debug\XYZ.API.MiscService.dll, updating cached data.
[10:22:07.834 Verbose] - TestDriver - [Workflow 4] Notify Aggregator about completion of test run. (Passed: 0, Failed: 0, Run succeeded: True)
[10:22:07.834 Verbose] - Aggregator - [Workflow 4] Received TestResponseEvent (TestRunCompleted)
[10:22:07.834 Verbose] - Aggregator - [Workflow 4] Coverage data for 0 tests was received during this workflow
[10:22:07.834 Verbose] - Aggregator - Starting coverage aggregation cycle - work list has 3 methods
[10:22:07.834 Verbose] - Aggregator - Finished coverage aggregation cycle - work list had 3 methods of which 3 methods were defined in 5 open files
[10:22:07.834 Verbose] - BuildManager - Allow to send a single build event.
[10:22:07.834 Verbose] - BuildManager - Interrupting build queue -&gt; no new assemblies.
[10:22:07.834 Verbose] - Aggregator - Sending FileCoverageResult for 'C:\XYZProjectCollection\Lincoln\XYZ.API.MiscService\Repositories\ValueRepository.cs - C:\XYZProjectCollection\Lincoln\XYZ.API.MiscService\XYZ.API.MiscService.csproj'
[10:22:07.834 Verbose] - Aggregator - [Workflow 4] Sending TestRunCompletedEvent
[10:22:07.850 Verbose] - StatusMargin - Received file coverage result
</code></pre>

<p><strong>Edit 5:</strong></p>

<p>According to this blog:
<a href=""https://blogs.msdn.microsoft.com/visualstudio/2017/03/09/live-unit-testing-in-visual-studio-2017-enterprise/"" rel=""noreferrer"">https://blogs.msdn.microsoft.com/visualstudio/2017/03/09/live-unit-testing-in-visual-studio-2017-enterprise/</a></p>

<p><strong>Q: Why does nothing happen after I include or exclude tests from Live Test Set?</strong></p>

<p>A: This is a known issue which we were not able to fix in Visual Studio 2017 version 15.0. It is now fixed in Visual Studio 2017 version 15.2.</p>

<p>Turns out I have Visual Studio/15.0.0 +26228.9. Upgrading to Visual Studio 2017 (v15.2) DOES <strong>NOT</strong> fix the problem.</p>

<p>I have reported the issue to <a href=""https://developercommunity.visualstudio.com"" rel=""noreferrer"">https://developercommunity.visualstudio.com</a> and will keep everyone posted. It properly didn't get reported the environment is locked.</p>
",https://stackoverflow.com/questions/44427076/bug-vs2017-live-unit-testing-only-minuss-doesnt-work,"['c#', '.net', 'unit-testing', 'visual-studio-2017', 'live-unit-tests']",5477,TRUE,42,7
"Retrofit2 unit testing, MockWebServer","<p>I would like to test my Rest services build under Retrofit2. I don't want to mock all responses individually, but I would like to mock the entire web server. I found that it's possible with MockServer. But I am not able to work with it. </p>

<p>My Retrofit2 base URL is given by my build type. I tried for instance to create a new build type, for example ""staging"" like so:</p>

<pre><code>    staging {
        buildConfigField ""String"", ""APP_BASE_URL"", ""\""http://test.com\""""
    }
</code></pre>

<p>and added in the gradle config as well</p>

<pre><code>testBuildType ""staging""
</code></pre>

<p>But my tests aren't working anymore, everything turn red in Intellij. Dependencies aren't found.</p>

<p>Basically what I want to do is that for each test, I want a mock web server with a specific URL. This url will be used by my Retrofit2 interface Base URL, and I want the mockwebserver to response to them with specific JSON file response.</p>

<p>For example:</p>

<pre><code>@Before
override public fun setUp() {
    super.setUp()
    server = MockWebServer()
    server.url(""http://test.com"")
}

@Test
fun forbiddenLogin() {
    server.enqueue(MockResponse()
            .setResponseCode(403)
            .setBody(""{\""message\"": \""Forbidden access!\""}"")
    )
    server.start()

   //HOW TO CALL AND TESTS MY SERVICES HERE?
}
</code></pre>

<p>For information my Retrofit2 service uses RxJava Observable</p>

<pre><code>@POST(""/rest/login"")
@FormUrlEncoded
fun login(
        @Field(""login"") login: String,
        @Field(""password"") password: String
): Observable&lt;ApiWrapper&lt;UserDTO&gt;&gt;
</code></pre>
",https://stackoverflow.com/questions/48020312/retrofit2-unit-testing-mockwebserver,"['android', 'unit-testing', 'intellij-idea', 'retrofit2', 'mockwebserver']",829,FALSE,3,0
Unit testing composite functions,"<p>Say you have 3 functions, functionA, functionB, and functionC </p>

<p>functionC relies on functionA and functionB</p>

<pre><code>functionA(a) {
    return a
}
functionB(b) {
     return b
}
functionC(a, b){
     return functionA(a) + functionB(b);
}
</code></pre>

<p>Now this is obviously a super simplified example.. but what's the correct way to test functionC? If I'm already testing functionA and functionB and theyre passing wouldn't testing functionC wind up being more than a unit test since it would be relying on functionA and functionB returns..</p>
",https://stackoverflow.com/questions/45654729/unit-testing-composite-functions,"['unit-testing', 'testing']",1137,TRUE,3,3
Unit testing the State,"<p>I am trying to fetch data from SharedPreferences during initState() and test it.
If I simply set private variable inside the state without invoking setState(), view is not updated.</p>

<p>If I try to wrap setting variables inside setState() my test will break
with null pointer at setState() method.</p>

<pre><code>NoSuchMethodError: The method 'markNeedsBuild' was called on null.
Receiver: null
Tried calling: markNeedsBuild()
</code></pre>

<p>Here is my initState()</p>

<pre><code>initState() {
  _appRepository.readOnboardingCompleted().then((readValue) {
    print(""read: $readValue"");
    setState(()=&gt;_onboardingCompleted = readValue);
});
  super.initState();
}
</code></pre>

<p>here is the test</p>

<pre><code>test(
  'GIVEN app starts WHEN onboarding was completed THEN onboarding is disabled',() {

     when(mockAppRepository.readOnboardingCompleted()).thenReturn(mockBoolFuture);
     AppState systemUnderTest = new AppState(mockAppRepository);
     systemUnderTest.initState();
     verify(mockAppRepository.readOnboardingCompleted());
});
</code></pre>

<p>I feel there has to be an easier way of doing this.</p>
",https://stackoverflow.com/questions/44796857/unit-testing-the-state,['flutter'],2166,TRUE,2,1
Unit testing angular $modal.result.then(),"<p>I am writing unit tests for a controller and I stuck on testing <code>$modal</code>.
I am confusing how could I unit test code inside <code>newModal.result.then()</code>? </p>

<p>Here is the code:</p>

<pre><code> angular.module('myModule')
       .controller('myCtrl', function($modal){
           $scope.myFunction = function(){
               var newModal = $modal.open({
                   templateUrl: 'path.html',
                   controller: 'modalController',
                   backdrop: 'static',
                   resolve: {
                      message: function (){return 'some messages';}
                   }
               });
               newModal.result.then(function(type){
                   $scope.type = type;
               });
           };
       });
</code></pre>

<p>Here is what I have right now:</p>

<pre><code>describe('Testing modalController', function(){
    var $scope,ctrl,$modal;     
    var fakeMsg = {
            result: {
                then: function(confirmCallback, cancelCallback) {
                    this.confirmCallBack = confirmCallback;
                    this.cancelCallback = cancelCallback;
                }
            },
            close: function(item) {
                this.result.confirmCallBack(item);
            },
            dismiss: function(type) {
                this.result.cancelCallback(type);
            }
        };        


    beforeEach(module('myModule'));

    beforeEach(inject(function(_$rootScope_, $controller,_$modal_){
        $rootScope = _$rootScope_;
        $scope = $rootScope.$new();
        ctrl = $controller('myCtrl', {$scope: $scope});};
        $modal = _$modal_;
    }));
   it(""should open modal"", function() {
        spyOn($modal, 'open').andReturn(fakeMsg);
        $scope.myFunction();
        $rootScope.$apply();
        expect($modal.open).toHaveBeenCalled();
    });    
});
</code></pre>
",https://stackoverflow.com/questions/42216683/unit-testing-angular-modal-result-then,"['angularjs', 'unit-testing']",251,FALSE,2,0
Unit testing functional interface,"<p>I have a public method like this:</p>

<pre><code>public List&lt;Resource&gt; getResource(Function&lt;InputStream, List&lt;Resource&gt;&gt; funcToExecute)
{
    InputStream inp = getInputStream();
    return funcToExecute.apply(inp);
}
</code></pre>

<p>How do I unit test this functionality? How do I establish relation between inputstream and list of resource to be returned in my Unit tests?</p>
",https://stackoverflow.com/questions/45253539/unit-testing-functional-interface,"['java', 'unit-testing', 'mocking', 'mockito', 'functional-interface']",6516,FALSE,2,1
"Unit Testing, iOS, DTXProxyChannel error 1","<p>I sometimes start to get the following error</p>

<blockquote>
  <p>2017-04-02 18:55:22.645937+0200 Stamps[730:111791] Connection peer
  refused channel request for
  ""dtxproxy:XCTestDriverInterface:XCTestManager_IDEInterface""; channel
  canceled  Failed to run tests: The operation
  couldn’t be completed. (DTXProxyChannel error 1.)</p>
</blockquote>

<p>Last time, when this happened, I just did some random actions with clean my project, remove derived data etc., and it was fixed. Now, it happens again - just after a start of the app, it closes and log contains this error.</p>

<p>What does it mean and is there any workaround here?</p>

<p>I use XCode 8.3, Swift 3.1, test on device 6s with 10.3 installed.</p>
",https://stackoverflow.com/questions/43171020/unit-testing-ios-dtxproxychannel-error-1,"['ios', 'xcode', 'unit-testing', 'testing']",3832,TRUE,18,1
Unit testing with XUnit,"<p>I'm implementing unit testing in my app with XUnit and I have autofac as my DI. The autofac documentaion recomends using Autofac.Extras.Moq.AutoMock. I'm completely new to this and have been following the documented examples but I can't get it to work properly. This is code I'm using to generate the test:</p>

<pre><code>using (var mock = AutoMock.GetLoose())
{
    mock.Mock&lt;IScheduleService&gt;().Setup(m =&gt; m.GenerateSchedule(request)).Returns(response);
    var sut = mock.Create&lt;ScheduleService&gt;();
    var actual = sut.GenerateSchedule(request);
    mock.Mock&lt;IScheduleService&gt;().Verify(x =&gt; x.GenerateSchedule(request));
    Assert.Equal(response.Schedules, actual.Schedules);
}
</code></pre>

<p>The method under test basically returns a list of 'schedule' objects (dates &amp; times) So I've mocked up a valid response which the method will return from its input. The method is invoked and the code runs and returns an object (list of schedules), but I get this error and the test fails</p>

<pre><code>ApplicationService.Tests.Schedule.ScheduleServiceTest.TestDailyScheduleCreation [FAIL]
[xUnit.net 00:02:33.7051040]       Moq.MockException : 
Expected invocation on the mock at least once, but was never performed: x =&gt; x.GenerateSchedule()
[xUnit.net 00:02:33.7089101]       
[xUnit.net 00:02:33.7096712]       Configured setups: 
[xUnit.net 00:02:33.7101336]       m =&gt; m.GenerateSchedule()
[xUnit.net 00:02:33.7134611]       No invocations performed.
</code></pre>

<p>I'm not really sure what's going on here as I've not used XUnit and Moq before, can anyone tell me where I'm going wrong?</p>

<p>heres the system under test</p>

<pre><code>private List&lt;ScheduleDto&gt; CalculateDaily(DateTime startDate, DateTime endDate, TimeSpan GenerationTimeUTC, long scheduleId)
    {
        List&lt;ScheduleDto&gt; schedulesList = new List&lt;ScheduleDto&gt;();
        var numOfDays = (endDate - startDate).TotalDays;
        for (int i = 0; i &lt; numOfDays ; i++)
        {
            ScheduleDto newSchedule = new ScheduleDto();
            newSchedule.GenerationDate = startDate.AddDays(i);
            newSchedule.GenerationTimeUTC = GenerationTimeUTC;
            newSchedule.ScheduleID = scheduleId;
            newSchedule.IsEmailed = false;
            newSchedule.IsGenerated = false;
            schedulesList.Add(newSchedule);
        }
            return schedulesList;
    }
</code></pre>

<p>this is the request object</p>

<pre><code>ScheduleGenerationRequest request = new ScheduleGenerationRequest(0);
        CreateScheduleRequest response = new CreateScheduleRequest(0);

        request.StartDate = new DateTime(2017, 7, 17);
        request.EndDate = request.StartDate.AddDays(7);
        request.Frequency = EnumHelper.ScheduleFrequency.Daily;
        request.FrequencyPeriod = 1;
        TimeSpan timeSpan = new TimeSpan(19, 00, 00);
        request.GenerationTimeUTC = timeSpan;
</code></pre>

<p>this is the main method in the service class</p>

<pre><code>public CreateScheduleRequest GenerateSchedule(ScheduleGenerationRequest request)
    {
        CreateScheduleRequest response = new CreateScheduleRequest(request.Id);
        List&lt;ScheduleDto&gt; result = new List&lt;ScheduleDto&gt;();
        switch (request.Frequency)
        {
            case EnumHelper.ScheduleFrequency.Daily:
                result = CalculateDaily(request.StartDate,request.EndDate, request.GenerationTimeUTC,request.Id);
                break;
            case EnumHelper.ScheduleFrequency.Weekly:
                result = CalculateWeekly(request.StartDate, request.EndDate, request.GenerationTimeUTC, request.Id, request.PrintDaySpecifier, request.FrequencyPeriod);
                break;
            case EnumHelper.ScheduleFrequency.Monthly:

                break;
            case EnumHelper.ScheduleFrequency.Yearly:

                break;
        }
        response.Schedules = result;
        return response;
    }
</code></pre>
",https://stackoverflow.com/questions/45278012/unit-testing-with-xunit,"['c#', 'moq', 'autofac', 'xunit.net']",766,FALSE,2,0
Unit testing side outputs,"<p>I'm unit testing a ParDo function with Apache Beam that has 1 main output and 1 sideoutput:</p>

<pre><code>public class GetPubsubMessageDoFn extends DoFn&lt;PubsubMessage, PubsubPayload.PubsubPayloadDTO&gt; {

  @ProcessElement
  public void processContext(ProcessContext processContext) {
    PubsubPayload pubsubPayload = new PubsubPayload(processContext.element());
    processContext.output(pubsubPayload.getPayload()); //main output
    processContext.output(ORIGIN_PATH_TUPLE_TAG, GCSUtils.toGSURL(pubsubPayload.getPayload().bucket, pubsubPayload.getPayload().name)); //side output
  }
}
</code></pre>

<p>I set up a unit test class for testing the main - and side outputs:</p>

<pre><code> public class GetPubsubMessageDoFnTest {

      private DoFnTester&lt;PubsubMessage, PubsubPayloadDTO&gt; getPubsubMessageDoFn;   
      private Injector injector;
      private final TupleTagList tags = TupleTagList.of(PUBSUB_PAYLOAD_DTO_TUPLE_TAG).and(ORIGIN_PATH_TUPLE_TAG);


      @Before   
      public void setup() {
        injector = Guice.createInjector(new GetPubsubMessageTestModule());
        this.getPubsubMessageDoFn = DoFnTester.of(injector.getInstance(GetPubsubMessageDoFn.class));
        this.getPubsubMessageDoFn.setOutputTags(tags); //Does not compile
      }

  //Tests
</code></pre>

<p>According to <a href=""https://beam.apache.org/documentation/pipelines/test-your-pipeline/#additional-outputs"" rel=""nofollow noreferrer"">the documentation</a> I should be able to set the side output using  <code>setOutputTags(tags)</code> only that function does not exist on the <code>DoFnTester</code> class. I'm using the <a href=""https://mvnrepository.com/artifact/com.google.cloud.dataflow/google-cloud-dataflow-java-sdk-all/2.1.0"" rel=""nofollow noreferrer"">Google Cloud Dataflow dependency</a> version 2.1.0, which does use a subset of Apache Beam's features, but even looking at the Apache Beam reference documentation for <a href=""https://beam.apache.org/documentation/sdks/javadoc/2.1.0/"" rel=""nofollow noreferrer"">DoFnTester</a> <code>setOutputTags</code> isn't listed (even though it's mentioned again in the intro).</p>
",https://stackoverflow.com/questions/47264421/unit-testing-side-outputs,"['java', 'unit-testing', 'google-cloud-dataflow', 'apache-beam']",554,TRUE,2,1
PowerBuilder unit testing framework,"<p>Is there any ability of PowerBuilder to write and run unit tests? I'm talking about PowerBuilder 12 classic.</p>

<p>Alternatively is there any third party framework or library for unit testing of powerbuilder code?</p>

<p>I'm pretty new to PowerBuilder, so I appreciate any advice or experience on testing PB applications.</p>
",https://stackoverflow.com/questions/47181779/powerbuilder-unit-testing-framework,"['unit-testing', 'powerbuilder']",1836,TRUE,2,2
Unit testing JPA queries,"<p>How should I unit test a method that returns a boolean value and is implemented like so?</p>

<pre><code>return entityManager.createQuery(""SELECT(i) FROM Items i WHERE o.id=:id"", Long.class).setParameter(""id"", id).getSingleResult() == 1;
</code></pre>

<p><code>entityManager</code> is injected into the class.</p>

<p>I think I probably should verify that <code>createQuery</code> gets called with this query and then <code>setParameter</code> gets called with <code>id</code> and then result is compared to 1. However, isn't such a test a bit overkill for a simple line of code like this?
I especially feel uncomfortable using the whole select statement in unit test. It seems more like implementation detail to me. However, what other way is there to check that the query actually check item COUNT and does something else?</p>
",https://stackoverflow.com/questions/42422547/unit-testing-jpa-queries,"['java', 'unit-testing', 'jpa', 'orm']",1785,TRUE,2,2
Unit testing django serializers,"<p>I'm trying to unit test serializers but I have an issue in getting the expected error messages when I do serializers.is_valid().</p>

<p>Code:</p>

<p>serializer.py</p>

<pre><code>class RandomSerializer(serializers.Serializer):
    sno = serializers.IntegerField(required=True)
    description = serializers.CharField(required=True)

    def __init__(self, *args, **kwargs):
        super(RandomSerializer, self).__init__(*args, **kwargs)

....
</code></pre>

<p>test_serializer.py</p>

<pre><code>def test_random_serializer():
    val_dict = {'sno': 1, 'description':'test'}
    serializer = RandomSerializer(val_dict)
</code></pre>

<p>At this point when I check serializer.is_valid(), this evaluates to False and I get the following error when I check serializer.errors</p>

<pre><code> {u'non_field_errors': [u'No input provided']}
</code></pre>

<p>How can I fix this? Any thoughts?</p>

<p>Thanks in advance</p>

<p>PS: I also tried serializer = RandomSerializer(data=val_dict) but this does not even populate values to serializers.data</p>
",https://stackoverflow.com/questions/44469046/unit-testing-django-serializers,"['python', 'django', 'unit-testing', 'serialization', 'pytest-django']",3657,FALSE,2,2
Laravel PHP Unit Testing,"<p>I am just testing my laravel app with phpunit 
When i run <code>vendor/bin/phpunit</code> i am getting error like below <code>Error: Call to undefined method ExampleTest::assertStatus()</code> </p>

<p>Below is the code i was trying to execute </p>

<pre><code>$response = $this-&gt;json('POST', '/users', ['customer_name' =&gt; 'Ratke-Harris']);

        $response
            -&gt;assertStatus(200)
            -&gt;assertExactJson([
                'created' =&gt; true,
            ]);
</code></pre>

<p>As per the laravel docs , even there they have mentioned the same example. I don't understand why it is throwing  error.</p>

<p>Any ideas ? Please.</p>
",https://stackoverflow.com/questions/44194453/laravel-php-unit-testing,"['phpunit', 'laravel-5.4', 'laravel-testing']",575,TRUE,2,2
unit testing using mock,"<p>I'm trying to conduct unit test on my app.
This is my test:</p>

<pre><code>class CustomerControllerTest
{
    [Test]
    public void GetAuctionsByJson_works()
    {
        // Arrange
        Mock&lt;IAuctionRespository&gt; mockAuction = new Mock&lt;IAuctionRespository&gt;();
        mockAuction.Setup(m =&gt; m.Auctions).Returns(new Auction[]
            {
                new Auction { a_id=1, auctionname=""computer"", deadLine=DateTime.Today},
                new Auction { a_id=2, auctionname=""keyboard"", deadLine=DateTime.Today},
                new Auction { a_id=3, auctionname=""mouse"", deadLine=DateTime.Today}
            }.AsQueryable());
        CustomerController controller = new CustomerController(mockAuction.Object);
        var actual = controller.GetAuctionsByJson() as JsonResult;
        //parse result
        List&lt;Auction&gt; result = actual.Data as List&lt;Auction&gt;; //null
        Assert.AreEqual(3, result.Count);
        Assert.AreEqual(1, result[0].a_id);
        Assert.AreEqual(""computer"", result[0].auctionname);
        Assert.AreEqual(DateTime.Today, result[0].deadLine);

    }
}
</code></pre>

<p>var actual has values (as seen in image)
<a href=""https://i.stack.imgur.com/sJRKo.png"" rel=""nofollow noreferrer"">actual val</a>
but i get that var result is null
<a href=""https://i.stack.imgur.com/7fj4V.png"" rel=""nofollow noreferrer"">result val</a>
why?
how can i get actual values in a list?
Thank</p>
",https://stackoverflow.com/questions/43109654/unit-testing-using-mock,"['c#', 'json', 'unit-testing']",95,FALSE,1,1
Unit testing asynchronous operations,"<p>I'm trying to unittest code that delegates work to a background executor. After I refactored a delete-method to return a list of ids, I've run into a problem in my unit tests. The tests that should validate the behavior when a method throws a sqlexception fails.</p>

<p>I've not used Futures in my code previously, so forgive me if this design is flawed.</p>

<p>The following is my code.</p>

<p>TaskInteractor.java:</p>

<pre><code>public class TaskInteractor extends AbstractInteractor
    implements TaskContract.Interactor {

    private final TaskRepository mRepository;

    @Inject
    public TaskInteractor(WorkerThread workerThread, MainThread mainThread, TaskRepository repository) {
        super(workerThread, mainThread);
        this.mRepository = repository;
    }
    ...
    @Override
    @android.support.annotation.MainThread
    public void deleteTasks(@NonNull final List&lt;Task&gt; tasks, @NonNull final DeleteTaskCallback callback) {
        try {
        final Future&lt;List&lt;String&gt;&gt; future = mWorkerThread.execute(() -&gt;
                mRepository.softDeleteAllInTransaction(tasks));
        mMainThread.post(() -&gt; {
            try {
                callback.onDeleteSuccess(future.get());
            } catch (InterruptedException | ExecutionException e) {
                Timber.e(e);
                throw new RuntimeException(e.getCause());
            }
        });
    } catch (final SQLiteAbortException e) {
        mMainThread.post(() -&gt; { callback.onAbortException(e); });
        throw e;
    } catch (final SQLiteConstraintException e) {
        mMainThread.post(() -&gt; { callback.onConstraintException(e); });
        throw e;
    } catch (final Exception e) {
        mMainThread.post(() -&gt; { callback.onFailure(e); });
        throw new RuntimeException(e);
    }
    }
}
</code></pre>

<p>I'm getting the following message:</p>

<pre><code>Wanted but not invoked:
mDeleteTaskCallbackMock.onAbortException(
    &lt;any android.database.sqlite.SQLiteAbortException&gt;
);
-&gt; at com.example.ui.task.ExaminationInteractorTest.whenDeleteFailWithSQLiteAbortException_shouldCallOnAbortFailureCallback(ExaminationInteractorTest.java:173)

However, there was exactly 1 interaction with this mock:
mDeleteTaskCallbackMock.onFailure(
    java.lang.RuntimeException: 
android.database.sqlite.SQLiteAbortException
);
-&gt; at com.example.ui.examination.ExaminationInteractor.lambda$deleteExaminations$8(ExaminationInteractor.java:79)
</code></pre>

<p>Here's one of my tests.</p>

<pre><code>@Test
public void whenDeleteFailWithSQLiteConstraintException_shouldCallOnConstraintFailureCallback() throws Exception {
    doThrow(new SQLiteConstraintException()).when(mRepositoryMock).softDeleteAllInTransaction(ArgumentMatchers.&lt;Task&gt;anyList());

    List&lt;Task&gt; tasks = Arrays.asList(TEST_TASKS);

    mInteractor.deleteTasks(tasks, mDeleteTaskCallback);
    verify(mDeleteTaskCallback).onConstraintException(
        any(SQLiteConstraintException.class));
}
</code></pre>

<p>The execution is done by a test double with the following implementation.</p>

<p>FakeWorkerThread.java:</p>

<pre><code>/**
* Just runs the commands without invoking other threads
*/
public class FakeWorkerThread implements WorkerThread {

    @Override
    public void execute(Runnable interactor) {
        interactor.run();
    }

    @Override
    public &lt;T&gt; Future&lt;T&gt; execute(Callable&lt;T&gt; callable) throws Exception {
        RunnableFuture&lt;T&gt; ftask = new FutureTask&lt;T&gt;(callable);
        execute(ftask);
        return ftask;
    }
}
</code></pre>
",https://stackoverflow.com/questions/47014667/unit-testing-asynchronous-operations,"['java', 'android', 'unit-testing', 'concurrency', 'exception']",757,TRUE,1,1
ReactiveUI ViewModel Unit Testing,"<p>I have been trying to get rid of iOS/Android Test Harness and make my VM Unit Tests run directly on XS/VS test runners, because:
1) It's WAAAAY faster then loading up the Harness every time
2) Makes it easier to run on VSTS</p>

<p>I know that I can't run it from a PCL directly due the ""Bait &amp; Switch"", so after reading @kentcb post <a href=""http://kent-boogaart.com/blog/using-the-visual-studio-test-runner-for-mobile-development"" rel=""nofollow noreferrer"">http://kent-boogaart.com/blog/using-the-visual-studio-test-runner-for-mobile-development</a>, I decided to give a try to run it on a net45 test project and see how it goes, but still no success so far, I'm getting some errors like:</p>

<blockquote>
  <p>System.TypeInitializationException : The type initializer for
  'ReactiveUI.ReactiveNotifyPropertyChangedMixin' threw an exception.<br>
  ----> System.TypeInitializationException : The type initializer for 'ReactiveUI.RxApp' threw an exception.   ---->
  System.TypeInitializationException : The type initializer for
  'ReactiveUI.CreatesCommandBindingViaEvent' threw an exception.</p>
  
  <p>at ReactiveUI.WhenAnyMixin.WhenAny[TSender,TRet,T1,T2] (TSender
  This, System.Linq.Expressions.Expression<code>1[TDelegate] property1,
  System.Linq.Expressions.Expression</code>1[TDelegate] property2,
  System.Func`3[T1,T2,TResult] selector) [0x00000] in
  &lt;4aefaa9175534ecd872465be2cbe3a19>:0    at
  RxUIVIewModelUnitTesting.ViewModels.LoginViewModel..ctor
  (RxUIVIewModelUnitTesting.Services.IAuthenticationSystem
  authenticationSystem, System.Reactive.Concurrency.IScheduler
  scheduler) [0x000b1] in
  /Users/giusepecasagrande/Git/Giusepe/RxUIVIewModelUnitTesting/src/RxUIVIewModelUnitTesting.ViewModels/LoginViewModel.cs:58
  at
  RxUIVIewModelUnitTesting.ViewModels.UnitTests.LoginViewModelTest.Setup
  () [0x00020] in
  /Users/giusepecasagrande/Git/Giusepe/RxUIVIewModelUnitTesting/src/RxUIVIewModelUnitTesting.ViewModels.UnitTests/LoginViewModelTest.cs:28
  at (wrapper managed-to-native)
  System.Reflection.MonoMethod:InternalInvoke
  (System.Reflection.MonoMethod,object,object[],System.Exception&amp;)   at
  System.Reflection.MonoMethod.Invoke (System.Object obj,
  System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder
  binder, System.Object[] parameters, System.Globalization.CultureInfo
  culture) [0x00038] in
  /private/tmp/source-mono-4.6.0/bockbuild-mono-4.6.0-branch/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class/corlib/System.Reflection/MonoMethod.cs:305</p>
  
  <p>--TypeInitializationException   at ReactiveUI.ReactiveNotifyPropertyChangedMixin..cctor () [0x00020] in
  &lt;4aefaa9175534ecd872465be2cbe3a19>:0 
  --TypeInitializationException   at ReactiveUI.Registrations+&lt;>c.b__0_7 () [0x00000] in
  &lt;4aefaa9175534ecd872465be2cbe3a19>:0    at
  ReactiveUI.DependencyResolverMixins+&lt;>c__DisplayClass0_0.b__0
  (System.Func<code>1[TResult] f, System.Type t) [0x00000] in
  &lt;4aefaa9175534ecd872465be2cbe3a19&gt;:0    at
  ReactiveUI.Registrations.Register (System.Action</code>2[T1,T2]
  registerFunction) [0x00149] in &lt;4aefaa9175534ecd872465be2cbe3a19>:0<br>
  at ReactiveUI.DependencyResolverMixins.InitializeReactiveUI
  (Splat.IMutableDependencyResolver resolver) [0x00028] in
  &lt;4aefaa9175534ecd872465be2cbe3a19>:0    at
  ReactiveUI.RxApp+&lt;>c.&lt;.cctor>b__0_0 () [0x0000d] in
  &lt;4aefaa9175534ecd872465be2cbe3a19>:0    at
  Splat.Locator.RegisterResolverCallbackChanged (System.Action callback)
  [0x00039] in &lt;66ec575cc13f4eaea0cbad3add11aa6e>:0    at
  ReactiveUI.RxApp..cctor () [0x00010] in
  &lt;4aefaa9175534ecd872465be2cbe3a19>:0</p>
</blockquote>

<p>So I put a sample project with this happening (<a href=""https://github.com/GiusepeCasagrande/RxUIVIewModelUnitTesting"" rel=""nofollow noreferrer"">https://github.com/GiusepeCasagrande/RxUIVIewModelUnitTesting</a>), any help here would be appreciate, even if it's to ""no way that's gonna work"", because then I'll just move back to Test Harness and start using Cake for VSTS.</p>

<p>edit: I forgot to say: I'm running this on a Mac with XS. So I asked a friend to test the same solution on a Windows/VS and it works! Now seems that I have found some Mac/mono limitations here.</p>
",https://stackoverflow.com/questions/41851356/reactiveui-viewmodel-unit-testing,"['xamarin', 'mono', 'xamarin-studio', 'reactiveui']",432,FALSE,1,0
Unit testing custom AuthorizationFilterAttribute,"<p>We did custom authorization attribute and want this to be covered by unit test. Unfortunately I don't have any idea how to unit test such kind of staff. Could you advise please?<br/></p>

<pre><code>public override void OnAuthorization(HttpActionContext actionContext)
   {
      var ts = GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(TokenService));
        try
            {
                var token = GetHeader(actionContext.Request);
                if (token == null)
                {
                    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                    {
                        Content = new StringContent(""Token not found"")
                    };
                    return;
                }
                else
                {
                    var tks = ts as TokenService;
                    var tkn = Task.Run(() =&gt; tks.FindToken(token)).Result;
                    if (tkn.ValidTill &gt; DateTime.Now)
                    {
                        var us = GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(UserService));
                        var uss = us as UserService;
                        var user = Task.Run(() =&gt; uss.FindByTokenValue(token)).Result;
                        if (user != null)
                        {
                            if (!_roles.Contains(user.RoleName))
                            {
                                actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden)
                                {
                                    Content = new StringContent(""You role permission is not enough"")
                                };
                                return;
                            }
                            var identity = new Identity { Name = user.Login, IsAuthenticated = true };
                            var principal = new GenericPrincipal(identity, new[] { user.RoleName });
                            actionContext.RequestContext.Principal = principal;
                            Thread.CurrentPrincipal = principal;
                            base.OnAuthorization(actionContext);
                            _roles = null;
                        }
                        else
                        {
                            actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                            {
                                Content = new StringContent(""User not found"")
                            };
                            return;
                        }
                    }
                    else
                    {
                        actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                        {
                            Content = new StringContent($""Token valid till {tkn.ValidTill}"")
                        };
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                {
                    Content = new StringContent($""Authorization error: {ex.Message}"")
                };
                return;
            }
        }
</code></pre>

<p>Test that should be passed:
- Token is exist.
- Token is valid for this DateTime.
- User role is valid.
P.S. Please don't ask me why we did this instead of using ASP.NET Identity, that's was not my solution, I prefer ASP.NET Identity.</p>
",https://stackoverflow.com/questions/41629611/unit-testing-custom-authorizationfilterattribute,"['c#', 'unit-testing', 'authorization']",836,TRUE,1,1
AngularJS unit testing dependencies,"<p>I need to make unit tests in AngularJS project, I've never done it before and I got a problems in first step.</p>

<p>Packages:</p>

<pre><code>""jasmine-core"": ""^2.8.0"",
""karma"": ""^1.7.1"",
""karma-chrome-launcher"": ""^2.2.0"",
""karma-jasmine"": ""^1.1.0""
</code></pre>

<p>Controller (as syntax):</p>

<pre><code>angular.module('app').controller('LoginController', ['models.store', function(MODELS) {
    var vm = this;
    vm.account = new MODELS.Account('', '');
}]);
</code></pre>

<p>So I need to write a test for this controller property - <em>account</em></p>

<p>Test:</p>

<pre><code>describe('LoginTest', function() {
    var MODELS;

    beforeEach(module('app'));

    beforeEach(inject(function($injector) {
        inject(function() {
            MODELS = jasmine.createSpy('models.store');
        });
    }));

    beforeEach(inject(function($controller) {
        scope = $controller('LoginController', {'models.store': MODELS});
    }));

    it('Account model values should be empty', function() {
        expect(scope.account.login).toBe('');
    });
});
</code></pre>

<p>And I get <strong>""TypeError: MODELS.Account is not a constructor""</strong></p>

<p>Injecting factory code:</p>

<pre><code>angular.module('app.models').factory('models.store', function() {
    return {
        Account: function() {
            this.login = login || '';
            this.password = password || '';
        }
    }
});
</code></pre>

<p>What do I do wrong? What should I do to make the test correct?</p>
",https://stackoverflow.com/questions/47090994/angularjs-unit-testing-dependencies,"['javascript', 'angularjs', 'unit-testing']",173,FALSE,1,2
Retrofit RxJava Unit Testing,"<p>I'm using the Mosby Library to implement MVP pattern along with Retrofit and RxJava for my api calls almost exactly as it's done <a href=""https://medium.com/@nurrohman/a-simple-android-apps-with-mvp-dagger-rxjava-and-retrofit-4edb214a66d7"" rel=""nofollow noreferrer"">here</a>. </p>

<p>I have just began with UI and Unit testing and while I've had no problems mocking my api during my UI testing (with MockWebServer), I can't figure out how to mock my api for Unit testing.</p>

<p>I've looked at the answer <a href=""https://stackoverflow.com/a/39828581/4092656"">here</a> but it seems like it's still trying to make the real api call since I see it's landing on onError (network exception) instead of onNext/onComplete. If I user MockWebServer it will also land on onError but not the network type.</p>

<p>What I want: When the presenter makes the api call :</p>

<pre><code>signUpSubscriber = api.signUpUser(credentials)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(new Subscriber&lt;User&gt;()
</code></pre>

<p>To not actually make the call, but rather to be able to give it the ""User"" object it's supposed to return so that the test can pass on to onNext and onComplete</p>
",https://stackoverflow.com/questions/43079020/retrofit-rxjava-unit-testing,"['android', 'unit-testing', 'mockito', 'rx-java', 'retrofit2']",805,FALSE,1,0
Javascript/jQuery unit testing,"<p>I want to start writing Unit tests for my JS code, i have never done this before, never had the need, but as my projects are ever expanding think it's time to start.</p>

<p>Now writing the tests themselves i don't think will be an issue for functional javascript code (a function that adds two numbers together), i don't have that, all of those things are server side (as it's much more complex than adding two digits), what i do have (and a lot of it) is dynamic Javascript (and jQuery) which is intertwined with HTML and my question is, how (and can i) write tests for that? Same code bellow (completely lorem ispum)</p>

<pre><code>MyHelperClass = function () {
    var _someBool = false;

    return {
        Initialize: function () {
            MyHelperClass.ChangeALotOfThings(""init"");
        },

        ChangeALotOfThings: function (arg1) {
            var $someID = $(""#myID"");
            var _anotherBool = true;

            if ($someID.lenght) {
                var moreHTML = MyOtherHelperClass.ThisFunctionWillReturnSomeHTML();

                $someID.find("".myClass"").append(moreHTML);
                $("".someClass"").on(""click"", function(){
                    // do some code | i.e. basic Accordion 
                });

                if (_anotherBool &amp;&amp; arg1) {
                    var result = $.ajax({
                            url: ""test.html"",
                            context: document.body
                        });

                    $someID.prepend(result);    
                }
            } else {
                // do other similar stuff
            }
        }
    }
}

MyHelperClass.Initialize();
</code></pre>

<p>This is a random example i wrote in 5min (some .js/jQuery syntax isn't even correct) and think the code doesn't even make a lot of sense, bottom line is, can something like this be Unit Tested?</p>

<p>I was looking into Tape.js and Jasmine.js but couldn't find much.
Thank you for any comments and/or advice regarding writing Unit Test for .js/jQuery.</p>
",https://stackoverflow.com/questions/43188192/javascript-jquery-unit-testing,"['javascript', 'jquery', 'html', 'unit-testing']",62,FALSE,1,0
Android Studio Unit Testing,"<p>I am doing the unit testing on android studio, I create a test case in test class and on every time when I run that it give different output but when I debug it give me fine out put.It may be problem of caching or something else. I have also tried Invalidate studio and clean project but still occurring. Please Help.</p>
",https://stackoverflow.com/questions/43673160/android-studio-unit-testing,"['android', 'android-studio', 'android-testing']",110,TRUE,1,1
Mockito Android Unit testing,"<p>I have MVP in my application. Presenter has interface</p>

<pre><code>public interface ILoginPresenter&lt;V&gt; extends Presenter&lt;V&gt; {
    void logUserIn(String email, String password, String deviceToken, String deviceType); 
}
</code></pre>

<p>Realization has RX Single</p>

<pre><code> mLoginSubscription = mModel.logUserIn(email, password, deviceToken, deviceType)
            .compose(RxUtil.setupNetworkSingle())
            .subscribe(new Subscriber&lt;User&gt;() {
                @Override
                public void onCompleted() {
                    Timber.i(""Log in complete"");
                }

                @Override
                public void onError(Throwable e) {
                    Timber.e(e, ""Retrofit could not get User."");

                    getView().dismissProgressDialog();
                }

                @Override
                public void onNext(UserResponseRetrofit response) {
                    Timber.i(""Retrofit is attempting to get User"");
                    mSaveModel.saveUser(user);
                    getView().dismissProgressDialog();
                    getView().goToMenuActivity();
                }
            });
</code></pre>

<p>Also i have module for Dagger </p>

<pre><code>@Module
public class ModelModule {
    @Provides
    @ScreenScope
    public ILoginModel provideLoginModel(LoginModel p) {
        return p;
    }
}
</code></pre>

<p>My unit test look like next:</p>

<pre><code>@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21, manifest = ""/src/main/AndroidManifest.xml"")
public class LoginPresenterTest {

    public static final String SOME_OTHER_TOKEN = ""someOtherToken"";
    private AppComponent mAppComponent;
    private LoginComponent mLoginComponent;
    private ILoginView mockView;
    private ModelModule mockModel;
    private ILoginPresenter mLoginPresenter;

    @Before
    public void setup() {
        // Creating the mocks
        mockView = Mockito.mock(ILoginView.class);
        mockModel = Mockito.mock(ModelModule.class);

        ILoginModel mock = Mockito.mock(ILoginModel.class);
        User urr = Mockito.mock(User.class);
        Mockito.when(mockModel.provideLoginModel(null)).thenReturn(mock);
        Mockito.when(mock.logUserIn("""", """", """", """")).thenReturn(ScalarSynchronousSingle.just(urr));

        mAppComponent = DaggerAppComponent.builder()
                .appModule(new AppModule(RuntimeEnvironment.application))
                .build();

        mLoginComponent = DaggerLoginComponent.builder()
                .appComponent(mAppComponent)
                .modelModule(mockModel)
                .presenterModule(new PresenterModule())
                .build();

        mLoginPresenter = mLoginComponent.provideLoginPresenter();
        mLoginPresenter.setView(mockView);
    }

    @Test
    public void testLogin() {
        mLoginPresenter.logUserIn("""", """", """", """");
        try {
            java.lang.Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Mockito.verify(mockView).dismissProgressDialog();
    }
</code></pre>

<p>So using Dagger I need to build Presenter correctly. For this purposes, I am trying to use Mockito.when. Firstly look like this line doesn't work</p>

<pre><code>Mockito.when(mockModel.provideLoginModel(null)).thenReturn(mock);
</code></pre>

<p>The target purpose is to use my own Model realization which return Single.</p>

<p>don't really understand why my mock of ModelModule doesn't work?</p>
",https://stackoverflow.com/questions/43093061/mockito-android-unit-testing,"['android', 'unit-testing', 'mockito', 'dagger-2']",603,TRUE,1,2
Unit Testing in Retrofit for Callback,"<p>Here i got a sample of code in presenter. How do i make write a test for onSuccess and onFailure in retrofit call</p>

<pre><code>public void getNotifications(final List&lt;HashMap&lt;String,Object&gt;&gt; notifications){

        if (!"""".equalsIgnoreCase(userDB.getValueFromSqlite(""email"",1))) {
            UserNotifications userNotifications =
                    new UserNotifications(userDB.getValueFromSqlite(""email"",1),Integer.parseInt(userDB.getValueFromSqlite(""userId"",1).trim()));
            Call call = apiInterface.getNotifications(userNotifications);
            call.enqueue(new Callback() {
                @Override
                public void onResponse(Call call, Response response) {
                    UserNotifications userNotifications1 = (UserNotifications) response.body();


                    if(userNotifications1.getNotifications().isEmpty()){
                        view.setListToAdapter(notifications);
                        onFailure(call,new Throwable());
                    }
                    else {
                        for (UserNotifications.Datum datum:userNotifications1.getNotifications()) {
                            HashMap&lt;String,Object&gt; singleNotification= new HashMap&lt;&gt;();
                            singleNotification.put(""notification"",datum.getNotification());
                            singleNotification.put(""date"",datum.getDate());
                            notifications.add(singleNotification);
                        }
                        view.setListToAdapter(notifications);
                    }
                }

                @Override
                public void onFailure(Call call, Throwable t) {
                    call.cancel();
                }
            });
        }
    }

}
</code></pre>

<p>How do i write unittesting to cover all cases for this piece of code.</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/45160055/unit-testing-in-retrofit-for-callback,"['android', 'unit-testing', 'junit', 'mockito', 'retrofit2']",13369,TRUE,16,2
Unit Testing involving databases,"<p>Suppose I have a directory</p>

<pre><code>  home/user/my_python_scripts/
                   /src
                       /my_script.py
                   /tests
                      /test_my_script.py
</code></pre>

<p>I am running some unit tests to test <code>my_script.py</code> from the <code>~/my_python_scripts/test</code> directory. I am importing the function from <code>my_script</code> in to my <code>test_my_script.py</code>.</p>

<p>The problem however arises since the function in <code>my_script.py</code> imports two other functions from another script. Those two functions query a database for specific data. I am mocking and patching these two functions in my test script however when I run <code>pytest</code> on this script the function ends up querying the database regardless. I looked at the two functions that <code>my_script.py</code> uses. Each of them queries a different database and furthermore one of the functions ends up using three other functions that live in the same file as it does.</p>

<p>Am I not accounting for these functions and/or database properly in my unit test? I cannot share the code since it is proprietary but I am more than happy to share my unit test code below:</p>

<pre><code>from pytest_mock import mocker

params = [(3141, 55)]
raw_data = [{'a': 'fizz', 'b': 'buzz', 'c': 'foo', 'd': 'hello'}]
descriptors = ['taxi', 3141, 55, 1]

def test_get_data(mocker):
    setattr(get_data, 'get_raw_data', params)
    mocker.patch.object(get_data, 'get_raw_data')
    get_data.get_raw_data.return_value = params
    setattr(get_data, 'get_data_by_day', raw_data)
    mocker.patch.object(get_data, 'get_data_by_day')
    get_data.get_data_by_day.return_value = raw_data
    assert get_data('taxi', 3141, '1', '3') == raw_data, descriptors
</code></pre>

<p>Looking for any advice as well as tips.</p>
",https://stackoverflow.com/questions/43083061/unit-testing-involving-databases,"['python', 'unit-testing']",67,TRUE,1,1
Jasmine Unit Testing Angularjs,"<p>I'm new to Unit Testing.  I have followed the tutorials and I have everything
configured on node.js via npm.  I have done some describe and it just to get the feel for ho things are set up and my spec runner is fine. The problem I'm trying to get test on controllers figured out but I run in a snag and been trying to figure things out for a while but I continue to get the same error so I thought I would reach out.  </p>

<p>I'm trying to do a simple test on a LoginController but I continue to get the same error. I can't point out what I'm doing wrong.  Trying to get over this hurdle.</p>

<p>TypeError: angular.mock.module is not a function:</p>

<p>spec runner index html file.</p>

<pre><code>&lt;!doctype html&gt;
   &lt;html&gt;
 &lt;head&gt;
&lt;title&gt;Jasmine Spec Runner&lt;/title&gt;
&lt;link rel=""stylesheet"" href=""../bower_components/jasmine-core/lib/jasmine-core/jasmine.css""&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;script src=""../My Documents/My Website/AngularLogin-
      Registration/js/angular-1.6.0.js""&gt;&lt;/script&gt;
&lt;script src=""../My Documents/My Website/AngularLogin-Registration/js/angular-route-1.6.0.min.js""&gt;&lt;/script&gt;

&lt;script src=""../bower_components/jasmine-core/lib/jasmine-core/jasmine.js""&gt;&lt;/script&gt;
&lt;script src=""../bower_components/jasmine-core/lib/jasmine-core/jasmine-html.js""&gt;&lt;/script&gt;
&lt;script src=""../bower_components/jasmine-core/lib/jasmine-core/boot.js""&gt;&lt;/script&gt;

&lt;!-- include source files here... --&gt;


&lt;!--&lt;script src=""//code.jquery.com/jquery-3.1.1.min.js""&gt;&lt;/script&gt;--&gt;
&lt;!--&lt;script src=""//code.angularjs.org/1.6.0/angular-cookies.min.js""&gt;&lt;/script&gt;--&gt;
&lt;script src=""../My Documents/My Website/AngularLogin-Registration/js/angular-mock.js""&gt;&lt;/script&gt;
&lt;script src=""../My Documents/My Website/AngularLogin-Registration/js/app.js""&gt;&lt;/script&gt;
&lt;script src=""../My Documents/My Website/AngularLogin-Registration/login/login.controller.js""&gt;&lt;/script&gt;

&lt;!-- include spec files here... --&gt;
&lt;script src=""spec/test.js""&gt;&lt;/script&gt;
</code></pre>

<p>
</p>

<p>Here is my test file.</p>

<pre><code>describe('LoginController test', function () {
    beforeEach(angular.mock.module('app'));
    beforeEach(angular.mock.inject(function(_$controller_){
        $controller = _$controller_;
}));
describe('$scope.grade', function() {
      it('sets the strength to ""strong"" if the password length is &gt;8 chars', 
       function() {
        var $scope = {};
        var controller = $controller('LoginController', { $scope: $scope });
  $scope.password = 'longerthaneightchars';
  $scope.grade();
      expect($scope.strength).toEqual('strong');
    });
       });
          });
</code></pre>

<p>Thanking You In Advance
PDH</p>
",https://stackoverflow.com/questions/43702287/jasmine-unit-testing-angularjs,"['angularjs', 'node.js', 'jasmine', 'bower']",203,FALSE,1,1
Unit testing mongoose method,"<p>I'm new to unit testing, can't wrap my head what I should unit test given this function ? Note that I don't want to hit database, so I need to mock/stub  mongoose built in function ""findById"" maybe ? Can't figure it out big picture here :).
Not asking for complete solution, just an idea or some pointer to go from there. </p>

<pre><code>LyricSchema.statics.like = function(id) {
  const Lyric = mongoose.model('lyric');

  return Lyric.findById(id)
    .then(lyric =&gt; {
      ++lyric.likes;
      return lyric.save();
    })
}
</code></pre>

<p>Thank you !</p>
",https://stackoverflow.com/questions/43937613/unit-testing-mongoose-method,"['javascript', 'node.js', 'mongodb', 'unit-testing', 'mongoose']",162,TRUE,0,2
Angular 4 - router.url unit testing,"<p>How do I mock router.url in angular 4 unit testing?</p>

<p>I use router.url in ngOnint in my component but in my test the value for router.url is '/'</p>
",https://stackoverflow.com/questions/46271968/angular-4-router-url-unit-testing,"['angular', 'unit-testing']",7970,TRUE,8,3
Unit testing in PyCharm,"<p>Alright, so I am doing Python Crash Course exercies for unit tests chapter and I can't quite get it to work using PyCharm.</p>

<p>My ""project"" literally consists of two trivial files:</p>

<p>city_functions.py:</p>

<pre><code>def city_country(city, country):
    result = '{0}, {1}'.format(city.title(), country.title())
    return result
</code></pre>

<p>test_cities.py:</p>

<pre><code>import unittest
from city_functions import city_country


class CityTestCase(unittest.TestCase):
    """"""Tests for 'city_functions.city_country' function.""""""

    def test_city_country(self):
        result = city_country('london', 'england')
        self.assertEqual(result, 'London, England')

unittest.main()
</code></pre>

<p>Now, when I am trying to run the module from PyCharm I get:</p>

<pre><code>(...)
----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK
</code></pre>

<p>but it works, when I run it from command line:</p>

<pre><code>&gt; python -m test_cities
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
</code></pre>

<p>Are there any shenanigans with PyCharm configuration to get it to work? I've read some posts about naming conventions (that test function and the whole module MUST start with 'test', but it already does in my case).</p>
",https://stackoverflow.com/questions/45305695/unit-testing-in-pycharm,"['python', 'unit-testing', 'pycharm']",4703,TRUE,0,2
Unit testing for SparkPost,"<pre><code>package johnny.me.controller;

import com.sparkpost.Client;
import com.sparkpost.model.responses.Response;
import com.sparkpost.exception.SparkPostException;
import org.springframework.stereotype.Service;

/**
* Sparkpost class sends the email using
* the sendmessage methood
*/
</code></pre>

<p>@Service
   public class SparkPostController {</p>

<pre><code>    String API_KEY = ""API KEY"";
         Client client = new Client(API_KEY);
         private static String from_email = ""me@yahoo.com"";
         private static String subject = ""Time equation"";
         private static String text = """";

    public Response sendMessage(String recipient, String message) throws SparkPostException {
         return client.sendMessage(from_email,recipient,subject,
                 text,message);
    }

}
</code></pre>

<p>This my sparkpost controller class. Trying to make a unit test/ mock to send message. Also known as regression test Please be very specific fairly new to unit testing. Have my class made under the testing folder.Thats all i got.</p>
",https://stackoverflow.com/questions/42905933/unit-testing-for-sparkpost,"['java', 'unit-testing', 'regression-testing', 'sparkpost']",249,FALSE,0,1
Unit testing os.File.Write call,"<p>I want to unit test a function that calls <code>os.File.Write()</code> and want 100% coverage. </p>

<p>This function returns <code>n</code> and an error. Inducing an error is easy. All I need is to close the file. How can I induce no write error and a value <code>n</code> different of the written data length ?</p>

<p>It looks like I should create a dummy os.File on which I can control the error returned. Unfortunately, os.File is not an interface. </p>

<p><strong>Edit</strong>: Based on the answer of PeterOS, and after double checking the documentation, the <code>Write()</code> method, whether is for the <code>io.Writer</code> or the <code>io.File</code> will always return the length of the written slice if <code>err</code> is nil. As a consequence, it appears that my question is pointless. I learned something important, thanks. I have some code to cleanup. </p>

<p>As a side note, it seems that my quest of the 100% code coverage is criticized. I'll try to explain my rational to achieve 100% coverage. I'm open to discussion.</p>

<ol>
<li><p>the 100% coverage I'm talking about means that 100% of the code lines are executed by the unit tests. I use the Go tools to measure that.</p></li>
<li><p>100% code coverage does obviously not mean 0% bugs. It is easy to get 100% code coverage without properly testing all possible or critical use cases. </p></li>
<li><p>the danger of the 100% coverage metric is that it becomes the focus and goal of the unit tests writing. The first goal of unit testing, which is to find bugs, is then pushed in the background.</p></li>
<li><p>writing unit tests to reach 100% coverage adds a significant cost to development and it's not fun to do. I know that.</p></li>
<li><p>the only benefit I see in 100% code coverage is to make it easy to detect and locate untested code addition. </p></li>
</ol>

<p>Whether the benefit beats the costs depends on the way you program. I program like a painter modifying and adding code here and there as needed. I keep all the plan and road map in my head. If I had to add or update tests and check them, I would loose track of what I was doing. So I first code the feature and then test it. The 100% code coverage make it very simple for me to locate the code addition for which I need to add tests. It's a heuristic. Not a method to detect all missing tests. </p>

<p><strong>Conclusion</strong>: it is indeed important to not confuse 100% code coverage with 0% bugs. It is also important to be aware that targeting 100% code coverage may pass to the background the first goal of testing which is to find bugs. Finally, reaching 100% coverage has a cost that must be balanced by its benefit which is to easily detect and locate untested code, otherwise it's a waste of resource. Make your pick based on your personal development methodology. I made mine.</p>
",https://stackoverflow.com/questions/43916000/unit-testing-os-file-write-call,"['unit-testing', 'go']",3873,TRUE,-2,3
Android unit testing Realm,"<p>I can't find a solution to do some unit testing on Android. I am trying to test Realm interaction with a service. 
I tried using PowerMockito and in memory solution, but in each case it's not working for me. </p>

<p>I am looking for a solution to check the data stored in realm. Could someone can give me a resource or a hint?</p>

<p><strong>Edit: My sample code for inMemory</strong></p>

<p><strong>build.gradle</strong></p>

<pre><code>testInstrumentationRunner ""android.support.test.runner.AndroidJUnitRunner""
...
dependencies {
  androidTestImplementation 'com.android.support:support-annotations:26.1.0'
  androidTestImplementation 'com.android.support.test:runner:1.0.1'
  androidTestImplementation 'com.android.support.test:rules:1.0.1'
}
</code></pre>

<p><strong>Sync Service</strong></p>

<pre><code>@RunWith(AndroidJUnit4::class)
class StateSyncServiceTest {

    lateinit var mockRealm: Realm

    @Before
    fun setup() {
        val testConfig = RealmConfiguration.Builder().inMemory().name(""test-realm"").build()
        mockRealm = Realm.getInstance(testConfig)
    }

    @Test
    fun shouldBeAbleToGetDefaultInstance() {
        Assert.assertThat(Realm.getDefaultInstance(), `is`(mockRealm)) //NOT WORKING WRONG OBJECT
    }

    @Test
    fun correctSynchronizationPerformed() {
        //given
        val organizationsDTO = listOf&lt;OrganizationDTO&gt;(OrganizationDTO(3, ""Organization Mauritius"", true))
        val statesDTO = listOf&lt;StateDTO&gt;(StateDTO(2, 3, false, ""State 2""), StateDTO(3, 3, false, ""State 3""))
        val stateDAO = StateDAO()
        val stateSynchroService = StateSyncService()

        //when
        stateSynchroService.synchronize(statesDTO, organizationsDTO)

        //then
        val resultRealm = stateDAO.findAll()
        Assert.assertEquals(statesDTO.size, resultRealm?.size) //WRONG DATA, MIX PRODUCTION AND TEST
    }
}
</code></pre>

<p>Plus the data aren't erased from the emulator. I still can get the realm db file with the mix data after execution..</p>
",https://stackoverflow.com/questions/47282634/android-unit-testing-realm,"['android', 'unit-testing', 'realm']",1642,TRUE,0,1
Unit testing with classes,"<p>Write a unit test for addInventory(). Call redSweater.addInventory() with parameter sweaterShipment. Print the shown error if the subsequent quantity is incorrect. Sample output for failed unit test given initial quantity is 10 and sweaterShipment is 50:
Beginning tests.
   UNIT TEST FAILED: addInventory()
Tests complete.
Note: UNIT TEST FAILED is preceded by 3 spaces.</p>

<hr>

<pre><code>#include &lt;iostream&gt;
using namespace std;

class InventoryTag {
public:
   InventoryTag();
   int getQuantityRemaining() const;
   void addInventory(int numItems);

private:
   int quantityRemaining;
};

InventoryTag::InventoryTag() {
    quantityRemaining = 0;
}

int InventoryTag::getQuantityRemaining() const {
   return quantityRemaining;
}

void InventoryTag::addInventory(int numItems) {
   if (numItems &gt; 10) {
      quantityRemaining = quantityRemaining + numItems;
   }
}

int main() {
   InventoryTag redSweater;
   int sweaterShipment = 0;
   int sweaterInventoryBefore = 0;

   sweaterInventoryBefore = redSweater.getQuantityRemaining();
   sweaterShipment = 25;

   cout &lt;&lt; ""Beginning tests."" &lt;&lt; endl;

   // FIXME add unit test for addInventory




   cout &lt;&lt; ""Tests complete."" &lt;&lt; endl;

   return 0;
}
</code></pre>
",https://stackoverflow.com/questions/47734778/unit-testing-with-classes,"['c++', 'unit-testing', 'visual-c++']",2897,FALSE,-2,2
unit testing rxjs 5,"<p>So I'm still very new to rxjs. </p>

<p>Currently using tape js for unit tests in my code base. I've looked into marble diagram testing, but it's really not clicking for me. </p>

<p>My question : 
How to unit test a search call that makes use of rxjs observable? I'm interested in asserting that the _handleSearchResults function is called with the observable completes. Similarly how to test if the observable fails, that the _handleSearchError is called. </p>

<p>this.searchSubject is a rx subject</p>

<pre><code>searchChanged(query) {
    this.searchSubject.next(query);
}
</code></pre>

<p>Search subject is defined with the switchmap which is really what I want to unit test when calling searchChanged.</p>

<pre><code> this.searchSubject.switchMap(searchQuery =&gt; {
        return Rx.Observable.fromPromise(this._queryAutoComplete(searchQuery));
    })
    .subscribe(this._handleSearchResults.bind(this), this._handleSearchError.bind(this));
</code></pre>
",https://stackoverflow.com/questions/44401939/unit-testing-rxjs-5,"['javascript', 'unit-testing', 'rxjs']",214,FALSE,0,0
c# Unit Testing errors,"<p>im trying to get familiar with unit testing , but I keep getting this annoying error and I have no idea why. I made a class that just divides 2 numbers.</p>

<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DivideNum
{
    class Program
    {
        public static int doStuff(int num1, int num2)
        {
            int result = num1 / num2;
            return result;


        }
        static void Main(string[] args)
        {

        }
    }
}
</code></pre>

<p>I then made my unit test </p>

<pre><code>using DivideNum;
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {

            //arrange
            int a = 10;
            int b = 2;
            int result = 5;

            //act

        }
    }
}
</code></pre>

<p>i added a reference to my DivideNum namespace and added using DivideNum , but i still cant get a reference to the DivideNum class in my testing class. It wont show up at all in my testing code. why cant i use my DivideNum class in my Test class?</p>
",https://stackoverflow.com/questions/44428023/c-unit-testing-errors,"['c#', 'unit-testing']",71,TRUE,0,2
Array List Unit Testing,"<pre><code>@Test
public void testGetDoctors() {
    System.out.println(""GetDoctors"");
    List&lt;Doctor&gt; result = Operations.GetDoctors();
    assertThat(result, hasItem (""Henry""));     
}
</code></pre>

<p>I wrote this recently and I noticed that the Doctor List keeps bringing up an error . I am wondering if I should add an import for the Doctor Array List or not.</p>
",https://stackoverflow.com/questions/42923523/array-list-unit-testing,['java'],45,TRUE,-2,2
Unit testing basic auth,"<p>I have some problems to unit testing my authentication method. This is my method :</p>

<pre><code>    public int basicAuth(String username, String password) throws IOException {
    connection = (HttpURLConnection)new URL(""URL"").openConnection();
    connection.setRequestMethod(""GET"");
    String basicAuth = username + "":"" + password;
    String wrap = ""Basic "" + new String(Base64.encode(basicAuth.getBytes(),Base64.NO_WRAP));
    connection.setRequestProperty(""Authorization"",basicAuth);
    connection.connect();
    //InputStream in = connection.getInputStream();
    int response = connection.getResponseCode();
    Log.v(""Reponse HTTP : "", String.valueOf(response));
    responseCode_ = connection.getResponseCode();
    return responseCode_;
}
</code></pre>

<p>This is my testing code : </p>

<pre><code>@Test
public void basicAuth() throws Exception {
    PowerMockito.mockStatic(Base64.class);
    String username = ""username"";
    String password = ""password"";
    int responseCode = 200;
    int integer = auth.basicAuth(username, password);
    assertEquals(responseCode, integer);
}
</code></pre>

<p>I'm using Powermock because i have an error with Base64 which is not mocked. And now, when i use Powermock i have this error : </p>

<blockquote>
  <p>java.lang.NullPointerException
      at java.lang.String.(String.java:566)
      at com.example.local.app_android.Authentification.basicAuth(Authentification.java:96)
      at com.example.local.app_android.AuthentificationTest.basicAuth(AuthentificationTest.java:34)
      /.../
      at java.lang.reflect.Method.invoke(Method.java:498)
      at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)</p>
</blockquote>

<p>(I have cut the middle of the error)</p>

<p>Do someone have an idea of where the error comes from?</p>

<p>EDIT N°1</p>

<pre><code>testCompile 'org.powermock:powermock-api-mockito:1.6.1'
testCompile 'org.powermock:powermock-module-junit4-rule-agent:1.6.1'
testCompile 'org.powermock:powermock-module-junit4-rule:1.6.1'
testCompile 'org.powermock:powermock-module-junit4:1.6.1'
testCompile 'org.mockito:mockito-core:1.10.19'
</code></pre>
",https://stackoverflow.com/questions/43606605/unit-testing-basic-auth,"['java', 'android', 'unit-testing', 'basic-authentication']",1950,TRUE,0,2
MVC Unit Testing - System.NullReferenceException,"<p>I am totally brand new to Unit Testing and am trying to learn off my own back. I have failed at the first hurdle and despite countless books and web sites I cannot see what I am doing wrong... Please can someone tell me?? I have an Action ViewResult as follows I am looking to test:</p>

<pre><code>    public ViewResult ProductList()
    {
        List&lt;ProductItem&gt; allProducts = CallGetAllProducts();
        return View(allProducts);
    }
</code></pre>

<p>You can see it is calling a function:</p>

<pre><code>    private List&lt;ProductItem&gt; CallGetAllProducts()
    {
        var productFilePath = Server.MapPath(@""~/CSV/products.csv"");
        var products = new ProductsCSV();

        return (products.GetAllProductsFromCSV(productFilePath));
    }
</code></pre>

<p>Which is in turn calling the following function:</p>

<pre><code>    public List&lt;ProductItem&gt; GetAllProductsFromCSV(string csvPath)
    {
        String[] csvData = File.ReadAllLines(csvPath);
        List&lt;ProductItem&gt; result = new List&lt;ProductItem&gt;();

        foreach (string csvrow in csvData)
        {
            var fields = csvrow.Split(',');
            ProductItem prod = new ProductItem()
            {
                ID = Convert.ToInt32(fields[0]),
                Description = fields[1],
                Item = fields[2][0],
                Price = Convert.ToDecimal(fields[3]),
                ImagePath = fields[4],
                Barcode = fields[5]
            };
            result.Add(prod);
        }
        return result;
    }
</code></pre>

<p>I have a Unit Test project I have created with the following test method in the appropriate ControllerTest file:</p>

<pre><code>    [TestMethod()]
    public void ProductListGetsViewResult()
    {
        ProductsController controller = new ProductsController();
        ViewResult result = controller.ProductList() as ViewResult;
        Assert.IsNotNull(result);
    }
</code></pre>

<p>I have all the correct references setup as far as I can see, however the results of running this test are coming back with:</p>

<p><em>Result Message:<br>
Test method ShoppingBasket.Controllers.Tests.ProductsControllerTests.ProductListGetsViewResult threw exception: 
System.NullReferenceException: Object reference not set to an instance of an object.</em></p>

<p>It looks like the problem is with the calling of the ViewResult in the 'Act' part of the process... But Why, I dont know.</p>
",https://stackoverflow.com/questions/45495624/mvc-unit-testing-system-nullreferenceexception,"['c#', 'asp.net-mvc', 'unit-testing']",50,FALSE,0,0
React Application Unit Testing,"<p>I am currently testing a React app using Selenium for Functional Testing. Selenium is used to launch the app on the browser, and simulate user actions and keep asserting/verifying at each step.</p>

<p>However it gets very tedious to debug these tests as the UI automation is heavy as it has to actually launch the browser , wait for pages to load (which at times is a pain given the unstable environments).</p>

<p>I read about some frameworks  like chai which are very lightweight and very fast since I do not have to wait for the pages to load.</p>

<p>On similar lines , can anyone suggest me ways to do the complete functional testing of this application where I can bypass the UI actions (as done by Selenium) , for eg. instead of making selenium to go around clicking and simulation user actions on the UI, is there any way we can load a react component and try to simulate certain user actions through the code and then do the functional verification from the DB and also have data providers for my test . For eg - I have a set of data to be passed to my test function , and this test will run for all the set of data and keep asserting respectively.</p>

<p>Will something like unit testing/white box testing work ?
Will testing frameworks like chai help me with this requirement ?</p>

<p>Do suggest me any other approach if you know.</p>
",https://stackoverflow.com/questions/42796835/react-application-unit-testing,"['unit-testing', 'reactjs', 'jasmine', 'chai', 'white-box-testing']",1378,TRUE,0,1
Unit testing Grails controller,"<p>how to preform unit test this function</p>

<pre><code>private void secondaryRepError(def secRepCmd) {

    def repProfile = springSecurityService?.currentUser?.representativeProfile
    def productTypes = representativeManagementService.getAssignedProductTypes(repProfile)
    def facilities = representativeManagementService.getAssignedFacilities(repProfile)
    def facilityType = representativeManagementService.getFacilityType()
    def listOfRetail   = representativeManagementService.listOfFacilities(facilities?.toList(), facilityType?.retail)
    def listOfLpg      = representativeManagementService.listOfFacilities(facilities?.toList(), facilityType?.lpg)
    def listOfPipeline = representativeManagementService.listOfFacilities(facilities?.toList(), facilityType?.pipeline)
    def listOfRelated  = representativeManagementService.listOfFacilities(facilities?.toList(), facilityType?.related)
    render view:'addSecondaryRep', model: [secondaryRepInstance: secRepCmd, appType: ApplicationType.getAll(), productTypes: productTypes, facilities: facilities, retailFacility: facilityType?.retail, lpgFacility: facilityType?.lpg, pipelineFacility: facilityType?.pipeline, facFacility: facilityType?.related, listOfRetail: listOfRetail, listOfLpg: listOfLpg, listOfPipeline: listOfPipeline, listOfRelated:listOfRelated]


  }
</code></pre>
",https://stackoverflow.com/questions/45629086/unit-testing-grails-controller,"['unit-testing', 'grails', 'controller']",30,TRUE,0,1
Angularjs unit testing image.onload,"<p>I have the following angularjs service which I would like to unit test:</p>

<pre><code>angular.module(""services"")
.factory(""imageService"", function($q)
{
    var load = function(options)
    {
        var deferred = $q.defer();
        var image = new Image();

        image.onload = function()
        {
            deferred.resolve(image.width);
        };
        image.src = options.imageSource;

        return deferred.promise;
    };

    return {
        load: load
    };
});
</code></pre>

<p>My unit test looks like this:</p>

<pre><code>describe(""imageService"", function()
{
    beforeEach(module(""services""));
    beforeEach(function()
    {
        inject(function($injector)
        {
            imageService = $injector.get(""imageService"");
        });
    });

    it(""should return image width"", function(done)
    {
        imageService.load({
            imageSource: ""data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD//gATQ3JlYXRlZCB3aXRoIEdJTVD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wgARCAACAAIDAREAAhEBAxEB/8QAFAABAAAAAAAAAAAAAAAAAAAACP/EABQBAQAAAAAAAAAAAAAAAAAAAAD/2gAMAwEAAhADEAAAAVSf/8QAFBABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQABBQJ//8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAgBAwEBPwF//8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAgBAgEBPwF//8QAFBABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQAGPwJ//8QAFBABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQABPyF//9oADAMBAAIAAwAAABCf/8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAgBAwEBPxB//8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAgBAgEBPxB//8QAFBABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQABPxB//9k=""
        })
        .then(function(width)
        {
            expect(width).to.equal(2);
            done();
        });
    });
});
</code></pre>

<p>The problem I am having is that the onload call is asynchronous, and normally you would use <code>$timeout.flush()</code> after the call to flush the deferred task, but since it takes some time for the image to load, you cannot flush the task after you have called the function, and thus the <code>done()</code> function will never be called causing the test to fail.</p>

<p>Libraries used:</p>

<ul>
<li>angular 1.6.6</li>
<li>angular-mocks 1.5.5</li>
<li>karma 1.1.2  </li>
<li>karma-mocha 1.1.1</li>
<li>karma-chai 0.1.0</li>
</ul>
",https://stackoverflow.com/questions/47333511/angularjs-unit-testing-image-onload,"['javascript', 'angularjs', 'image', 'unit-testing', 'onload']",523,FALSE,0,0
Unit Testing in SalesForce,"<p>I found a similar answer here:</p>

<p><a href=""https://stackoverflow.com/questions/4372202/how-to-unit-test-works-in-salesforce"">How to unit test works in salesforce?</a></p>

<p>and here: <a href=""https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_controller_error_handling.htm"" rel=""nofollow noreferrer"">https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_controller_error_handling.htm</a></p>

<p>But those didn't really seem to answer my particular question.</p>

<p>I ""stubbed out"" some test classes. We <em>should have</em> been doing this from the beginning, but they handed a group of developers a SalesForce project who have never done SalesForce before...then put us on a time crunch. They told us at the time not to worry about unit testing, and now we find out that SalesForce requires 75% or greater code coverage in order to be in production.</p>

<p>Anyway, I know I can test for state in methods that return void, and I know I can test the return type of methods that have them.</p>

<p>But my question is: How do I test values that are supposed to be input through a VisualForce page? Do I just create the class and fill in the info?</p>

<p>I'm much more familiar with Unit Testing in C#, to the point where I use Roy Osherove's test method naming convention, or at least my version of it.</p>

<p>Additionally, how would I test pages that have a querystring? I'm assuming I would do a PageReference with some kind of query string, but unit tests, in general, should run independently.</p>

<p>My main concern is running the tests dynamically (i.e. dynamic record IDs), and what happens if there are no records (i.e. if the dev/testing environment get wiped).</p>

<p>So, thoughts on this?</p>
",https://stackoverflow.com/questions/42838219/unit-testing-in-salesforce,"['unit-testing', 'salesforce', 'apex-code']",831,TRUE,0,2
Node.js unit testing problems,"<p>I have a web app that I have to perform unit tests on. I'm really new to testing so am having some problems. I am using mocha and chai and have been able to set up a simple test to pass that simply checks a function to return a string, but am struggling to apply tests to my more complicated functions. </p>

<p>The code I am trying to create tests for is to test a function that removes users items from a shopping cart I have created. </p>

<pre><code> this.removeItem = function(id) {
        this.totalQty -= this.items[id].qty;
        this.totalPrice -= this.items[id].price;
        delete this.items[id];

    };
</code></pre>
",https://stackoverflow.com/questions/47816659/node-js-unit-testing-problems,"['javascript', 'node.js', 'unit-testing', 'web-applications']",27,FALSE,-1,1
How to suppress InMemoryEventId.TransactionIgnoredWarning when unit testing with in-memory database with transactions?,"<p>I'm using an EF Core in-memory database and I'm trying to run a unit test on a method that uses transactions:</p>
<pre class=""lang-cs prettyprint-override""><code>using (var transaction = await _context.Database.BeginTransactionAsync())
{
    _context.Update(item);
    result = await _context.SaveChangesAsync();

    // some other stuff

    transaction.Commit();
}
</code></pre>
<p>However, I'm getting this error from the test runner:</p>
<blockquote>
<p>System.InvalidOperationException: Warning as error exception for
warning 'InMemoryEventId.TransactionIgnoredWarning': Transactions are
not supported by the in-memory store. See
<a href=""http://go.microsoft.com/fwlink/?LinkId=800142"" rel=""noreferrer"">http://go.microsoft.com/fwlink/?LinkId=800142</a> To suppress this
Exception use the DbContextOptionsBuilder.ConfigureWarnings API.
ConfigureWarnings can be used when overriding the
DbContext.OnConfiguring method or using AddDbContext on the
application service provider.</p>
</blockquote>
<p>How do I suppress that error?</p>
",https://stackoverflow.com/questions/44080733/how-to-suppress-inmemoryeventid-transactionignoredwarning-when-unit-testing-with,"['c#', 'asp.net-core', 'entity-framework-core', 'in-memory-database']",13903,TRUE,67,2
Unit Testing Pandas DataFrame,"<p>I'm looking to develop a unit test where it compares two DataFrames and returns True if their lengths are the same and if not returns the difference in length as well as what the missing output rows are.</p>

<p>For instance:
Example 1:</p>

<pre><code>df1 = {0,1,2,3,4}
df2 = {0,1,2,3,4}
</code></pre>

<blockquote>
  <p>True</p>
</blockquote>

<p>Example 2:</p>

<pre><code>df1 = {0,1,2,3,4}
df2 = {0,2,3,4}
</code></pre>

<blockquote>
  <p>False. 2 is missing. </p>
</blockquote>

<p>Notifies me that the second item in df1 is missing from df2. </p>

<p>Is this something that is possible?</p>
",https://stackoverflow.com/questions/45180564/unit-testing-pandas-dataframe,"['python', 'unit-testing', 'pandas', 'dataframe', 'diff']",3042,TRUE,0,2
Unit testing celery tasks directly,"<p>I know this will be seen as a duplicate, but I <strong>have</strong> looked around before asking this question, however all of the questions seem to be either outdated or don't help at all with my problem. This is where I've looked before writing this question:</p>

<ul>
<li><a href=""http://docs.celeryproject.org/en/latest/userguide/testing.html"" rel=""noreferrer"">Official Docs</a></li>
<li><a href=""https://stackoverflow.com/questions/12078667/how-do-you-unit-test-a-celery-task"">How do you unit test a Celery task?</a> (5 years old, all dead links)</li>
<li><a href=""https://stackoverflow.com/questions/31739246/how-to-unit-test-code-that-runs-celery-tasks"">How to unit test code that runs celery tasks?</a> (2 years old)</li>
<li><a href=""https://stackoverflow.com/questions/22314242/how-do-i-capture-celery-tasks-during-unit-testing"">How do I capture Celery tasks during unit testing?</a> (3 years old)</li>
</ul>

<hr>

<p>I'm currently working on a project that heavily uses Celery to handle asynchronous tasks; to make the entire code-base stable I'm writing unit tests for the entire project however I haven't been able to write <em>a single</em> working test for Celery so far.</p>

<p>Most of my code needs to keep track of the tasks that were run in order to determine wether or not all results are ready to be queried. This is implemented in my code as follows:</p>

<pre><code>@app.task(bind=True)
def some_task(self, record_id):
    associate(self.request.id, record_id)  # Not the actual DB code, but you get the idea

# Somewhere else in my code, eg: Flask endpoint
record = some_db_record()
some_task.apply_async(args=[record.id])
</code></pre>

<p>Since I don't have a *nix based machine to run my code on, I tried solving this by setting the always eager option to true, however this causes issues whenever any sub-task tries to query the result:</p>

<pre><code>@app.task(bind=True)
def foo(self): 
    task = bar.apply_async()
    foo_poll.apply_async(args=[task.id]) 

@app.task(bind=True, max_retries=None):
def foo_poll(self, celery_id)
    task =  AsyncResult(celery_id)
    if not task.ready():  # RuntimeError: Cannot retrieve result with task_always_eager enabled
        return self.retry(countdown=5)
    else:
        pass  # Do something with the result

@app.task
def bar():
    time.sleep(10)
</code></pre>

<p>I tried fixing this by patching the <code>AsyncResult</code> methods, however this caused issues as <code>self.request.id</code> would be <code>None</code>:</p>

<pre><code>with patch.object(AsyncResult, ""_get_task_meta"", side_effect=lambda: {""status"": SUCCESS, ""result"": None}) as method:
    foo()

@app.task(bind=True)
def foo(self):
    pass   # self.request.id is now None, which I need to track sub-tasks
</code></pre>

<p>Does anyone know how I could do this? Or if Celery is even worth using anymore? I'm at the point where I find the documentation and any questions related to testing so overwhelmingly complex I just feel like ditching it all together and just go back to multithreading.</p>
",https://stackoverflow.com/questions/45015662/unit-testing-celery-tasks-directly,"['python', 'unit-testing', 'celery']",5314,TRUE,7,3
Live unit testing exclude tests,"<p>I know it is possible to exclude the whole test project(s) from Live Unit Testing by right clicking on the test project and selecting the ""Live Unit Testing"" context menu.</p>

<p>But in my solution I have some long running/resource intensive tests, which I would like to exclude. Is it possible to exclude individual tests?</p>
",https://stackoverflow.com/questions/47157050/live-unit-testing-exclude-tests,"['visual-studio-2017', 'live-unit-tests']",5374,TRUE,7,2
FTP Route - Unit Testing,"<p>I have a camel route which:</p>

<ol>
<li>polls a FTP server for new XML files</li>
<li>downloads the files locally</li>
<li>validates the XML files against a XSD</li>
<li>splits the XML by categories into entities</li>
<li>transforms the entities into json</li>
<li>sends the json to a HTTP endpoint</li>
</ol>

<p>UPDATE: This works now</p>

<pre><code>@Component
public class FTPPoller extends RouteBuilder {
    XmlJsonDataFormat xmlJsonFormat = new XmlJsonDataFormat();

    @Override
    public void configure() throws Exception {

        from(""{{endpoint.ftp.server}}"")
                .id(""ftp-poller"")
                .log(""Found file ${file:name}."")
                .to(""{{endpoint.local.validation}}"");


        from(""{{endpoint.local.validation}}"")
                .id(""xml-validator"")
                .log(""Processing file ${file:name}."")
                .doTry()
                    .to(""validator:classpath:schema/fr-masterdata.xsd"")
                    .log(""File ${file:name} is valid."")
                    .to(""{{endpoint.local.processing}}"")
                .doCatch(org.apache.camel.ValidationException.class)
                    .log(""File ${file:name} is invalid."")
                    .to(""{{endpoint.local.error}}"")
                .end();

        from(""{{endpoint.local.processing}}"")
                .id(""xml-processor"")
                .split(xpath(""//flu:entities/category"")
                        .namespace(""flu"", ""hxxx://www.xxx.com"")
                ).streaming()
                .marshal(xmlJsonFormat)
                .to(""direct:category"")
                .end();

        from(""direct:category"")
                .id(""requestbin"")
                .log(""Processing category ${body}"")
                .setHeader(Exchange.HTTP_METHOD, constant(""POST""))
                .setHeader(Exchange.CONTENT_TYPE, constant(""application/json""))
                .to(""{{endpoint.requestbin}}"");

    }
}
</code></pre>

<p><strong><code>Tests</code></strong> :</p>

<pre><code>@RunWith(CamelSpringBootRunner.class)
@SpringBootTest(classes = {HbIntegrationApplication.class},
        properties = { ""camel.springboot.java-routes-include-pattern=**/FTPPoller*""})
public class FTPPollerTest {

    @Autowired
    protected ProducerTemplate producerTemplate;

    @EndpointInject(uri = ""{{endpoint.requestbin}}"")
    protected MockEndpoint requestbinEndpoint;

    @EndpointInject(uri = ""{{endpoint.local.error}}"")
    protected MockEndpoint localErrorEndpoint;

    @Before
    public void cleanDir() throws Exception {
        deleteDirectory(""hb"");
    }


    @Test
    @DirtiesContext
    public void testFileUploadSuccess() throws Exception {
        String fileContent = FileUtils.readFileToString(new File(""src/test/resources/test-files/category.xml""));

        requestbinEndpoint.expectedMessageCount(2);
        producerTemplate.sendBody(""file://hb/incoming"", fileContent);

        requestbinEndpoint.assertIsSatisfied();
    }

    @Test
    @DirtiesContext
    public void testFileUploadFailure() throws Exception {

        localErrorEndpoint.expectedMessageCount(1);
        requestbinEndpoint.expectedMessageCount(0);

        producerTemplate.sendBody(""file://hb/incoming"", ""invalidContent"");

        localErrorEndpoint.assertIsSatisfied();
        requestbinEndpoint.assertIsSatisfied();
    }
}
</code></pre>

<p><strong><code>application.properties</code></strong> :</p>

<pre><code>endpoint.ftp.server=file://hb/incoming
endpoint.local.validation=file://hb/validation
endpoint.local.processing=file://hb/processing
endpoint.local.error=mock:file://hb/error
endpoint.requestbin=mock:requestbin
</code></pre>

<p>Remaining question is:</p>

<p>If I have defined the following property:</p>

<pre><code>endpoint.local.processing=mock:file://hb/processing
</code></pre>

<p>my test fails with:</p>

<pre><code>Caused by: java.lang.UnsupportedOperationException: You cannot consume from this endpoint
</code></pre>

<p>Is there any way to define which routes should be included in my Unit test?</p>
",https://stackoverflow.com/questions/46231749/ftp-route-unit-testing,"['spring-boot', 'apache-camel', 'spring-boot-test']",818,FALSE,0,1
Cryptography Unit Testing Logic,"<p>I'm relatively new to C# and I've just learnt cryptography (symmetric and one way hash). Now I can surely create two methods that encrypt/decrypt text and they work fine. I encountered my problem when I tried to unit test the two methods. What do I test exactly? If I use for example TDES or AES to encrypt, there's not a single online encrypter that gives the same cipher text ( let alone that no online encrypter gives the same result of another one) for me to use as an expected result to compare with my actual result, so how do I verify that my method actually encrypted my text? Also are there any other logical tests to run on such methods?</p>
",https://stackoverflow.com/questions/44001027/cryptography-unit-testing-logic,['c#'],294,FALSE,0,0
Unit testing with jasmine,"<p>I'm new to jasmine. Here is my directive</p>

<pre><code>(function () {
'use strict';
angular.module('AccountPortal.components').directive('forgotPasswordForm', forgotPasswordForm);
forgotPasswordForm.$inject = ['Account', 'accountApi', 'emailApi', 'utils', 'Exception'];
function forgotPasswordForm(Account, accountApi, emailApi, utils, Exception) {

    var directive = {};
    directive.restrict = 'E';
    directive.templateUrl = 'app/components/_utilities/forgotPasswordForm/forgotPasswordForm.html';
    directive.controller = ['$scope', ctrl];
    directive.controllerAs = 'vm';
    directive.scope = {};

    return directive;

    function link(scope, elem, attrs, vm) {

    }

    function ctrl($scope) {
        var vm = this;
        vm.formSubmitted = false;
        vm.email = '';
        vm.forgotPasswordSubmit = function () {
            if (!vm.forgotPasswordForm.$valid) {
                return;
            }
            delete vm.forgotPasswordForm.email.$error.accountNotFound;
            Account.customerForgotPassword(vm.email)
                .then(function (response) {
                    emailApi.sendForgotPasswordEmail(response.data.EmailAddress, response.data.FirstName, response.data.LastName, response.data.QueryString);
                    vm.formSubmitted = true;
                })
                .catch(function (response) {
                    if (response.status === 400) {
                        $scope.forgotPasswordForm.email.$error.accountNotFound = true;
                    }
                    else {
                        throw new Exception();
                    }
                });
        };
    }
}
</code></pre>

<p>})();</p>

<p>Here I've tested my controller and the function in it to be defined. In the 3rd It block, I want to test if the emailApi.sendForgotPasswordEmail function is invoked with (response.data.EmailAddress, response.data.FirstName, response.data.LastName, response.data.QueryString) arguments</p>

<pre><code>describe('forgotPasswordForm directive', function () {
var ctrl,emailApi, $componentController;
beforeEach(module('AccountPortal'));
beforeEach(inject(function (_$componentController_, _emailApi_) {
    $componentController = _$componentController_;
    ctrl = $componentController('forgotPasswordForm');
    emailApi=_emailApi_;
    ctrl.forgotPasswordForm = {
        $valid: true,
        email: {
            $error:{}
        }
    };
}));

beforeEach(inject(function(_Account_) {
    Account = _Account_;
}));


it('forgotPasswordForm controller should be defined', function () {
    expect(ctrl).toBeDefined();
});

it('forgotPasswordSubmit function should be defined', function () {
    expect(ctrl.forgotPasswordSubmit).toBeDefined()
});

it('new password should be sent if email exists', function () {


});
</code></pre>

<p>});</p>

<p>Thanks for help guys, I really cant figure out</p>
",https://stackoverflow.com/questions/43996809/unit-testing-with-jasmine,"['javascript', 'unit-testing', 'jasmine']",41,FALSE,0,1
unit testing @Suspended AsyncResponse controller,"<p>I am upgrading to be fully asynchronous and I have an exsiting test that unit tests the controller with mocked dependencies and tests the various paths. I can't figure out how to convert this unit test. I am using dropwizard/jersey and the method I want to test looks like this now </p>

<pre><code> @POST
public void getPostExample(final Map body, @Suspended final AsyncResponse
 asyncResponse){}
</code></pre>

<p>The old test uses mockito/junit and uses <code>@InjectMocks</code> for the controller which it then calls the method on <code>getPostExample</code> and asserts some info on the response. The services it calls are mocked but I can't find much when I search for how to manually get this to return data.  I can get access to the AsyncResponse but in the real code that calls the resume with results. Should I be calling resume in my test? </p>
",https://stackoverflow.com/questions/44637439/unit-testing-suspended-asyncresponse-controller,"['java', 'unit-testing', 'junit', 'jersey', 'dropwizard']",2867,TRUE,6,2
Python unit testing Class properties,"<p>I am trying to figure out if there's a way to (unit test) verify that the property and the setter is actually called to set the name attribute.</p>

<pre><code>class DummyName:
    def __init__(self):
        self.name = ''

    @property
    def name(self):
        return self.name

    @name.setter
    def name(self, name):
        if not isinstance(name, basestring):
            raise Exception('Name must be a string.')
        self.name = name
</code></pre>

<p>Trying to do something like this...</p>

<pre><code>@mock.patch.object(DummyName, 'name', new_callable=PropertyMock)
def testNameProperty(self, mock_name):
    MockName = Mock()
    mock_name.return_value = MockName
    dummyName = DummyName()
    dummyName.name = 'test_name'
    # assert setter is called to set the name
    # assert name is called to get the name
    # assert name is 'test_name'
</code></pre>

<p>Seems like name() and setter are never accessed. the Anyone has a better idea? Thanks!</p>
",https://stackoverflow.com/questions/45680483/python-unit-testing-class-properties,"['python', 'python-unittest', 'python-unittest.mock']",7603,TRUE,6,2
Mock datetime.datetime.now() while unit testing,"<pre><code>@pytest.mark.parametrize(""test_input,expected_output"", data)
def test_send_email(test_input, expected_output):
    emails = SendEmails(email_client=MagicMock())
    emails.send_email = MagicMock()
    emails.send_new_email(*test_input)
    emails.send_email.assert_called_with(*expected_output)
</code></pre>

<p>I am looking to mock datetime.datetime.now() which is called in the send_new_email method. I am unsure how to do it however.</p>

<p>I tried creating a new datetime object</p>

<pre><code> datetime_object = datetime.datetime.strptime('Jun 1 2017  1:33PM', 
                                          '%b %d %Y %I:%M%p')
</code></pre>

<p>and then overriding datetime.datetime.now</p>

<pre><code>datetime.datetime.now = MagicMock(return_value=datetime_object)
</code></pre>

<p>However, I get the error</p>

<blockquote>
  <p>TypeError: can't set attributes of built-in/extension type 'datetime.datetime'</p>
</blockquote>

<p><em>This question was marked as duplicate of Python: Trying to mock datetime.date.today() but not working</em> </p>

<p><a href=""https://stackoverflow.com/questions/4481954/python-trying-to-mock-datetime-date-today-but-not-working"">Python: Trying to mock datetime.date.today() but not working</a></p>

<p>I had already tried this solution but I could not get it to work. I cannot install freezegun due to the project requirements.</p>

<p>I have created a new class in the test file</p>

<pre><code>class NewDate(datetime.date):
@classmethod
def today(cls):
    return cls(2010, 1, 1)
datetime.date = NewDate
</code></pre>

<p>But I have no idea how to get the SendEmails class to use this.</p>
",https://stackoverflow.com/questions/47413871/mock-datetime-datetime-now-while-unit-testing,"['python', 'datetime']",7599,TRUE,6,1
Angular 2: How to mock ChangeDetectorRef while unit testing,"<p>I have just started with Unit-Testing, and I have been able to mock my own services and some of Angular and Ionic as well, but no matter what I do <code>ChangeDetectorRef</code> stays the same.</p>

<p>I mean which kind of sorcery is this?</p>

<pre><code>beforeEach(async(() =&gt; 
    TestBed.configureTestingModule({
      declarations: [MyComponent],
      providers: [
        Form, DomController, ToastController, AlertController,
        PopoverController,

        {provide: Platform, useClass: PlatformMock},
        {
          provide: NavParams,
          useValue: new NavParams({data: new PageData().Data})
        },
        {provide: ChangeDetectorRef, useClass: ChangeDetectorRefMock}

      ],
      imports: [
        FormsModule,
        ReactiveFormsModule,
        IonicModule
      ],
    })
    .overrideComponent(MyComponent, {
      set: {
        providers: [
          {provide: ChangeDetectorRef, useClass: ChangeDetectorRefMock},
        ],
        viewProviders: [
          {provide: ChangeDetectorRef, useClass: ChangeDetectorRefMock},
        ]
      }
    })
    .compileComponents()
    .then(() =&gt; {
      let fixture = TestBed.createComponent(MyComponent);
      let cmp = fixture.debugElement.componentInstance;

      let cdRef = fixture.debugElement.injector.get(ChangeDetectorRef);

      console.log(cdRef); // logs ChangeDetectorRefMock
      console.log(cmp.cdRef); // logs ChangeDetectorRef , why ??
    })
  ));
</code></pre>

<hr>

<pre><code> it('fails no matter what', async(() =&gt; {
    spyOn(cdRef, 'markForCheck');
    spyOn(cmp.cdRef, 'markForCheck');

    cmp.ngOnInit();

    expect(cdRef.markForCheck).toHaveBeenCalled();  // fail, why ??
    expect(cmp.cdRef.markForCheck).toHaveBeenCalled(); // success

    console.log(cdRef); // logs ChangeDetectorRefMock
    console.log(cmp.cdRef); // logs ChangeDetectorRef , why ??
  }));
</code></pre>

<hr>

<pre><code>@Component({
  ...
})
export class MyComponent {
 constructor(private cdRef: ChangeDetectorRef){}

 ngOnInit() {
   // do something
   this.cdRef.markForCheck();
 }
}
</code></pre>

<p>I have tried everything , <code>async</code>, <code>fakeAsync</code>, <code>injector([ChangeDetectorRef], () =&gt; {})</code>.</p>

<p>Nothing works.</p>
",https://stackoverflow.com/questions/41421807/angular-2-how-to-mock-changedetectorref-while-unit-testing,"['unit-testing', 'angular', 'typescript', 'jasmine', 'testbed']",23402,TRUE,35,6
Observable.fromPromise empty during unit testing,"<p><code>loadAdList$</code> is an Observable that taps into the <code>actions$</code> stream:</p>

<pre><code>loadAdList$: Observable&lt;Action&gt; = this.actions$
    .ofType&lt;adActions.Load&gt;(adActions.LOAD)
    .switchMap((action) =&gt; {
      return Observable.fromPromise(store.findAll('ad', action.payload)
        .then((ads) =&gt; {
          return new adActions.LoadSuccess(ads);
        })
        .catch((err) =&gt; {
          return new adActions.LoadFail(err);
        }));
    });
</code></pre>

<p>It works in the browser, there is no problem with it. However, I want to unit test it as well:</p>

<pre><code>actions$ = hot('-a', { a: loadAction });
const storeResponse = Promise.resolve(mockAds);
const expected$ = cold('-c', { c: loadSuccessAction });

spyOn(store, 'findAll').and.returnValue(storeResponse);

expect(effects.loadAdList$).toBeObservable(expected$);
</code></pre>

<p>The test fails with the following:</p>

<pre><code>Expected 

to deep equal 
    {""frame"":10,""notification"":{""kind"":""N"",""value"":{""payload"":""[
    ...
</code></pre>

<p>I believe the issue has something to do with the <code>store.findAll</code> method returning a promise. This is based on the results of the following test:</p>

<pre><code>.switchMap((action) =&gt; {
  // This test will pass
  return Observable.from([new adActions.LoadSuccess(mockAds)]);

  // This test will fail
  return Observable.fromPromise(Promise.resolve(new adActions.LoadSuccess(mockAds)));

});
</code></pre>
",https://stackoverflow.com/questions/46106985/observable-frompromise-empty-during-unit-testing,"['typescript', 'promise', 'jasmine', 'observable']",2128,TRUE,5,1
Angular2 unit testing : testing a component&#39;s constructor,"<p>All is in the title : <strong>how can one test what is done in the component's constructor ?</strong></p>

<p>For your information, I am using a service that requires a setting, and I would like to see if the 2 methods that I call in the constructor are called correctly. </p>

<p>My component's constructor : </p>

<pre><code>constructor(
  public router: Router,
  private profilService: ProfileService,
  private dragula: DragulaService,
  private alerter: AlertService
) {
  dragula.drag.subscribe((value) =&gt; {
    this.onDrag(value);
  });
  dragula.dragend.subscribe((value) =&gt; {
    this.onDragend(value);
  });
}
</code></pre>
",https://stackoverflow.com/questions/43498055/angular2-unit-testing-testing-a-components-constructor,"['unit-testing', 'angular', 'angular2-testing']",52145,TRUE,20,3
Unit testing a Web API controller,"<p>I am fairly new to unit testing and I am trying to create a unit test for a Web API contoller that I have created which returns a list of brands.</p>

<p>My Web API controller <code>Get()</code> method looks like this:</p>

<pre><code>[HttpGet(""/api/Brands/Get"", Name = ""GetBrands"")]
public async Task&lt;IActionResult&gt; Get()
{
    var brands = await _brandsService.GetAll(null, ""Image"");
    return Json(brands);
}
</code></pre>

<p>The generic service method looks like this:</p>

<pre><code>public async Task&lt;List&lt;T&gt;&gt; GetAll(
    Func&lt;IQueryable&lt;T&gt;, 
    IOrderedQueryable&lt;T&gt;&gt; orderBy = null, 
    string includeProperties = null)
{
    return await _genericRepository.GetAll(orderBy, includeProperties);
}
</code></pre>

<p>and the generic repo method looks like this:</p>

<pre><code>public async Task&lt;T&gt; Get&lt;TKey&gt;(Expression&lt;Func&lt;T, bool&gt;&gt; filter = null, string includeProperties = """", bool noTracking = false)

{
    includeProperties = includeProperties.Trim() ?? string.Empty;
    IQueryable&lt;T&gt; query = Context.Set&lt;T&gt;();

    if (noTracking)
    {
        query.AsNoTracking();
    }

    if (filter != null)
    {
        query = query.Where(filter);
    }

    foreach (var includeProperty in includeProperties.Split
        (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
    {
        query = query.Include(includeProperty);
    }

    return await query.SingleOrDefaultAsync();
}
</code></pre>

<p>This is working and I am returning a list of brands from the database.</p>

<p>Now I tried to create a Unit test for this:</p>

<pre><code>[SetUp]
public void Setup()
{
    Brands = new List&lt;Brand&gt;
    {
        new Brand
        {
            Id = 1,
            Name = ""Adidas"",
            ImageId = 1
        },
        new Brand
        {
            Id = 2,
            Name = ""Nike"",
            ImageId = 2
        },
        new Brand
        {
            Id = 3,
            Name = ""Puma"",
            ImageId = 3
        }
    };
}

[Test]
public async Task Get_ReturnsAAListOfBrands()
{
    //Arrange
    var mockService = new Mock&lt;IGenericService&lt;Brand&gt;&gt;();
    mockService.Setup(repo =&gt; repo.GetAll(null, null)).Returns(Task.FromResult(Brands));
    var controller = new BrandsController(mockService.Object);

    //Act
    var result = await controller.Get();
    //Assert
}
</code></pre>

<p>however the result is always null.  Am I testing this correctly or do I need to change my unit test code to verify that the mock service has three items stored?</p>
",https://stackoverflow.com/questions/41722191/unit-testing-a-web-api-controller,"['c#', 'unit-testing', 'asp.net-web-api', 'nunit', 'moq']",31536,TRUE,13,1
unit testing spyOn observable service in angular2,"<p>I have a service (ChildService) which depends on another service (InteractWithServerService). The latter service (InteractWithServerService) is used to make server calls and return an observable of ""any"" type. For simplicity let's assume it returns an observable. I am trying to write a unit test for ChildService. </p>

<p>ChildService</p>

<pre><code>@Injectable()
export class ApplicationService {
    constructor(private  interactWithServerService:InteractWithServerService){;}

    public GetMeData():string {
        var output:string;       
        this.interactWithServerService.get(""api/getSomeData"").
           subscribe(response =&gt;{console.log(""server response:"", response);
           output=response});        
         return output;
    }
}
</code></pre>

<p>ServerInteractionService</p>

<pre><code>@Injectable()
export class InteractWithServerService {        
    constructor(private http: Http) {
        ;
    }    
    get(url: string): Observable&lt;any&gt; {        
        return this.http.get(this.url);
    }       
}
</code></pre>

<p>The test case works fine when I mock the dependent service. i.e.,</p>

<pre><code>class MockInteractWithServerService {
    get() {
        return Observable.of(""some text"");
    }           
}

describe('Service:ChildService', () =&gt; {
    let childService: ChildService;

    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            providers: [
             { provide: InteractWithServerService, useClass: MockInteractWithServerService },
                ChildService],
        });


    beforeEach(inject([ChildService], (actualService: ChildService) =&gt; {
        childService= actualService;        
    }));

    fit('should call server-call testCall()', () =&gt; {
        let actualReturnvalue= childService.GetMeData();        
        expect(actualReturnvalue).toBe(""some text"");
    });
});
</code></pre>

<p>The above method is not preferred as I might end up writing ""n"" mock classes for ""n"" dependencies. So I want to create my unit tests using spyOn.
However, the test case doesn't work and throws ""Error: No provider for Http!"". While I understand what the error is, I would like to know why it is thrown although I am spying on the dependent service. Looks like the ""spyOn"" is not working.</p>

<pre><code>describe('Service:ChildService', () =&gt; {
    let childService: ChildService;

    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            providers: [
             InteractWithServerService,
                ChildService],
        });

        spyOn(InteractWithServerService.prototype, 'get').and
             .callFake(()=&gt;      
          {return Observable.of(""some text"");});       
    });
    beforeEach(inject([ChildService], (actualService: ChildService) =&gt; {
        childService= actualService;        
    }));

    fit('should call server-call testCall()', () =&gt; {
        let actualReturnvalue= childService.GetMeData();        
        expect(actualReturnvalue).toBe(""some text"");
    });
});
</code></pre>

<p>Am I missing something obvious?</p>
",https://stackoverflow.com/questions/42358747/unit-testing-spyon-observable-service-in-angular2,"['angular', 'typescript', 'unit-testing']",61372,TRUE,19,3
Unit testing javascript (NOT node),"<p>I am scratching my head at this one, I must have missed something really obvious.</p>

<p>I have a .Net ASP MVC Web app, developed with VS2015, in which I have written some library javascript code. I would like to have some simple tests for this javascript code that I can run in my dev environment, on my own machine. I have no IIS server locally. (The server side code is fine, I use NUnit and VSs Testrunner).</p>

<p>I have read about Mocha (and used it back end), QUnit etc - but anything whose installation and use instructions start <code>npm install</code> and talks about running grunt jobs is not what I am after. </p>

<p>Can someone point me in the right direction / educate me? </p>
",https://stackoverflow.com/questions/44948750/unit-testing-javascript-not-node,"['javascript', 'testing', 'client-side']",116,FALSE,4,1
Unit Testing - Some difficulties mocking,"<p>I'm working with some legacy code which I require to write some unit tests for. There is data access method with the following signature.</p>

<pre><code>Task ExecuteReaderAsync(string procedureName, Parameters procedureParameters, 
    params Action&lt;System.Data.IDataReader&gt;[] actions);
</code></pre>

<p>which there is an implementation in the class i'm testing similar to this</p>

<pre><code>private async Task&lt;CustomObject&gt; GetCustomObject(int id) 
{
    CustomObject obj = null;
    await db.ExecuteReaderAsync(""nameOfProcedure"", some parameters, 
    dr =&gt;
    {
        obj = new CustomObject()
        {
            Prop1 = dr[""Col1""],
            Prop2 = dr[""Col2""]
        }
    }
    return obj;
}
</code></pre>

<p>What I'm struggling with is being able to control the values returned by <code>GetCustomObject</code>. If <code>ExecuteReaderAsync</code> actually returned something I could have a set up like this. </p>

<pre><code>mockDataAccess.Setup(x =&gt; x.ExecuteReaderAsync(""nameOfProcedure"", It.IsAny&lt;Parameters&gt;()))
    .Returns(Task.FromResult(new CustomeObject() { prop1 = ""abc"", prop2 = ""def""};));
</code></pre>

<p>But the logic for specifying the values is an <code>Action&lt;IDataReader&gt;</code> which I don't control. I'm wondering if there are any tricks I could employ to do what I want, 
i.e. control the value of the object returned by <code>GetCustomObject</code>.</p>
",https://stackoverflow.com/questions/41811691/unit-testing-some-difficulties-mocking,"['c#', 'unit-testing', 'moq']",1022,TRUE,4,1
Unit Testing complex Observable flows,"<p>I have the following function, which (I think) returns a compound observable:</p>

<pre><code>test(cell) {
   const observ1 = this.store.select('range').flatMap((val: IRange) =&gt; {return this.getCellOEE(val.value)});
   const observ2 = this.getCellOEE(cell);
   return Observable.merge(observ1, observ2);
}
</code></pre>

<p>I am using this in an angular 4 service, and trying to unit test with jasmine and karma.</p>

<p>So I am mocking store like this:</p>

<pre><code>class mockStore {
  select(): Observable&lt;IRange&gt; {
    return Observable.of({value: 'daily', start: moment(), end: moment()}, {value: 'monthly', start: moment(), end: moment()})
  }
}
</code></pre>

<p>and then I have the following test:</p>

<pre><code> it('should update result on store change', fakeAsync(inject(
    [MockBackend, OeeService],
    (backend: MockBackend, s: OeeService) =&gt; {
      const urls = [];

      backend.connections.subscribe((connection: MockConnection) =&gt; {
        const req: any = connection.request;
        urls.push(req.url);
        if (req.method === RequestMethod.Get &amp;&amp; req.url === 'api/getLine/data' req.headers.get('range') === 'daily') {
          connection.mockRespond(new Response(new ResponseOptions({ body: { data: 12 } })));
        }
        if (req.method === RequestMethod.Get &amp;&amp; req.url === 'api/getLine/data' &amp;&amp;
          req.headers.get('range') === 'monthly') {
          connection.mockRespond(new Response(new ResponseOptions({ body: { data: 15 } })));
        }
      });
      let value;
      s.test('powders').subscribe(val =&gt; {
        value = val;
      })

      tick();
      expect(value).toEqual(12);
      tick();
      expect(value).toEqual(15);
    })
  ));
</code></pre>

<p>I hope it is clear what I am trying to achieve, so when the <code>test()</code> function is initially called, a straight forward http call is made, but then my mocked store should release a change in params, map that to an http request with the new params and then return a different value.</p>

<p>I currently get the first <code>expect()</code> passing, but the second failing with:</p>

<blockquote>
  <p>Expected 12 to contain 15</p>
</blockquote>

<p>So I think there is a timing issue? Any ideas how I can resolve this? I think the test is important to verify, because then I can sue some good old TDD to prove whether this approach works. </p>

<h1>Update:</h1>

<p>Here is my full unit test <a href=""https://gist.github.com/georgeedwards/82f28ae77e2323e82028f3dedf82bd2f"" rel=""nofollow noreferrer"">file</a></p>
",https://stackoverflow.com/questions/43766574/unit-testing-complex-observable-flows,"['angular', 'rxjs', 'reactive-programming', 'observable', 'ngrx']",4295,TRUE,4,1
UWP unit testing with Jenkins,"<p>It is not really an issue I would like to ask today but I search best practices to unit testing a UWP application with Jenkins.</p>

<p>First, I created a Unit Test App for my main application and, on my development machine, I generated appx package using MSBuild command line tool. It works well and I can also execute unit tests with the VS Test console.
Then I tried to automate it with Jenkins on my build server. But the MSBuild command does not work. I have no issue but it produces no output. After lot of research (without any success), my question is the following:</p>

<p>What is the best way to make UWP unit testing with a result dashboard using Jenkins?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/47938100/uwp-unit-testing-with-jenkins,"['unit-testing', 'jenkins', 'msbuild', 'uwp', 'continuous-integration']",229,FALSE,4,1
Ionic 2 NavController unit testing,"<p>I'm kinda new to unit testing in Angular 2 and Ionic 2.</p>

<p>I am trying to test the <code>login()</code> method below</p>

<pre><code>export class LoginPage {

  constructor(public navCtrl: NavController) {}

  login() {
    this.navCtrl.setRoot(TabsPage);
  }
}
</code></pre>

<p>With the following test</p>

<pre><code>import { ComponentFixture, async } from '@angular/core/testing';
import { TestUtils } from '../../test';
import { LoginPage } from './login';
import { TabsPage } from '../tabs/tabs';

let fixture: ComponentFixture&lt;LoginPage&gt; = null;
let instance: any = null;

describe('Login Page', () =&gt; {

  beforeEach(async(() =&gt; TestUtils.beforeEachCompiler([LoginPage]).then(compiled =&gt; {
    fixture = compiled.fixture;
    instance = compiled.instance;
  })));

  it('changes root nav to TabsPage on login()', () =&gt; {
    spyOn(instance.navCtrl, 'setRoot');
    instance.login();
    expect(instance.navCtrl.setRoot).toHaveBeenCalledWith(TabsPage);
  });
});
</code></pre>

<p>But I get the following error</p>

<pre><code>Error: &lt;spyOn&gt; : setRoot() method does not exist
</code></pre>

<p>I followed <a href=""http://lathonez.github.io/2017/ionic-2-unit-testing/"" rel=""nofollow noreferrer"">this tutorial</a> for set up. </p>

<p>I must be missing something. Is <code>instance.navCtrl</code> the right thing to be spying on?</p>
",https://stackoverflow.com/questions/41970496/ionic-2-navcontroller-unit-testing,"['unit-testing', 'angular', 'ionic2']",2324,TRUE,3,1
Unit testing for rest call,"<p>I am currently at a loss with unit testing a method that calls a REST service within it for messaging a status to this service.</p>

<p>I have a method like:</p>

<pre><code>public void informService(String state, BusinessObject bus) {

  Client client = null;
  Response response = null;
  try {

    client = new ResteasyClientBuilder()
                            .establishConnectionTimeout(10L, TimeUnit.MINUTES)
                            .socketTimeout(10L, TimeUnit.MINUTES)
                            .build();

      WebTarget target = client.target(""my.url"");

      MyDTO dto = new MyDTO();
      dto.state = state;

      response = target.request(""application/json"").put(Entity.json(dto));

      boolean ok = handleReturnCode(response.getStatus(), bus.getId());

      if (!ok) {
        throw new RuntimeException(""Invalid status"" + response.getStatus());
      }

      return ok;

  } catch (Exception e) {
  } finally {
    try {
      if (response != null) {
        response.close();
      }
      if (client != null)
        client.close();
    } catch (Exception e) {
  }
}
</code></pre>

<p>So in the method there is a call to a REST service which is evaluated within the method. How can I unit test this behaviour?</p>
",https://stackoverflow.com/questions/42158464/unit-testing-for-rest-call,"['java', 'rest', 'unit-testing']",990,TRUE,3,2
Camel unit testing with MockEndPointsandSkip,"<p>Am a Camel newbie and am trying out some code to understand how the MockEndpoints functionality works, but it is not working. Here are my Camel routes that I want to unit test using MockEndpoints. The property values are defined in the application.properties file.</p>

<pre><code>from(""kafka:{{kafka.servers}}?topic={{kafka.consumer.topic}}&amp;groupId={{kafka.consumer.groupId}}"")
    .to(""direct:notify"");

from(""direct:notify"")
    .log(""direct:notfy"");
</code></pre>

<p>Here is my Test code which is failing the assertion of receiving 1 Exchange. It appears that the Producer is never sending the message to my Kafka Mockendpoint:</p>

<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest
@MockEndpointsAndSkip(""kafka:{{kafka.servers}}?*|direct:notify"")
public class NotificationApplicationTests {     

    @Autowired
    private CamelContext context;

    @Value(""${kafka.servers}"")
    private String kafkaServers;

    @EndpointInject(uri=""mock:kafka:{{kafka.servers}}"")
    private MockEndpoint mockKafka;

    @EndpointInject(uri=""mock:direct:notify"")
    private MockEndpoint mockDirect;

    @Autowired
    private ProducerTemplate notiProducer;

    @Test
    public void testMockEndpoints() throws Exception{                                       

        mockDirect.setExpectedMessageCount(1);
        mockDirect.whenAnyExchangeReceived( (Exchange exchange) -&gt; {
            //NEVER GETS HERE!!
            log.info(""MOCK DIRECT exchange received"");          
        });     

        String payload = ""{'email': 'test@gmail.com', 'data': 'ABC1234'}"";

        notiProducer.sendBody(mockKafka, payload);

        mockDirect.assertIsSatisfied();

    }

}
</code></pre>
",https://stackoverflow.com/questions/45241206/camel-unit-testing-with-mockendpointsandskip,['apache-camel'],4660,TRUE,3,1
Unit Testing Conditions for Directory.GetFiles,"<p>I've never used Unit tests before, but I am wanting to do so moving forward. Right now I have the simplest method I'm wanting to test: </p>

<pre><code>public void GetAvailableFiles(string rootFolder)
{
   string[] dirs = Directory.GetFiles(rootFolder);
}
</code></pre>

<p>My unit test for this is as follows:</p>

<pre><code>[Test]
public void CheckDirectory()
{     
   AvailableFile fileUpload = new AvailableFile();
   fileUpload.GetAvailableFiles(""C:\\Input"");      
}
</code></pre>

<p>When I debug this, I return all the files in my target location. However, I am struggling to come up with a valid condition in which this test can verify that it has passed. </p>

<p>My thinking was to have an expected count of files for this test. I have 10 files in there, so I should expect 10 results back. However, I am unsure how I could go about writing this with what I have. </p>

<p>How should I go about this? </p>
",https://stackoverflow.com/questions/45216967/unit-testing-conditions-for-directory-getfiles,"['c#', 'unit-testing']",3361,TRUE,3,3
Unit Testing With Pyserial-Asyncio,"<p>I have a <a href=""https://github.com/FaradayRF/faradayio/issues/3#issuecomment-350653922"" rel=""nofollow noreferrer"">github issue</a> I am trying to figure out. Basically, I am attempting to use <a href=""https://github.com/pyserial/pyserial-asyncio/"" rel=""nofollow noreferrer"">pyserial-asyncio</a> to connect to a serial port asynchronously. However, I would like to unit test it and am learning this all at the same time. What's throwing me for a loop (pun intended) is that When I <a href=""https://github.com/pyserial/pyserial-asyncio/blob/master/test/test_asyncio.py"" rel=""nofollow noreferrer"">use the pyserial-asyncio unit test</a> I can get it to work. This does seem to create a very specialized test which doesn't bode well with integrating the asynchronous functions into a module. <strong>Mainly, I can't seem to understand how I would implement this in a module and then check the values in each function.</strong></p>

<p><strong>Output Class (Asyncio.Protocol)</strong>
Below I've implemented an asyncio.Protocol similar to that needed for unit testing pyserial-asyncio. This is implemented in the test as an imported object ""faradayOut = faraday.Output""</p>

<pre><code>class Output(asyncio.Protocol):

def __init__(self):
    super().__init__()
    self._transport = None
    self.received = []
    self.actions = []
    self.TEXT = b'Hello, World!\n'

def connection_made(self, transport):
    self._transport = transport
    self.actions.append('open')
    transport.write(self.TEXT)

def data_received(self, data):
    self.received.append(data)
    if b'\n' in data:
        self._transport.close()
    return data

def connection_lost(self, exc):
    self.actions.append('close')
    self._transport.loop.stop()

def pause_writing(self):
    self.actions.append('pause')
    print(self._transport.get_write_buffer_size())

def resume_writing(self):
    self.actions.append('resume')
    print(self._transport.get_write_buffer_size())
</code></pre>

<p>This is used in the test below:</p>

<pre><code>import os
import unittest
import asyncio

import serial_asyncio

HOST = '127.0.0.1'
_PORT = 8888
</code></pre>

<p>on which port should the tests be performed:</p>

<pre><code>PORT = 'socket://%s:%s' % (HOST, _PORT)

@unittest.skipIf(os.name != 'posix', ""asyncio not supported on platform"")
class Test_asyncio(unittest.TestCase):
    """"""Test asyncio related functionality""""""

    def setUp(self):
        self.loop = asyncio.get_event_loop()
        # create a closed serial port

    def tearDown(self):
        self.loop.close()

    def test_asyncio(self):
        faradayIn = faraday.Input
        faradayOut = faraday.Output
        if PORT.startswith('socket://'):
            coro = self.loop.create_server(faradayIn, HOST, _PORT)
            self.loop.run_until_complete(coro)

        client = serial_asyncio.create_serial_connection(self.loop, faradayOut, PORT)
        self.loop.run_until_complete(asyncio.gather(client))
        # print(""TEST = {0}"".format(test))
        self.loop.run_forever()
        # self.assertEqual(b''.join(client.received), faraday.Output.TEXT)
        # self.assertEqual(actions, ['open', 'close'])
</code></pre>

<p>This works. The problem is that I cannot check the client.received text against faraday.Output.TEXT. This is because once the aysncio loop completes the coroutine seems to be destroyed and with it that instances self.received list.</p>

<p>How can I unit test this with the intended implementation?</p>
",https://stackoverflow.com/questions/47765822/unit-testing-with-pyserial-asyncio,"['python', 'unit-testing', 'asynchronous', 'pyserial', 'python-asyncio']",640,FALSE,3,0
Unit testing angular router events,"<p>I have a module that shows a loading screen on navigation. How do I test that the <code>isLoading</code> variable updates on <code>NavigationStart</code>, <code>NavigationEnd</code>, etc.?</p>

<pre><code>component.html
&lt;app-loader *ngIf=""isLoading""&gt;&lt;/app-loader&gt;

component.ts
    this.router.events
      .subscribe((event) =&gt; {
        if (event instanceof NavigationStart) {
          this.isLoading = true;
          // alert('NavigationStart:' + event);
        } else if (
          event instanceof NavigationEnd || event instanceof NavigationCancel
        ) {
          this.isLoading = false;
          // alert('NavigationEnd:' + event);
        } else if (event instanceof NavigationError) {
          this.isLoading = false;
          // console.log('NavigationError: ', event);
        }
      });
</code></pre>
",https://stackoverflow.com/questions/47306550/unit-testing-angular-router-events,"['angular', 'unit-testing', 'jasmine', 'angular-cli']",426,FALSE,3,0
Java unit testing with parameter,"<p>In C#, it is possible to specify parameters for the same unit test method.
Example:</p>

<pre><code>[DataTestMethod]
[DataRow(12,3,4)]
[DataRow(12,2,6)]
public void DivideTest(int n, int d, int q)
{
   Assert.AreEqual( q, n / d );
}
</code></pre>

<p>Is it possible to do the same in Java? I have read Parametrized runner but this solution is not as easy to use. </p>
",https://stackoverflow.com/questions/44865146/java-unit-testing-with-parameter,"['java', 'unit-testing']",7329,TRUE,3,4
Unit testing with dart&#39;s shelf_rest,"<p>I'm trying to test a Dart REST app run on <a href=""https://pub.dartlang.org/packages/shelf_rest"" rel=""nofollow noreferrer"">shelf_rest</a>. Assuming a setup similar to the <code>shelf_rest</code> example, how can one test the configured routes without actually running an HTTP server?</p>

<pre><code>import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
import 'package:shelf_rest/shelf_rest.dart';

void main() {
  var myRouter = router()
    ..get('/accounts/{accountId}', (Request request) {
      var account = new Account.build(accountId: getPathParameter(request, 'accountId'));
      return new Response.ok(JSON.encode(account));
    });

  io.serve(myRouter.handler, 'localhost', 8080);
}

class Account {
  final String accountId;

  Account.build({this.accountId});

  Account.fromJson(Map json) : this.accountId = json['accountId'];

  Map toJson() =&gt; {'accountId': accountId};
}  

class AccountResource {
  @Get('{accountId}')
  Account find(String accountId) =&gt; new Account.build(accountId: accountId);
}
</code></pre>

<p>Without getting into too much additional logic, how could the GET <code>account</code> endpoint be unit tested? Some basic tests I'd like to run would be:</p>

<ul>
<li><code>GET /accounts/123</code> returns 200</li>
<li><code>GET /accounts/bogus</code> returns 404</li>
</ul>
",https://stackoverflow.com/questions/42824533/unit-testing-with-darts-shelf-rest,"['unit-testing', 'dart', 'dart-shelf']",376,TRUE,3,1
Unit testing elixir functions properly,"<p>I'm fairly new to elixir and functional programming in general and I'm struggling to properly unit test functions that are composed of other functions. The general question is: when I have a function <strong><em>f</em></strong> that uses other functions <strong><em>g</em></strong>, <strong><em>h</em></strong>... internally, which approach should I take to test the whole? </p>

<p>Coming from the OOP world the first approach that comes to mind involves injecting the functions <strong><em>f</em></strong> depends of. I could unit test <strong><em>g</em></strong>, <strong><em>h</em></strong>... and inject all of those as arguments to <strong><em>f</em></strong>. Then, unit tests for <strong><em>f</em></strong> would just make sure it calls the injected functions as expected. This feels like overfitting though, and as an overall cumbersome approach that is against the functional mindset for which function composition should be a cheap thing to do and you should not be concerning yourself on passing all those arguments around the whole codebase.   </p>

<p>I can also unit test <strong><em>g</em></strong>, <strong><em>h</em></strong>... as well as <strong><em>f</em></strong> by treating each of those as black boxes, which feels like the appropriate thing to do, but then the complexity of <strong><em>f</em></strong>'s tests increases dramatically. Having simple tests that scale is one of the main purposes of unit testing.</p>

<p>To make the argument more concrete I'll put an example of a function that composes other functions inside and that I don't know how to unit test properly. This in particular is code for a plug that handles the creation of a resource in a RESTful fashion. Note that some of the ""dependencies"" are pure functions (such as <em>validate_account_admin</em>) but others are not (<em>Providers.create</em>):</p>

<pre class=""lang-rb prettyprint-override""><code>  def call(conn, _opts) do
    account_uuid = conn.assigns.current_user.account[""uuid""]

    with {:ok, conn}      &lt;- Http.Authorization.validate_account_admin(conn),
         {:ok, form_data} &lt;- Http.coerce_form_data(conn, FormData),
         {:ok, provider}  &lt;- Providers.create(FormData.to_provider(form_data), account_uuid: account_uuid) do
      Http.respond_create(conn, Http.provider_path(provider))
    else
      {:error, reason, messages} -&gt; Http.handle_error(conn, reason, messages)
    end
  end
</code></pre>

<p>Thanks!</p>
",https://stackoverflow.com/questions/43137698/unit-testing-elixir-functions-properly,"['unit-testing', 'testing', 'functional-programming', 'elixir']",357,TRUE,3,1
Unit Testing a Function Macro,"<p>I'm writing unit tests for some function macros, which are just wrappers around some function calls, with a little housekeeping thrown in.</p>

<p>I've been writing tests all morning and I'm starting to get tedium of the brainpan, so this might just be a case of tunnel vision, but:</p>

<p>Is there a valid case to be made for unit testing for macro expansion? By that I mean checking that the correct function behavior is produced for the various source code forms of the function macro's arguments. For example, function arguments can take the form, in source code of a:</p>

<ul>
<li>literal</li>
<li>variable</li>
<li>operator expression</li>
<li>struct member access</li>
<li>pointer-to-struct member access</li>
<li>pointer dereference</li>
<li>array index</li>
<li>function call</li>
<li>macro expansion</li>
<li>(feel free to point out any that I've missed)</li>
</ul>

<p>If the macro doesn't expand properly, then the code usually won't even compile. So then, is there even any sensible point in a different unit test if the argument was a <code>float</code> literal or a <code>float</code> variable, or the result of a function call?</p>

<p>Should the expansion be part of the unit test?</p>
",https://stackoverflow.com/questions/47848573/unit-testing-a-function-macro,"['c', 'unit-testing', 'macros']",1246,TRUE,2,3
Laravel - Unit Testing with SoftDeletes,"<p>I have a basic test which verifies that a user can only see its own posts.</p>

<p>In my test_database I whip up a couple posts, attach some of them to the user with the ModelFactory - which I then test that this user can only see the posts that are linked to the user according to the 'user_id' column in the post records. The test basically asserts that the output of a query is as expected.</p>

<ul>
<li>I'm using the SoftDeletes trait in my Post model.</li>
<li>I have 'deleted_at' in the 'protected $dates' property on Post Model.</li>
</ul>

<p>The problem is that the 'deleted_at' field is NOT returned in the factory()->create() output - but it IS present in the query where I fetch all the user's posts.</p>

<p>I was able to solve this by adding the 'deleted_at' field to the factory with value null, but it seems silly to me to have to add this field to every factory.</p>

<p>Why do I explicitly need to do this for 'deleted_at' but not for example for 'created_at' and 'updated_at'?</p>

<p><strong>Code</strong></p>

<p>Post schema</p>

<pre><code>Schema::create('posts', function (Blueprint $table) {
    $table-&gt;increments('id');
    $table-&gt;integer('company_id')-&gt;unsigned();
    $table-&gt;integer('locale_id')-&gt;unsigned();
    $table-&gt;string('name');
    $table-&gt;text('description')-&gt;nullable();
    $table-&gt;boolean('active')-&gt;default(false);
    $table-&gt;datetime('start_date')-&gt;nullable()-&gt;default(null);
    $table-&gt;datetime('end_date')-&gt;nullable()-&gt;default(null);

    $table-&gt;softDeletes();
    $table-&gt;timestamps();
});
</code></pre>

<p>Post factory</p>

<pre><code>$factory-&gt;define(App\Post::class, function (Faker\Generator $faker) {
    return [
        'company_id' =&gt; function () {
            return factory(App\Company::class)-&gt;create()-&gt;id;
        },
        'locale_id' =&gt; function () {
            return factory(App\Locale::class)-&gt;create()-&gt;id;
        },
        'title' =&gt; $faker-&gt;sentence(rand(1,3)),
        'body' =&gt; $faker-&gt;paragraph(1),
        'active' =&gt; rand(0,1),
        'start_date' =&gt; $faker-&gt;dateTimeBetween('now', '+2 years')-&gt;format('Y-m-d H:i:s'),
        'end_date' =&gt; $faker-&gt;dateTimeBetween('+2 years', '+4 years')-&gt;format('Y-m-d H:i:s')
    ];
});
</code></pre>

<p>My unit test</p>

<pre><code>public function test_scope_foruser_only_returns_posts_for_authenticated_user()
{
    // Given there are 2 companies
    $companies = factory(Company::class, 2)-&gt;create();

    // With 1 post per company
    $postX = factory(Post::class)-&gt;create(['company_id' =&gt; $companies-&gt;first()-&gt;id]);
    $postY = factory(Post::class)-&gt;create(['company_id' =&gt; $companies-&gt;last()-&gt;id]);

    // Given I am logged in as user of the first company
    $user = factory(User::class)-&gt;create([
        'typeable_type' =&gt; Company::class,
        'typeable_id' =&gt; $companies-&gt;first()-&gt;id
    ]);

    // Login
    $this-&gt;be(User::first());

    // When I fetch the posts for User (via company)
    $posts = Post::forUser()-&gt;get()-&gt;toArray();


    // Then It returns only posts which the user's company
    // is associated with in a properly formatted array
    $this-&gt;assertCount(1, $posts);
    $this-&gt;assertEquals([$postX-&gt;toArray()], $posts);
}
</code></pre>

<p>This is the query scope applied to the Post model as seen above</p>

<pre><code>public function scopeForUser($query)
{
    if ($company = auth()-&gt;user()-&gt;company) {
        return $query-&gt;where(['company_id' =&gt; $company-&gt;id]);
    }

    return $query;
}
</code></pre>
",https://stackoverflow.com/questions/44800208/laravel-unit-testing-with-softdeletes,"['php', 'mysql', 'laravel', 'unit-testing']",348,FALSE,2,0
Angular 4 Router Unit Testing,"<p>So I'm trying to unit test with Jasmine, first time ever doing it. I've read that you must create mocks. I've done so, however -- as soon as I provide the mock for RouterStub, I get the error ""cannot read root of undefined""</p>

<pre><code>class RouterStub {
navigate(params){

}
</code></pre>

<p>}</p>

<pre><code>beforeEach(async(() =&gt; {
TestBed.configureTestingModule({
  declarations: [ FpUserIdComponent ],
  imports: [ FormsModule, ReactiveFormsModule, RouterTestingModule, HttpModule, 
       TranslateModule.forRoot({
        loader: {
          provide: TranslateLoader,
          useFactory: (createTranslateLoader),
          deps: [ Http ]
  }
})
  ],
  providers: [
      ForgotPasswordService, CorrelateID, ErrorToggleService, ApiService,
    { provide: XHRBackend, useClass: MockBackend },
    { provide: ActivatedRouteStub, useClass: ActivatedRouteStub },
    { provide: ""api.config"", useFactory: getData },
    { provide: Router, useValue: RouterStub }
  ]
})
.compileComponents();
</code></pre>

<p>}));</p>

<p>My Component:</p>

<pre><code>export class FPUserIdComponent implements OnInit, ComponentCanDeactive {
constructor(
private route: ActivatedRoute,
private router: Router,
private forgotpasswordservice: ForgotPasswordService,
private errorToggleService: ErrorToggleService,
private apiService: ApiService ) { }

}
</code></pre>
",https://stackoverflow.com/questions/44575518/angular-4-router-unit-testing,"['angular', 'unit-testing', 'jasmine', 'angular2-routing']",982,FALSE,2,0
Unit testing function using File.Exists,"<p>How can I unit test this type of function? Of course I can't create real files and I can't make any changes to <em>Example</em> class and <em>Func</em> to make it easier to test.</p>

<p>As I found out, mocking static <code>Exists</code> is not possible using popular free frameworks like moq. I found some frameworks to mock filesystem like System.IO.Abstractions (<a href=""https://github.com/tathamoddie/System.IO.Abstractions"" rel=""nofollow noreferrer"">https://github.com/tathamoddie/System.IO.Abstractions</a>) but in all samples I found, methods (like <code>CreateDirectory</code> etc. - here <code>Exists</code>), are called from mocked object and I'm not sure how to adapt it to this method (if it is possible).</p>

<pre><code>public class Example
{
    public int Func()
    {
        if(System.IO.File.Exists(""some hard-coded path""))
        {
            return 1;
        }
        else
        {
            return 2
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/45354567/unit-testing-function-using-file-exists,"['c#', 'unit-testing', 'mocking']",9783,TRUE,2,3
Unit Testing Nodejs Express applications,"<p>I'm trying to write a unit test for a controller that fetches a list of users from MongoDB using mongoose. Have written test for both success &amp; error conditions. Is this correct &amp; sufficient? </p>

<p>Or do I need to use supertest or superagent to test this controller using its route. But that is more of integration test, right. Here, I also run all my middlewares too.</p>

<pre><code>// /controllers/users.js

exports.list = function (req, res) {
    User.find({}, function(err, users) {
        if(err) return applib.handleError(res, err);
        res.json(users);    
    });
};


// test/users.js

var chai = require('chai');
var expect = chai.expect;
var sinon = require('sinon');
var users = require('../controllers/users');
var mongoose = require('mongoose');
var User = mongoose.model('User');
var applib = require('../applib');

describe('User CRUD operations', function() {

  it('should list all users', function(done) {
    var fake = function(query, cb) {
      cb(null, [{ id: 1, email: 'foo@foobar.com' }]);
    };
    var stub = sinon.stub(User, 'find', fake);
    var req = {};
    var res = {
      json: function(data) {
        expect(data[0].id).to.equal(1);
        expect(data[0].email).to.equal('foo@foobar.com');
        done();
      }
    };
    users.list(req, res);
    stub.restore();
  });

  it('should err on user listing', function(done) {
    var fake = function(query, cb) {
      cb(new Error('Error'), null);
    };
    var stubUserFind = sinon.stub(User, 'find', fake);
    var stubHandleError = sinon.stub(applib, 'handleError');
    var req = {};
    var res = {};
    users.list(req, res);
    expect(stubHandleError.withArgs(res, new Error('Error')).calledOnce).to.be.true;
    stubUserFind.restore();
    stubHandleError.restore();
    done();
  });

});
</code></pre>
",https://stackoverflow.com/questions/41874699/unit-testing-nodejs-express-applications,"['node.js', 'unit-testing', 'express', 'mongoose', 'sinon']",194,FALSE,2,0
Angular 2+ Promise Unit testing,"<p>Hi I'm trying to write jasmine unit test for following angular service.</p>

<p>However, I'm struggling how to write test for return promise value and wasn't able to find any elaborate resource how to write for these cases.</p>

<p>Most struggle comes from not knowing how to test what has been called within the returned promise.</p>

<p>For example, I want to test calling <code>this.createMap()</code> invokes <code>this._mapResolver</code> with map instance <code>new google.maps.Map(el, mapOptions)</code></p>

<p>Could an Angular 2+ guru help me understand writing spec for promises? or references to learn from?</p>

<pre><code>declare let google: any;

/**
 * Wrapper class that handles the communication with the Google Maps Javascript
 * API v3
 */
@Injectable()
export class GoogleMapsAPIWrapper {
  private _map: Promise&lt;mapTypes.GoogleMap&gt;;
  private _mapResolver: (value?: mapTypes.GoogleMap) =&gt; void;

  constructor(private _loader: MapsAPILoader, private _zone: NgZone) {
    this._map =
      new Promise&lt;mapTypes.GoogleMap&gt;((resolve: () =&gt; void) =&gt; { this._mapResolver = resolve; });
  }

  createMap(el: HTMLElement, mapOptions: mapTypes.MapOptions): Promise&lt;void&gt; {
    return this._loader.load().then(() =&gt; {
      const map = new google.maps.Map(el, mapOptions);
      this._mapResolver(&lt;mapTypes.GoogleMap&gt;map);
      return;
    });
  }

  setMapOptions(options: mapTypes.MapOptions) {
    this._map.then((m: mapTypes.GoogleMap) =&gt; { m.setOptions(options); });
  }
}
</code></pre>

<hr>

<p>Solution suggested by @ArmenVardanyan</p>

<pre><code>describe('Service: GoogleMapsAPIWrapper', () =&gt; {

  const loaderServiceStub = {
    load: () =&gt; Promise.resolve()
  };

  let service;


  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      providers: [
        GoogleMapsAPIWrapper,
        {provide: MapsAPILoader, useValue: loaderServiceStub}
      ]
    });
  }));

  beforeEach(async(inject([GoogleMapsAPIWrapper], (_service: GoogleMapsAPIWrapper) =&gt; {
    service = _service;
  })));


  it('should be created',() =&gt; {
    expect(service).toBeTruthy();
  });

  it('should be call _mapResolver with specified arguments', async(() =&gt; {
    const elem = document.createElement('div');
    const spyOnCreateMap = spyOn(service, '_mapResolver');
    service.createMap(elem, {})
      .then(() =&gt; {
        expect(spyOnCreateMap).toHaveBeenCalled();
        expect(spyOnCreateMap).toHaveBeenCalledWith(new google.maps.Map(elem, {}));
      });
  }));

});
</code></pre>
",https://stackoverflow.com/questions/47022512/angular-2-promise-unit-testing,"['javascript', 'angular', 'unit-testing', 'jasmine']",1392,TRUE,2,1
C# Unit Testing Async Error,"<p>Just to set the question, when I have come to write a unit test I hit the following error:    </p>

<blockquote>
  <p>Error: The source IQueryable doesn't implement
  IDbAsyncEnumerable</p>
</blockquote>

<p>The problem happens when testing a method which calls ToListAsync(), the unit test is as follows:</p>

<pre><code>[TestMethod]
public async Task Method1CallsCount()
{
    //arrange
    MockContainer container = new MockContainer();

    IQueryable&lt;Entity1DTO&gt; querableentity1DTO = new List&lt;Entity1DTO&gt;().AsQueryable();

    container.DefaultQueryFactory.Setup(p =&gt; p.Load(It.IsAny&lt;ContextEnums&gt;(), It.IsAny&lt;Expression&lt;Func&lt;Entity1, Entity1DTO&gt;&gt;&gt;(),
        It.IsAny&lt;Expression&lt;Func&lt;Entity1, bool&gt;&gt;&gt;(), It.IsAny&lt;int&gt;(), It.IsAny&lt;bool&gt;())).Returns(querableentity1DTO);  

    var manager = new Manager1(container.DefaultQueryFactory.Object);

    //act
    var result = await manager.Method1();

    //assert
    //container.repo1.Verify(x =&gt; x.repoMethod(It.IsAny&lt;Expression&lt;Func&lt;Entity1,bool&gt;&gt;&gt;()), Times.Once);
}
</code></pre>

<p>And here is the method I am testing: </p>

<pre><code>public async Task&lt;List&lt;Entity1DTO&gt;&gt; Method1()
{
    Expression&lt;Func&lt;Entity1, Entity1DTO&gt;&gt; select = (x =&gt; new Entity1DTO()
    {
             ...   
            });

    Expression&lt;Func&lt;Entity1, bool&gt;&gt; where = (x =&gt; x.Property == ""Test"");

    return await _defaultQueryFactory.Load(ContextEnums.Enum1, select, where).ToListAsync();

}
</code></pre>

<p>To help a bit, I've tried mocking up the method that loads the data in the query factory and the error appears because the DTO model doesn't implement IDbAsyncEnumerable, now the method that is getting tested sends off a select statement and a where statement and an entity type which the query factory then uses to generate a query this is then executed with ToListAsync() when it returns from the load Method. The error message shows that the DTO model is the one that doesn't implement the IDbAsync not the DB entity itself.</p>

<p>I understand that there are a few other questions out there that are simular but my difference is that I use a DTO model and the method in question does not use the context itself as it is injected into the load method and not in the place in which ToListAsync() is called.</p>

<p>anyone any ideas?</p>
",https://stackoverflow.com/questions/44718835/c-unit-testing-async-error,"['c#', 'entity-framework', 'linq', 'unit-testing', 'asynchronous']",891,TRUE,2,2
Unit testing Redux async actions,"<p>I am trying to add unit test cases to my redux actions.</p>

<p>I have tried <a href=""https://stackoverflow.com/questions/40888535/unit-testing-redux-async-function"">this</a>, <a href=""https://stackoverflow.com/questions/39101637/cant-test-redux-async-action"">this</a> &amp; <a href=""https://stackoverflow.com/questions/38355847/react-redux-async-action-testing"">this</a></p>

<p>I am using <code>thunk</code>, <code>promise-middleware</code> in my actions</p>

<p>one of my action is like this</p>

<pre><code>export function deleteCommand(id) {
  return (dispatch) =&gt; {
    dispatch({
      type: 'DELETE_COMMAND',
      payload: axios.post(`${Config.apiUrl}delete`, { _id: id })
    })
  }
}
</code></pre>

<p>unit test for this is</p>

<pre><code>import configureMockStore from ""redux-mock-store""
const middlewares = [thunk, promiseMiddleware()];
const mockStore = configureMockStore(middlewares)

  it('creates DELETE_COMMAND_FULFILLED after deleting entry', (done) =&gt; {

    nock('http://localhost:8081/')
      .post('/delete',{
        _id: 1
      })
      .reply(200, {})

    const expectedActions = [{
      type: 'DELETE_COMMAND_FULFILLED',
      payload: {}
    }]

    const store = mockStore({
      command: {
        commands: []
      }
    })

    store.dispatch(actions.deleteCommand({_id: 1}).then(function () {
      expect(store.getActions())
        .toEqual(expectedActions)
      done();
    })

  })
</code></pre>

<p>I am using <code>nock</code>,<code>redux-mock-store</code> configured with <code>thunk</code>, <code>promise middleware</code></p>

<p>It gives <code>then of undefined</code></p>

<p>then I changed the action to return the promise, then I got <code>unhandled promise reject</code> exception, I added a catch to the action dispatch call.
Now I am getting <code>Network Error</code> because nock is not mocking the call.
Also tried <code>moxios</code>, changed <code>axios</code> to <code>isomorphic-fetch</code>, <code>whatwg-fetch</code>. Doesn't seem to be working</p>

<p>Where am I doing it wrong?.</p>
",https://stackoverflow.com/questions/43986386/unit-testing-redux-async-actions,"['javascript', 'unit-testing', 'redux', 'redux-thunk', 'nock']",596,FALSE,2,1
Unit testing a verticle deployment,"<p>I have a simple Verticle that reads configuration from a properties file and loads in into vertx config. I have written a unit test to test the deployment of this verticle and possible cause of test failure is non availability of the properties file at the location.</p>

<p>When I run the test, unit test passes irrespective of whether I change the properties file name or path and the handler says the verticle was deployed successfully. </p>

<p>Am I doing something wrong here? Below is my code</p>

<pre><code>import io.vertx.config.ConfigRetrieverOptions;
import io.vertx.config.ConfigStoreOptions;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.json.JsonObject;
import io.vertx.rxjava.config.ConfigRetriever;
import io.vertx.rxjava.core.AbstractVerticle;


/**
 * This is the main launcher verticle, the following operations will be executed in start() method of this verticle:
 * 1. Read configurations from application.properties file
 * 2. Deploy all other verticles in the application
 */
public class LauncherVerticle extends AbstractVerticle {


    @Override
    public void start() throws Exception {

        //set up configuration from the properties file
        ConfigStoreOptions fileStore = new ConfigStoreOptions()
                .setType(""file"")
                .setFormat(""properties"")
                .setConfig(new JsonObject().put(""path"", System.getProperty(""vertex.config.path""));

        //create config retriever options add properties to filestore
        ConfigRetrieverOptions options = new ConfigRetrieverOptions().addStore(fileStore);
        ConfigRetriever configRetriever = ConfigRetriever.create(vertx, options);

        DeploymentOptions deploymentOptions = new DeploymentOptions();

        //Deploy verticles after the config has been loaded
        //The configurations are loaded into JsonConfig object
        //This JsonConfig object can be accessed in other verticles using the config() method.
        configRetriever.rxGetConfig().subscribe(s -&gt; {

            //pass on the JsonConfig object to other verticles through deployment options
            deploymentOptions.setConfig(s);
            vertx.deployVerticle(AnotherVerticle.class.getName(), deploymentOptions);

        }, e -&gt; {
            log.error(""Failed to start application : "" + e.getMessage(), e);
            try {
                stop();
            } catch (Exception e1) {
                log.error(""Unable to stop vertx, terminate the process manually : ""+e1.getMessage(), e1);
            }
        });
    }
}
</code></pre>

<p><strong>This is my unit test</strong></p>

<pre><code>import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import io.vertx.rxjava.core.Vertx;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import rx.Single;


@RunWith(VertxUnitRunner.class)
public class LoadConfigurationTest {


    /**
     * Config should be loaded successfully
     *
     * @param context
     */
    @Test
    public void loadConfigTest(TestContext context) {
        /*
         * Set the system property ""vertx.config.path"" with value ""application.properties""
         * This system property will be used in the Launcher verticle to read the config file
         */
        System.setProperty(""vertx.config.path"", ""/opt/vertx/config/application.properties"");

        //create vertx instance
        Vertx vertx = Vertx.vertx();

        Single&lt;String&gt; single = vertx.rxDeployVerticle(LauncherVerticle.class.getName());
        single.subscribe(s -&gt; {
            vertx.rxUndeploy(s);
        }, e -&gt; {
            Assert.fail(e.getMessage());
        });

    }

    /**
     * Test for negative use case - file not available in the specified location
     *
     * @param context
     */
    @Test
    public void loadConfigFailTest(TestContext context) {

         //set path = non existing path
        System.setProperty(""vertx.config.path"", ""/non/existing/path/application.properties"");

        //create vertx instance
        Vertx vertx = Vertx.vertx();

        Single single = vertx.rxDeployVerticle(LauncherVerticle.class.getName());

        single.subscribe(s -&gt; {
            //not executing this statement
            Assert.fail(""Was expecting error but Verticle deployed successfully"");
        }, e -&gt; {
            //not executing this statement either
            System.out.println(""pass"");
        });
    }
}
</code></pre>
",https://stackoverflow.com/questions/44527933/unit-testing-a-verticle-deployment,"['java', 'junit', 'rx-java', 'vert.x']",3515,TRUE,2,2
(Unit) Testing Akka Streams Kafka,"<p>I'am currently evaluating Apache Kafka for the use as a middleware in a microservice environment. Not only as a Message Queue but also for aggregating other data sources. Kafka seems to be the perfect fit. The services in majority are based on the Play Framework, so <strong>Akka Stream Kafka</strong> seems to be the natural choice to interact with Kafka. </p>

<p>I prototyped a small App with a <em>Consumer</em> and a <em>Publisher</em>, communicating via JSON and that was pretty straight forward. But when it comes to unit testing I become a little helpless. Is it possible to run the tests in a lightweight fashion and not with a running Kafka Cluster or an embedded server (check <a href=""https://github.com/manub/scalatest-embedded-kafka"" rel=""nofollow noreferrer"">here</a>)? I also found <a href=""https://github.com/jpzk/mockedstreams"" rel=""nofollow noreferrer"">this</a> project which looked promising, but I was not able to test my <em>Consumer</em> with it. Isn't that the right tool? I'am a little confused.</p>
",https://stackoverflow.com/questions/46858572/unit-testing-akka-streams-kafka,"['unit-testing', 'apache-kafka', 'akka-stream']",352,FALSE,2,1
Unit Testing Angular Attribute Directive,"<p>I am having some problems testing an AngularJS (1.5) Attribute restricted Directive. See the below example directive and following unit test, of which produces a broken unit test.</p>

<p><strong>Directive</strong></p>

<pre><code>(function (angular) {
  'use strict';

  function SomethingCtrl($filter) {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, element, attrs, ngModelController) {
        var exampleFilter = $filter('exampleFilter');
        ngModelController.$parsers.push(function(value) {
          ngModelController.$setViewValue(value);
          ngModelController.$render();
          return value;
        });
      }
    };
  }

  SomethingCtrl.$inject = ['$filter'];

  angular.module('something.formatter', [
    'filters'
  ]).directive('somethingFormatter', SomethingCtrl);
}(window.angular));
</code></pre>

<p><strong>Directive Unit Test</strong></p>

<pre><code>fdescribe('something.formatter spec', function () {
  'use strict';
  var scope,
      element,
      testValue,
      compile,
      ngModelCtrl;

  beforeEach(function () {
    module('something.formatter');

    compile = function () {
      inject([
        '$compile',
        '$rootScope',
        function ($compile, $rootScope) {
          scope = $rootScope.$new();
          scope.testValue = testValue;
          element = angular.element('&lt;input something-formatter ng-model=""testValue""');
          $compile(element)(scope);
          ngModelCtrl = element.controller('ngModel');
          scope.$digest();
        }
      ]);
    };
  });
  describe('initialization', function () {
    beforeEach(function () {
      testValue = 'Yay!';
      compile();
      ngModelCtrl.$setViewValue('Nay?');
    });
    it('should be defined', function () {
      expect(scope.testValue).toEqual('Nay?');
    });
  });
});
</code></pre>

<p>I tried following these instructions: <a href=""http://jsfiddle.net/mazan_robert/hdsjbm9n/"" rel=""nofollow noreferrer"">http://jsfiddle.net/mazan_robert/hdsjbm9n/</a></p>

<p>To be able to call methods on the ngModelController, like; $setViewValue.</p>

<p>Yet, Jasmine continues to scream at me and tells me that $setViewValue is not a constructor, as well as doesn't even hit console.logs inside the actual directive.</p>

<pre><code>TypeError: undefined is not an object (evaluating 'ngModelCtrl.$setViewValue')
</code></pre>

<p>Thoughts?</p>

<p>Thanks so much for your help!</p>
",https://stackoverflow.com/questions/44770320/unit-testing-angular-attribute-directive,"['javascript', 'angularjs', 'unit-testing', 'angularjs-directive', 'jasmine']",1645,TRUE,1,1
Unit Testing Coverage RxJS.Observable.Catch Block,"<p>I am attempting to get unit test coverage on a code block similar to the following, specifically the catch block that calls a method to handle errors:</p>

<pre><code>return this._http.get(/someurl)
            .map((response: Response) =&gt; {
                let results = &lt;any&gt;response.json();
                return results;
            })
            .catch(response =&gt; {
                return this.handleError(response);
            });
</code></pre>

<p>I have attempted this:</p>

<pre><code>it('Should call base handleError method when an error occurs',
    fakeAsync(inject([MyService, MockBackend],
        (myService: MyService, mockBackend: MockBackend) =&gt; {
              mockBackend.connections.subscribe((connection: MockConnection) =&gt; {
                  expect(connection.request.url).toEqual(
                      `/someurl`
                  );
                  connection.mockRespond(new Response(new ResponseOptions({
                      status: 404
                  })));
              });

              spyOn(myService, 'handleError');
              myService.getData(1);
              tick();
              expect(myService.handleError).toHaveBeenCalled();
})));
</code></pre>

<p>The catch block is never called and the test fails as the spy was never hit.  I have tried using MockConnection.mockError with no luck there either.  I have seen posts that require using the subscribe error handler on the Observable, but there has to be a way to trigger the catch block via an error response too?  I have tried throwing an Observable failure via Observable.throw() but that didn't seem to get me down the right path either.</p>
",https://stackoverflow.com/questions/45019973/unit-testing-coverage-rxjs-observable-catch-block,"['angular', 'unit-testing', 'jasmine', 'rxjs']",1043,TRUE,1,1
Unit testing a Vertx.io application,"<p>I am playing with Vertx.io (version 3.4.2). Put down some code and now I want to test it, so I write a couple of unit test. When I run each test separately they both complete well but when I do a mvn clean test they both fail with this message:</p>

<pre><code>java.net.BindException: Address already in use: bind
at sun.nio.ch.Net.bind0(Native Method)
at sun.nio.ch.Net.bind(Unknown Source)
at sun.nio.ch.Net.bind(Unknown Source)
at sun.nio.ch.ServerSocketChannelImpl.bind(Unknown Source)
at io.netty.channel.socket.nio.NioServerSocketChannel.doBind(NioServerSocketChannel.java:128)
at io.netty.channel.AbstractChannel$AbstractUnsafe.bind(AbstractChannel.java:554)
at io.netty.channel.DefaultChannelPipeline$HeadContext.bind(DefaultChannelPipeline.java:1258)
at io.netty.channel.AbstractChannelHandlerContext.invokeBind(AbstractChannelHandlerContext.java:502)
at io.netty.channel.AbstractChannelHandlerContext.bind(AbstractChannelHandlerContext.java:487)
at io.netty.channel.DefaultChannelPipeline.bind(DefaultChannelPipeline.java:980)
at io.netty.channel.AbstractChannel.bind(AbstractChannel.java:250)
at io.netty.bootstrap.AbstractBootstrap$2.run(AbstractBootstrap.java:365)
at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163)
at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasksFrom(SingleThreadEventExecutor.java:379)
at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:354)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:436)
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)
at java.lang.Thread.run(Unknown Source)
</code></pre>

<p>It seems that verticle does not shutdown after test completition. Here are the tests:</p>

<pre><code>@RunWith(VertxUnitRunner.class)
public class SomeApiTest {

private ObjectMapper objectMapper;
private Vertx vertx;
private Integer port;
private static Logger log;

@BeforeClass
public static void initTests() {
log = Logger.getLogger(""SomeApiTest"");
}

@Before
public void setUp(TestContext context) {
log.info(""start up test."");
vertx = Vertx.vertx();
objectMapper = new ObjectMapper();
port = 8080;
DeploymentOptions options = new DeploymentOptions();
options.setConfig(new JsonObject());
options.getConfig().put(""api.port"", port);
vertx.deployVerticle(""SomeApi"", options, context.asyncAssertSuccess());
}

@After
public void tearDown(TestContext context) {
log.info(""shutting down test."");
vertx.close(h -&gt; {
    if (h.failed()) {
    log.error(h.cause());
    }
});
}

@Test
public void whenRequestHitsVerticleItReturnsRecipes(TestContext context) throws Exception {
final Async async = context.async();
List&lt;Integer&gt; votes = new ArrayList&lt;&gt;();
votes.add(new Integer(6));
votes.add(new Integer(4));
votes.add(new Integer(8));
vertx.eventBus().consumer(""persistence"", h -&gt; {
    h.reply(Json.encode(votes));
});
vertx.createHttpClient().getNow(port, ""localhost"", ""/votes?qty=3"", response -&gt; {
    response.handler(body -&gt; {
    Integer[] xvotes;
    try {
        xvotes = objectMapper.readValue(body.toString(), Integer[].class);
        int expected = 3;
        int actual = xvotes.length;
        Assert.assertEquals(expected, actual);
        async.complete();
    } catch (Exception e) {
        log.error(e);
        Assert.fail(e.getMessage());
    }
    });
});
}

@Test
public void fiveDishesRequestAgainsTenRecipesApi(TestContext context) throws Exception {
  final Async async = context.async();
  List&lt;Integer&gt; votes = new ArrayList&lt;&gt;();
  votes.add(new Integer(3));
  votes.add(new Integer(4));
  votes.add(new Integer(7));
  votes.add(new Integer(7));
  votes.add(new Integer(6));
  vertx.eventBus().consumer(""persistence"", h -&gt; {
    h.reply(Json.encode(votes));
  });
  vertx.createHttpClient().getNow(port, ""localhost"", ""/votes?qty=5"", response -&gt; {
    response.handler(body -&gt; {
    Integer[] xvotes;
    try {
        xvotes = objectMapper.readValue(body.toString(), Integer[].class);
        int expected = 5;
        int actual = xvotes.length;
        Assert.assertEquals(expected, actual);
        async.complete();
    } catch (Exception e) {
        log.error(e);
        Assert.fail(e.getMessage());
    }
    });
    });
  }
}
</code></pre>

<p>Tests are simple, their purpose is to get how to unit test with Vertx. I am expecting that each verticle will be undeployed after test ends. What am I missing?</p>
",https://stackoverflow.com/questions/46624321/unit-testing-a-vertx-io-application,"['java', 'maven', 'unit-testing', 'vert.x']",1852,TRUE,1,1
Aurelia: unit-testing Event Aggregator,"<p>As an Angular (2) developer, I recently started experimenting with Aurelia. Really like it by the way..
But I really have some difficulties unit-testing Aurelia's <code>Event Aggregator</code>. This is what I have currently, but it doesn't fire the event in my controller right now. I now I'm doing it wrong, some help would be great!</p>

<pre><code>// app.js

@inject(UserService, EventAggregator)
export class App {
    constructor(userService, eventAggregator) {
        this.userService = userService;
        this.eventAggregator = eventAggregator;
        this.authorizedUser = null;

        // get authorized user
        this.getAuthorizedUser();

        // subscribe to events
        this.eventAggregator.subscribe(EVENTS.USER_LOGGED_IN, data =&gt; {
            this.authorizedUser = data;
        });
    }

    // calls userService and sets this.authorizedUser;
    getAuthorizedUser() {
        ....
    }
 }
</code></pre>

<p>And my spec currently looks like this:</p>

<pre><code>describe('app', () =&gt; {
    let component,
        createComponent,
        eventAggregator = new EventAggregator(),
        userService = new UserService();

    beforeEach(() =&gt; {    
        component = StageComponent.withResources('app').inView('&lt;app&gt;&lt;/app&gt;');
        component.bootstrap(aurelia =&gt; {
            aurelia.use.standardConfiguration();
            aurelia.container.registerInstance(UserService, userService);
            aurelia.container.registerInstance(EventAggregator, eventAggregator);
        });

        createComponent = component.create(bootstrap);
    });

    // this one is working for example..
    it('should get authorized user when token is set', (done) =&gt; {
        const result = 'some value';

        spyOn(UserService, 'getToken').and.returnValue(true);
        spyOn(userService, 'getAuthorizedUser').and.returnValue(Promise.resolve('some value'));

        createComponent.then(() =&gt; {
            const viewModel = component.viewModel;
            expect(viewModel.authorizedUser).toEqual(result);
            done();
        });
    });

    // this one is failing (depending on Event Aggregator)
    it('should set authorized user when LOGGED_IN event is fired', (done) =&gt; {
        spyOn(UserService, 'getToken').and.returnValue(false);

        createComponent.then(() =&gt; {
            const viewModel = component.viewModel;
            expect(viewModel.authorizedUser).toEqual(null);

            eventAggregator.publish(EVENTS.USER_LOGGED_IN, 'some value');
            expect(viewModel.authorizedUser).toEqual('some value');
            done();
        });
    });

    afterEach(() =&gt; {
        component.dispose();
    });


});
</code></pre>
",https://stackoverflow.com/questions/43550379/aurelia-unit-testing-event-aggregator,"['unit-testing', 'aurelia']",611,TRUE,1,1
Unit testing using Moq framework,"<p>I want to test this method using Moq. Can someone tell me how to do this?
I am attaching the userid and value in the query string. How to mimic this in moq. The name of the class is RestClient.cs. I have created an interface called IRestClient. 
public interface IRestClient
    {
        string MakeRequest(string userID, string value );
    }</p>

<p>This is the makeRequest method of the RestClient class</p>

<pre><code>public string MakeRequest(string userId,string value)
{
     Logger.Info(""Entering method MakeRequest()."" + ""Input Parameter: "" + userId+Constant.NewLine+value);
     string strResponseValue = string.Empty;

     // The HttpWebRequest class allows you to programatically make web requests against an HTTP server.
     // create the WebRequest instantiated for making the request to the specified URI.
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Constant.webServerURI+""?id=""+userId + Constant.UserValueAppend + value);

     //Gets or sets the method for the request.(Overrides WebRequest.Method.)
     request.Method = httpMethod.ToString();

     //Initially response from webserver is set to null.
     HttpWebResponse response = null;

     try
     {
         // Get the response in the response object of type HttpWebResponse
         // The request object of HttpWebRequest class is used to ""get"" the response (GetResponse()) from WebServer and store it in the response object
         response = (HttpWebResponse)request.GetResponse();

         // We check that the response StatusCode is good and we can proceed
         if (response.StatusCode != HttpStatusCode.OK)
         {
             Logger.Error(""Error"" + response.StatusCode.ToString());
             throw new ApplicationException(Constant.ErrorDisplay + response.StatusCode.ToString());
         }

         // Process the response string
         // We obtain the ResponseStream from the webserver using ""get"" (GetResponseStream())
         // The Stream Class provides a generic view of a sequence of bytes

         using (Stream responseStream = response.GetResponseStream())
         {
             if (responseStream != null)
             {
                 using (StreamReader reader = new StreamReader(responseStream))
                 {
                     //read the stream and store it in string strResponseValue
                     strResponseValue = reader.ReadToEnd();

                  }//End of StreamReader
             }
         }//End of using ResponseStream
     }// End of using Response

     catch (Exception ex)
     {
         Logger.Error(""Error"" + ex.Message.ToString());
         strResponseValue = (""Error "" + ex.Message.ToString());
     }
     finally
     {
         if (response != null)
         {
             ((IDisposable)response).Dispose();
         }
     }
     //return the string strResponseValue
     Logger.Info(""Leaving method MakeRequest."" + ""Output parameter: "" + strResponseValue);
     return strResponseValue;
 }
</code></pre>

<p>This is my attempt at creating the moq in my unittest class called RestClientTests.cs</p>

<pre><code>[TestMethod]
public void TestMethod1()
{
    var expected = ""response content"";
    var expectedBytes = Encoding.UTF8.GetBytes(expected);
    var responseStream = new MemoryStream();
    responseStream.Write(expectedBytes, 0, expectedBytes.Length);
    responseStream.Seek(0, SeekOrigin.Begin);

    var mockRestClient = new Mock&lt;IRestClient&gt;();
    var mockHttpRequest = new Mock&lt;HttpWebRequest&gt;();

    var response = new Mock&lt;HttpWebResponse&gt;();
    response.Setup(c =&gt; c.GetResponseStream()).Returns(responseStream);

    mockHttpRequest.Setup(c =&gt; c.GetResponse()).Returns(response.Object);

    var factory = new Mock&lt;IHttpWebRequestFactory&gt;();
    factory.Setup(c =&gt; c.Create(It.IsAny&lt;string&gt;())).Returns(mockHttpRequest.Object);

    var actualRequest = factory.Object.Create(""http://localhost:8080"");
    actualRequest.Method = WebRequestMethods.Http.Get;

    string actual;

    using (var httpWebResponse = (HttpWebResponse)actualRequest.GetResponse())
    {
        using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
        {
            actual = streamReader.ReadToEnd();
        }
    }

    mockRestClient.Setup(moq =&gt; moq.MakeRequest(""xxx"", ""s"")).Returns(actual);
}
</code></pre>

<p>My IhttpWebRequestFactory interface looks like this:</p>

<pre><code>interface IHttpWebRequestFactory
{
    HttpWebRequest Create(string uri);

}
</code></pre>

<p>I am not sure how to test this</p>
",https://stackoverflow.com/questions/46800760/unit-testing-using-moq-framework,"['unit-testing', 'httpwebrequest', 'moq', 'httpwebresponse']",359,TRUE,1,1
Angular 2 unit testing issues,"<p>I am using angular rc.4 (unfortunately can't upgrade to newer version) and have some issues with unit testing.</p>

<p>My project was generated by <a href=""https://www.npmjs.com/package/generator-ng2-webpack"" rel=""nofollow noreferrer"">generator-ng2-webpack</a> and upgraded from rc.3 to rc.4.</p>

<p>Currently my simple test <code>expect(1).toEqual(1);</code> failures because of App injection, and I am getting strange error.</p>

<blockquote>
  <p>_instantiateProvider@C:/path-to-project/karma-shim.ts:23782:38<br>
   _new@C:/path-to-project/karma-shim.ts:23771:42<br>
   getObjByKeyId@C:/path-to-project/karma-shim.ts:23423:55<br>
   _getByKeyDefault@C:/path-to-project/karma-shim.ts:23951:52<br>
   _getByKey@C:/path-to-project/karma-shim.ts:23923:42<br>
   get@C:/path-to-project/karma-shim.ts:23732:31<br>
   C:/path-to-project/karma-shim.ts:34074:75<br>
   map@[native code]<br>
   execute@C:/path-to-project/karma-shim.ts:34074:33<br>
   path-to-project/karma-shim.ts:34168:63<br>
   _instantiate@C:/path-to-project/karma-shim.ts:23908:98  </p>
</blockquote>

<p>Spec file</p>

<pre><code>import {BaseRequestOptions, Http, Response, ResponseOptions} from '@angular/http';
import {MockBackend} from '@angular/http/testing';
import {provide} from ""@angular/core"";

class MockRouter {
  createUrlTree() {}
  navigateByUrl() {}
  navigate() {}
}

class MockActivatedRoute { }

// Load the implementations that should be tested
import {App} from './index';

describe('App', () =&gt; {
  // provide our implementations or mocks to the dependency injector
  beforeEach(() =&gt; {
    addProviders([
      App,
      HTTP_PROVIDERS,
      { provide : Router, useClass: MockRouter},
      { provide : ActivatedRoute,  useClass: MockActivatedRoute },
      ...
    ]);
  });

  it('should have an url', inject([App], (app: App) =&gt; {
    expect(1).toEqual(1);
  }));
});
</code></pre>

<p>karma.shim.ts (I made some changes as suggested <a href=""https://github.com/AngularClass/angular2-webpack-starter/issues/901#issuecomment-242894059"" rel=""nofollow noreferrer"">here</a>)</p>

<pre><code>Error.stackTraceLimit = Infinity;
import 'core-js/es6';
import 'core-js/es7/reflect';
import 'reflect-metadata';

import 'zone.js/dist/zone';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';
import 'zone.js/dist/sync-test';

var appContext = require.context('./src', true, /root\.?spec\.ts/);

appContext.keys().forEach(appContext);

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

testing.setBaseTestProviders(
    browser.TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS,
    browser.TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS
);
</code></pre>

<p>my package.json</p>

<pre><code>  ""dependencies"": {
    ""@angular/common"": ""2.0.0-rc.4"",
    ""@angular/compiler"": ""2.0.0-rc.4"",
    ""@angular/core"": ""2.0.0-rc.4"",
    ""@angular/forms"": ""0.2.0"",
    ""@angular/http"": ""2.0.0-rc.4"",
    ""@angular/platform-browser"": ""2.0.0-rc.4"",
    ""@angular/platform-browser-dynamic"": ""2.0.0-rc.4"",
    ""@angular/router"": ""3.0.0-beta.2"",
    ""zone.js"": ""^0.6.12""
    ...
  },
  ""devDependencies"": {
    ""istanbul-instrumenter-loader"": ""^0.1.3"",
    ""jasmine-core"": ""^2.4.1"",
    ""jasmine-given"": ""^2.6.4"",
    ""jasmine-spec-reporter"": ""2.5.0"",
    ""karma"": ""^0.13.22"",
    ""karma-chrome-launcher"": ""^0.2.1"",
    ""karma-coverage"": ""^0.5.2"",
    ""karma-jasmine"": ""^1.0.2"",
    ""karma-phantomjs-launcher"": ""^1.0.0"",
    ""karma-sourcemap-loader"": ""^0.3.7"",
    ""karma-spec-reporter"": ""0.0.26"",
    ""karma-story-reporter"": ""^0.3.1"",
    ""karma-webpack"": ""^1.7.0"",
    ""phantomjs-polyfill"": ""0.0.2"",
    ""phantomjs-prebuilt"": ""^2.1.7"",
    ""protractor"": ""^4.0.10"",
    ""ts-helpers"": ""^1.1.1"",
    ""ts-loader"": ""^0.8.2"",
    ""typescript"": ""^1.8.10"",
    ""webpack"": ""^1.13.0"",
    ""webpack-dev-server"": ""^1.14.1"",
    ""webpack-hot-middleware"": ""^2.10.0"",
    ""webpack-load-plugins"": ""^0.1.2""
    ...
  }
</code></pre>

<p>When i dont inject App </p>

<pre><code>it('should have an url', inject([], () =&gt; {
    expect(1).toEqual(1);
  }));
</code></pre>

<p>test works fine.</p>

<p>Also I need to test <code>App</code>s properties and website's routing, but cant find any guide how to do that on angular rc.4.</p>
",https://stackoverflow.com/questions/41677677/angular-2-unit-testing-issues,"['unit-testing', 'angular', 'webpack', 'karma-jasmine']",199,FALSE,1,0
Unit testing crash at cellForRowAtIndexPath,"<p>I have a simple tableview with some rows. Each row is a custom cell with an xib file. I have implemented the delegate and datasource and its working fine when I run the app. This is the way I have implemented it.</p>

<pre><code>class P: UITableViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        registerCell()
    }

    func registerCell() {
        self.tableView.register(UINib(nibName: ""PCell"", bundle: nil), forCellReuseIdentifier: ""cell"")
    }

    #number of rows implemented here

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: ""cell"", for: indexPath) as! PCell
        cell.titleLabel.text = ""Great""
        return cell
    }
}
</code></pre>

<p>This code works fine.</p>

<p>The problem is when I try to unit test the tableView I am facing problem. This is how I am unit testing</p>

<pre><code>class MockPController: PController {

}

class PControllerTests: XCTestCase {
    let mpc = MockPController()

    //THIS IS WORKING
    func testNumberOfSections() {
        mpc.viewDidLoad()
        XCTAssertEqual(mpc.numberOfSections(in: mpc.tableView), 5)
    }

    func testTitleForPCells() {
        mpc.viewDidLoad()
        var cell = mpc.tableView(mpc.tableView, cellForRowAt: IndexPath(row: 0, section: 1)) as! PCell
        //THE APP CRASHES AT THE CELLFORROWATINDEXPATH FUNCTION IN ACTUAL CODE - HERE ""let cell = self.tableView.dequeueReusableCell(withIdentifier: ""cell"", for: indexPath) as! PCell""
        //APP CRASHES HERE SAYING ""Could not cast value of type 'Project.PCell' to 'ProjectTests.PCell'
    }
}
</code></pre>

<p>On getting this app crash I added a override function for registerCell() in MockPController, so the new MockPController becomes</p>

<pre><code>class MockPController: PController {
    override func registerCell() {
        self.tableView.register(PCell.self, forCellReuseIdentifier: ""cell"")
    }
}
</code></pre>

<p>After adding this override function I am not getting crash at the dequeueReusableCell, but now app crashes saying that the outlet variable titleLabel is nil.</p>

<p>So I guess it is not getting the right instance of the cell because of the override registerCell() function. But without it also app crashes.</p>

<p>What am I doing wrong? </p>

<p>I searched google but I am not getting any result.</p>
",https://stackoverflow.com/questions/47836329/unit-testing-crash-at-cellforrowatindexpath,"['ios', 'swift', 'uitableview', 'unit-testing']",635,TRUE,1,1
Code runs while unit testing,"<p>I'm trying to unit test my minesweeper game made in python. I am starting small with just 1 test on 1 definition, but it runs the entire code of which I should be testing a very minor part.
Unit testing code:</p>

<pre><code>import unittest
from minesweeper import setupgrid

class Testmyfunctions(unittest.TestCase):
    def test_setup(self):
        self.assertTrue(setupgrid(9, [], 10))


if __name__ == '__main__' :
    unittest.main(exit=False)
</code></pre>

<p>And this is the function it should be checking:</p>

<pre><code>import random, re, time
from string import ascii_lowercase


def setupgrid(gridsize, start, numberofmines):
    emptygrid = [['0' for i in range(gridsize)] for i in range(gridsize)]
    mines = getmines(emptygrid, start, numberofmines)
    for i, j in mines:
        emptygrid[i][j] = 'X'
    grid = getnumbers(emptygrid)
    return (grid, mines)
</code></pre>

<p>The default values for emptygrid and numberofmines are, respectively, 9 and 10 and the value for start should be empty, hence the [].</p>
",https://stackoverflow.com/questions/41621593/code-runs-while-unit-testing,"['python', 'python-3.x', 'unit-testing']",72,FALSE,1,0
Conversations.SendToConversationAsync crashes on Unit testing,"<p>I have the following method in the controller to send a message from the controller itself (Say a welcome message when a user adds the bot)</p>

<pre><code>        private static async Task&lt;string&gt; OnSendOneToOneMessage(Activity activity,
        IList&lt;Attachment&gt; attachments = null)
    {
        var reply = activity.CreateReply();
        if (attachments != null)
        {
            reply.Attachments = attachments;
        }

        if (_connectorClient == null)
        {
            _connectorClient = new ConnectorClient(new Uri(activity.ServiceUrl));
        }

        var resourceResponse = await _connectorClient.Conversations.SendToConversationAsync(reply);
        return resourceResponse.Id;
    }
</code></pre>

<p>And the unit test looks like this</p>

<pre><code>[TestClass]
public sealed class MessagesControllerTest
{
    [Test]
    public async Task CheckOnContactRelationUpdate()
    {
        // Few more setup related to dB &lt;deleted&gt;
        var activity = new Mock&lt;Activity&gt;(MockBehavior.Loose);
        activity.Object.Id = activityMessageId;
        activity.Object.Type = ActivityTypes.ContactRelationUpdate;
        activity.Object.Action = ContactRelationUpdateActionTypes.Add;
        activity.Object.From = new ChannelAccount(userId, userName);
        activity.Object.Recipient = new ChannelAccount(AppConstants.BotId, AppConstants.BotName);
        activity.Object.ServiceUrl = serviceUrl;
        activity.Object.ChannelId = channelId;
        activity.Object.Conversation = new ConversationAccount {Id = Guid.NewGuid().ToString()};
        activity.Object.Attachments = Array.Empty&lt;Attachment&gt;();
        activity.Object.Entities = Array.Empty&lt;Entity&gt;();

        var messagesController =
            new MessagesController(mongoDatabase.Object, null)
            {
                Request = new HttpRequestMessage(),
                Configuration = new HttpConfiguration()
            };

        // Act
        var response = await messagesController.Post(activity.Object);
        var responseMessage = await response.Content.ReadAsStringAsync();

        // Assert
        Assert.IsNotEmpty(responseMessage);
    }
}
</code></pre>

<p>The method OnSendOneToOneMessage works fine when a user adds the bor. But it crashes for the unit test. Seems i am missing some setup for the POST?</p>

<p>The stack trace is</p>

<pre><code>Result StackTrace:  
   at System.Net.Http.StringContent.GetContentByteArray(String content, Encoding encoding)
   at System.Net.Http.StringContent..ctor(String content, Encoding encoding, String mediaType)
   at System.Net.Http.StringContent..ctor(String content)
   at &lt;&gt;.Controllers.MessagesController.&lt;Post&gt;d__4.MoveNext() in 
   C:\Users....MessagesController.cs:line 75
</code></pre>

<p>--- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
       at BotTest.Controllers.MessagesControllerTest.d__0.MoveNext() in 
       C:\Users....MessagesControllerTest.cs:line 75 
        --- End of stack trace from previous location where exception was thrown ---
       at     NUnit.Framework.Internal.AsyncInvocationRegion.AsyncTaskInvocationRegion.WaitFor       PendingOperationsToComplete(Object invocationResult)
       at  NUnit.Framework.Internal.Commands.TestMethodCommand.RunAsyncTestMethod(TestExecutionContext context)
    Result Message: 
    System.ArgumentNullException : Value cannot be null.
    Parameter name: content</p>

<p>And here is the output</p>

<pre><code>Exception thrown: 'System.ArgumentNullException' in mscorlib.dll
Exception thrown:     'Microsoft.Rest.TransientFaultHandling.HttpRequestWithStatusException' in  Microsoft.Rest.ClientRuntime.dll
Exception thrown: 'Microsoft.Rest.TransientFaultHandling.HttpRequestWithStatusException' in mscorlib.dll
Exception thrown: 'Microsoft.Rest.TransientFaultHandling.HttpRequestWithStatusException' in Microsoft.Rest.ClientRuntime.dll
Exception thrown: 'Microsoft.Rest.TransientFaultHandling.HttpRequestWithStatusException' in mscorlib.dll
Exception thrown: 'System.Net.Http.HttpRequestException' in System.Net.Http.dll
Exception thrown: 'System.UnauthorizedAccessException' in   Microsoft.Bot.Connector.dll
Exception thrown: 'System.UnauthorizedAccessException' in mscorlib.dll
Exception thrown: 'System.UnauthorizedAccessException' in System.Net.Http.dll
Exception thrown: 'System.UnauthorizedAccessException' in mscorlib.dll
Exception thrown: 'System.UnauthorizedAccessException' in mscorlib.dll
</code></pre>

<p>NOTE: I tried passing the credential in all different ways. Still it crashes on unit testing.</p>
",https://stackoverflow.com/questions/43264251/conversations-sendtoconversationasync-crashes-on-unit-testing,"['c#', 'unit-testing', 'botframework']",822,TRUE,1,2
Confusion about unit testing frameworks?,"<p>I get the concept of unit testing and TDD on a whole. </p>

<p>However, I'm still a little confused on what exactly unit testing frameworks are. Whenever I read about unit testing, it's usually an explanation of what it is, followed by ""oh here are the frameworks for this language, i.e JUnit"". </p>

<p>But what does that really mean? Are framework just a sort of testing library that allows programmers to write simpler/efficient unit tests? </p>

<p>Also, what are the benefits of using a framework? As I understand it, unit testing is done on small chunks of code at a time, i.e a method. However, I could individually write a test for a method without using a unit testing framework. Is it maybe for standardization of testing practices? </p>

<p>I'm just very new to testing and unit-testing, clarification on some basic concepts would be great.</p>
",https://stackoverflow.com/questions/44126037/confusion-about-unit-testing-frameworks,"['unit-testing', 'testing', 'tdd']",48,TRUE,1,1
Setup UserData for unit testing,"<p>How do i setup the UserData within the context for unit testing?</p>

<pre><code>        var context = new Mock&lt;IDialogContext&gt;();
        context.Setup(c =&gt; c.Activity).Returns(() =&gt; new Activity());
        context.Setup(c =&gt; c.UserData).Returns(() =&gt; ?);
</code></pre>

<p>Should i use BotData?</p>
",https://stackoverflow.com/questions/43238393/setup-userdata-for-unit-testing,"['unit-testing', 'botframework']",210,TRUE,1,1
reactjs - unit testing with enzyme,"<p>I am oretty new to react and am trying to unit test the following piece of code that I have in my react component</p>

<pre><code>import React,{Component} from 'react';

const styleSheet = document.styleSheets[0];

const keyframes =
  `@-webkit-keyframes pulse {
    0% {
      transform: scale(0.9);
      opacity: 0.6;
    }
    50% {
      transform: scale(1);
      opacity: 1;
    }
    100% {
      transform: scale(0.9);
      opacity: 0.6;
    }
  }`;

styleSheet.insertRule(keyframes, styleSheet.cssRules.length);
const style = {
  animation: 'pulse 5.5s infinite ease-in-out'
};

class someclass extends Component {

  render() {
    return (    
      &lt;svg style={style}&gt;

      &lt;/svg&gt;
    );
  }
}

export default someclass;
</code></pre>

<p>This is my test file:</p>

<pre><code>import React from 'react'
import {shallow, mount, render} from 'enzyme'
import {expect} from 'chai'
import someclassfrom '.../src/components/someclass';

describe('someclass', () =&gt; {
  it('should have the main svg', () =&gt; {
    const wrapper = shallow(&lt;someclass/&gt;);
    expect(wrapper.find('svg')).to.have.length(1);

  })
})
</code></pre>

<p>but I keep on getting the following error:</p>

<pre><code>Cannot read property '0' of undefined
</code></pre>

<p>How I can mock the same? Thanks in advance</p>
",https://stackoverflow.com/questions/46917470/reactjs-unit-testing-with-enzyme,"['javascript', 'reactjs', 'unit-testing', 'enzyme', 'jsdom']",231,FALSE,1,2
Unit testing Angular 2 Service,"<p>Im new to whole unit testing scene with Angular, so would be great if guys could point me in the direction.. Im trying to create a fake service and pass back data to which i can run a few simple test.. </p>

<p>When I go to run the test it seems to fail with </p>

<p>Server error
  at webpack:///~/rxjs/Subscriber.js:194:0 &lt;- config/karma-test-shim.js:20301</p>

<p>I don't think it my webpack config.. Here is my code anway...</p>

<pre><code>import { SearchModule } from './search.module';
import { SearchService } from './search.services';
import { HttpModule }    from '@angular/http'; 
import { inject, TestBed } from '@angular/core/testing';  
import { Observable } from 'rxjs/Observable';
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';

class SearchServiceMock {

search() {

    return Observable.of(
        [
            {
            ""title"": ""title_1"",
            ""artist"": ""artist_1"",
            ""release"": ""06/02/2016"",
            ""slug"": ""slug-1""
        },
        {
            ""title"": ""title_2"",
            ""artist"": ""artist_1"",
            ""release"": "" 27/01/2017"",
            ""slug"": ""slug-2""
        },
        {
            ""title"": ""title_3"",
            ""artist"": ""artist_3"",
            ""release"": ""17/02/2017"",
            ""slug"": ""slug-3""
        }
        ]
    )

}

}

describe('Service: TracksServices', () =&gt; {

let searchService: SearchService;

beforeEach(() =&gt; TestBed.configureTestingModule({
    imports: [ SearchModule, HttpModule ],
        providers: [
        { provide: SearchService, useClass: SearchServiceMock },
    ]
}));

beforeEach(inject([SearchService], (s: any) =&gt; {
    searchService = s;
}));

it('Search results 3', () =&gt; {

    searchService.search('track 1', 1, 4).subscribe(
        (x:any) =&gt; {     

            // expect(x).toContain(track);
            expect(x.length).toEqual(3);

        }
    );

});

});
</code></pre>

<p>The test still seems to be getting the real service i think when I want to use a fake one</p>
",https://stackoverflow.com/questions/41730657/unit-testing-angular-2-service,"['angular', 'unit-testing', 'karma-jasmine']",1259,TRUE,1,1
Unit testing code inside TransactionSynchronizationManager,"<p>I couldn't find a working solution, how to unit test something that happened inside TransactionSynchronizationManager.registerSynchronization(). I have code like this:</p>

<pre><code>pubclic class MyService {
    public void method() {
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter()
                        {
                            @Override
                            public void afterCommit()
                            {
                                myService.callSmth(params);
                            }
                        }
    }
}
</code></pre>

<p>Here I call method():</p>

<pre><code>public class MyClass {

    private MyService myService;

    public void method2() {
        myService.method();
    }
}
</code></pre>

<p>In my unit test I need to <em>verify</em> that myService.callSmth. But seems like test code doesn't go into afterCommit() method. 
That's my test class:</p>

<pre><code>@Configurable
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { ""classpath*:test-applicationContext.xml"" })
public class ServiceTest extends TestHelper
{
    @Mock
    MyService myService;

    @InjectMocks
    MyClass myClass;

    @Test
    public void allowWriteOffGlobal()
    {
         myClass.method();
         veryfy(myService).method();
    }
}
</code></pre>

<p>I simplified my code and please, don't pay attention if there could be any mistakes in mocking and smth like this. In a debugger I see how the flow comes to line TransactionSynchronizationManager.registerSynchronization and skips the afterCommit() method. 
P.s.: not sure I provided enough info. Please, write in the comment if there is a need of smth extra. Thanks.</p>
",https://stackoverflow.com/questions/46951310/unit-testing-code-inside-transactionsynchronizationmanager,"['java', 'spring', 'unit-testing', 'asynchronous', 'junit']",2287,TRUE,1,2
Unit testing Scala package object,"<p>As per my understanding, <code>package objects</code> contain common functionality used across the package. Presumably, these functionalities aren't modified 'as rapidly' as the rest of the codebase; rather only new functionalities would be added (to a package object) with time.</p>

<p>Then is it worthwhile to unit test methods inside a Scala package object?
If yes, then how do I access classes and methods inside package object in my test package?</p>
",https://stackoverflow.com/questions/47531128/unit-testing-scala-package-object,"['scala', 'unit-testing', 'package']",2619,TRUE,1,2
Laravel Unit testing Eloquent insertion,"<p>I'm currently having some troubles in testing a function in Laravel. This function is a simple save user function.</p>

<p>The current structure involves a User</p>

<pre><code>class User extends Authenticatable
</code></pre>

<p>Then I have a UserController</p>

<pre><code>class UserController extends Controller
{
protected $user;

public function __construct(User $user)
{
    $this-&gt;user = $user;
    $this-&gt;middleware('admins');
}
</code></pre>

<p>The save function is defined on the UserController class, this class only assigns the request variables and uses Eloquent save function to save to database.</p>

<p>The function signature is the following:</p>

<pre><code>public function storeUser($request)
{

    $this-&gt;user-&gt;name       = $request-&gt;name;
    $this-&gt;user-&gt;email      = $request-&gt;email;
    $this-&gt;user-&gt;country_id = $request-&gt;country_id;

    return $this-&gt;user-&gt;save();
}
</code></pre>

<p>The NewAccountRequest object extends from Request and has the validation rules for the request.</p>

<pre><code>class NewAccountRequest extends Request
{
public function authorize()
{
    return true;
}

public function rules()
{
    return [
        'name' =&gt; 'required|max:255',
        'email' =&gt; 'required|email|max:255|unique:user',
        'password' =&gt; 'required|min:6|max:60',
    ];
}

}
</code></pre>

<p>My problem is how can I unit test this storeUser function.</p>

<p>I have the current test:</p>

<pre><code>public function testSaveUserWithEmptyRequest()
{

    $user = $this-&gt;createMock(User::class);
    $controller = new UserController($user);

    $request = $this-&gt;createMock(NewAccountRequest::class);
    $store = $controller-&gt;storeUser($request);

    $this-&gt;assertFalse($store);
}
</code></pre>

<p>I'm mocking both User and NewAccountRequest, the problem is that the assertion should be false, from the Eloquent save. Instead I'm getting Null. Any idea on how can I correctly test the function?</p>
",https://stackoverflow.com/questions/42364863/laravel-unit-testing-eloquent-insertion,"['php', 'laravel', 'unit-testing', 'laravel-5', 'phpunit']",3074,FALSE,1,1
Async await unit testing issue,"<p>This is the <code>update</code> function I want to test in mocked database</p>

<pre><code>import Book from '../model/book';

function bookRepository(db) {
    this.db = db;
};

bookRepository.prototype.update = async function(id, data) {
    return await Book.findOneAndUpdate({ _id: id }, { $set: data });
}

export default bookRepository;
</code></pre>

<p>This is test script I wrote for it</p>

<pre><code>import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
chai.use(chaiAsPromised);
const expect = chai.expect;

import app from '../../server';
import bookRepo from '../../repository/book';
const Book = new bookRepo(app.db);

describe('Test repository: book', () =&gt; {

    describe('update', () =&gt; {
        let id;
        beforeEach(async() =&gt; {
            let book = {
                name: 'Records of the Three Kingdoms',
                type: 'novel',
                description: 'History of the late Eastern Han dynasty (c. 184–220 AD) and the Three Kingdoms period (220–280 AD)',
                author: 'Luo Guanzhong',
                language: 'Chinese'
            };
            let result = await Book.insert(book);
            id = await result.id;
            return;
        });
        it('Update successfully', async() =&gt; {
            let data = {
                type: 'history',
                author: 'Chen Shou'
            };
            let result = await Book.update(id, data);
            await expect(result).to.be.an('object');
            await expect(result.type).to.be.equal('history');
            return expect(result.author).to.be.equal('Chen Shou');
        });
    });

});
</code></pre>

<p>And I received this error</p>

<pre><code>AssertionError: expected 'novel' to equal 'history'
      + expected - actual
</code></pre>

<p>When I check the mocked database, it does update data, but why does its assertion fail? It should have already updated after completing <code>await</code> call</p>
",https://stackoverflow.com/questions/42758117/async-await-unit-testing-issue,"['javascript', 'node.js', 'unit-testing', 'ecmascript-6', 'async-await']",303,TRUE,0,1
exceptions unit testing in django,"<p>I am writing unit tests for this code and I was wondering how would someone test any of the exceptions of the code below. thanks.    </p>

<pre><code>class ExpiringTokenAuthentication(TokenAuthentication):
        """"""
        Extends token auth with inactivity expiration mechanism.
        """"""
        model = ExpiringToken

        def authenticate_credentials(self, key):

            try:
                token = self.model.objects.get(key=key)
            except self.model.DoesNotExist:
                raise exceptions.AuthenticationFailed('Invalid token')

            if not token.user.is_active:
                raise exceptions.AuthenticationFailed('Invalid user')

            if token.has_expired():
                raise exceptions.AuthenticationFailed('Token has expired')

            token.last_activity = timezone.now()
            token.save()
            return token.user, token
</code></pre>
",https://stackoverflow.com/questions/44686364/exceptions-unit-testing-in-django,"['python', 'django', 'django-rest-framework']",190,FALSE,0,0
Simple unit testing with monoids,"<p>Suppose I testing a function <code>echo: String =&gt; String</code>, which is just repeating the input, with <code>specs2</code>. </p>

<p>I can write a few tests like that:</p>

<pre><code>class EchoSpec extends SpecificationWithJUnit {

  ""echo should handle ASCII alphanumeric names"" in {
    echo(""abc"") must beEqualTo(""abc"")
  }

  ""echo should handle names with slashes"" in {
     echo(""a/b/c"") must beEqualTo(""a/b/c"")
  }

  ""echo should handle names with dots"" in {
    echo(""a.b.c"") must beEqualTo(""a.b.c"")
  }

  ""echo should handle non-ASCII names"" in {
    echo(""אבג"") must beEqualTo(""אבג"")
  }
} 
</code></pre>

<p>However I would prefer to get rid of the boilerplate code. So I am using <code>cats</code> monoids:</p>

<pre><code>import cats.implicits._

def testEcho(expected: String): String =&gt; Option[String] = {str =&gt;
  if (str == expected) none else s""$str != expected"".some
} 

def testEchoes(expected: List[String]): Option[String] = 
  expected foldMap testEcho map (_.mkString("", ""))

""echo should handle all names"" {
   val expected = List(""abc"", ""a/b/c"", ""a.b.c"", ""אבג"")
   testEcho(expected) must beNone
}
</code></pre>

<p>Does it make sense ? How to improve/simplify it ?
Is the monoid is really necessary here ? Can I git rid of the boilerplate code from the above <em>without</em> monoid ?</p>
",https://stackoverflow.com/questions/42674612/simple-unit-testing-with-monoids,"['scala', 'unit-testing', 'specs2', 'monoids', 'scala-cats']",75,TRUE,0,2
Unit Testing using Moq fails,"<p>I am new to the unit testing world so please spare me. The goal of the question is to test a class as mentioned below: </p>

<pre><code>public class Engine
{      
    #region Members
    private EnumDefinition.EngineRunningState runningState;
    private ComponentController componentController;
    private static readonly Logger logger = LogManager.GetCurrentClassLogger();
    #endregion

    #region Constructor
    public Engine(ComponentController componentController)
    {
        this.componentController = componentController;

    }
    #endregion

    #region Properties
    public EnumDefinition.EngineRunningState RunningState
    {
        get
        {
            return runningState;
        }
        private set
        {
            if (value != runningState)
            {
                componentController.EngineRunningStateChangedEvent += OnEngineRunningStateChange;               
            }
        }
    }
    #endregion

    /// &lt;summary&gt;
    /// Start the Engine Request
    /// &lt;/summary&gt;
    public void StartEngineRequest() 
    {
        // Check Engine Status
        if (runningState == EnumDefinition.EngineRunningState.Off)
        {
            componentController.SetEngineRequestToActive();
        }
        else if (runningState == EnumDefinition.EngineRunningState.Error)
        {
            logger.Trace(""Engine Start Request Sent on a ENGINE ERROR!!!!!!"");
        }
        else
        {
            logger.Trace(""Engine Start Request, Engine is still ON"");
        }

    }
    private void OnEngineRunningStateChange(object sender, EngineRunningStateArgs e)
    {
            runningState = e.runningStateofEngine;
    }
}
</code></pre>

<p>I want to test the public functions in Engine. Now I present my Test class:</p>

<pre><code>[TestFixture]
public class EngineTest
{       
    [Test]
    public void StartEngineRequestTest()
    {
        Mock&lt;ComponentController&gt; mockComponentController = new Mock&lt;ComponentController&gt;();
        Mock&lt;EngineRunningStateArgs&gt; mockEngineRunningStateArgs = 
            new Mock&lt;EngineRunningStateArgs&gt;(EnumDefinition.EngineRunningState.On);
        var engineTest = new Engine(mockComponentController.Object);
        mockComponentController.Raise(mock =&gt; mock.EngineRunningStateChangedEvent += null, mockEngineRunningStateArgs.Object);              
        engineTest.StartEngineRequest();
    }
}
</code></pre>

<p>mt test fails giving an error as mentioned below: 
<code>Result StackTrace: 
at Moq.Extensions.GetEvent[TMock](Action 1 eventExpression, TMock mock)
   at Moq.Mock 1.Raise(Action 1 eventExpression, EventArgs args)
   at AutoTugTest.EngineTest.StartEngineRequestTest() in C:\GatewayController\01 Working Copy\GatewayComputer\AutoTugTest\EngineTest.cs:line 23
Result Message: System.ArgumentException : Expression is not an event attach or detach, or the event is declared in a class but not marked virtual.</code></p>

<p>I have no idea what is happening.
I just want to throw an event from <code>ComponentController</code> with event name as <code>EngineRunningStateChangedEvent</code> with an event argument. 
Please suggest.  </p>
",https://stackoverflow.com/questions/41719333/unit-testing-using-moq-fails,"['c#', 'unit-testing', 'moq']",713,TRUE,-2,1
Properly Unit testing a QItemDelegate,"<p>I'm currently implementing unit tests for a class I have that contains a QAbstractTableModel, QSortFilerProxyModel, QTableView, and a QStyledItemDelegate.  Testing the model is easy enough.  The delegate, which decides how each cell is painted (and ultimately what the user sees) is another issue.</p>

<p>The crux of the issue is that paint() is called w/ a QModelIndex as a parameter, which has a pointer to the model.  It generally grabs the data from there, and decides what color to paint, how many decimals to use in the case of a double, etc.  With QModelIndexes being ""internal"" by nature, what's the best way of going about simulating the delegate painting an index?  I could have my model create an index, and just pass that to the delegate for unit tests.  That seems a bit tacky to me though.</p>

<p>Thoughts?</p>
",https://stackoverflow.com/questions/42256365/properly-unit-testing-a-qitemdelegate,"['qt', 'unit-testing', 'qt5']",85,FALSE,0,0
Gulps Ability for unit testing?,"<p>I'm newbie in gulp and I have some questions:</p>

<p>Is it possible to use gulp as unit testing in visual studio?</p>

<p>Is it any possibility to use gulp with Qunit, jasmine etc?</p>

<p>Thank you!</p>
",https://stackoverflow.com/questions/43066945/gulps-ability-for-unit-testing,"['visual-studio', 'unit-testing', 'gulp', 'jasmine', 'qunit']",59,TRUE,0,1
Jest unit testing - test setState(),"<p>I have defined <code>setState</code> in my function. The function setting the function is called by another function as follows : </p>

<pre><code>    pageChanged(page) {
      this.setPage(page, false);

    }

    setPage(page, isLoading) {
        var pager = this.state.pager;
        var totalItems = this.props.totalItems;

        if (page &lt; 1 || page &gt; pager.totalPages) {
            return null;
        }

        pager = this.getPager(totalItems, page, 6);

        this.setState({ pager: pager });

        if(!isLoading){ 
            this.props.onChangePage(pager.startIndex);
        }
    }
</code></pre>

<p>The function <code>pageChanged(page)</code> is called upon <code>click</code>.</p>

<blockquote>
  <p><code>onClick={this.pageChanged(page)}</code></p>
</blockquote>

<p>I have tried writing many tests using <code>sinon.spy</code> but without success. Any help on how to proceed with the test. </p>
",https://stackoverflow.com/questions/46078530/jest-unit-testing-test-setstate,"['javascript', 'reactjs', 'unit-testing', 'jestjs']",19614,TRUE,-1,1
Unit Testing with a DateTime,"<p>I am unit testing with a date but the build fails because the date has a timestamp in it. How would I remove it to enable the testing works?</p>

<pre><code> DateTime mockDateTime = new DateTime(2025, 4, 18).Date;
 _dateTimeWrapper.Setup(m =&gt; m.Now).Returns(mockDateTime)
</code></pre>

<p>The mockDateTime returns <code>4/18/2025 12:00:00 AM</code> but I only want <code>4/18/2025</code></p>
",https://stackoverflow.com/questions/44951506/unit-testing-with-a-datetime,"['.net', 'unit-testing', 'datetime']",82,TRUE,0,1
Unit Testing In App purchase,"<p>I am writing an android application that involves inapp purchases. Do I have to write unit tests for codes involving fetching products from play store, making purchases etc. 
I believe we need a real device to test inapp purchases, in that case how will unit tests work?</p>

<p>Should I instead write instrumented test using expresso and check the inapp purchases are working as intended?</p>

<p>I am completely new to unit testing. Any help really appreciated.</p>
",https://stackoverflow.com/questions/46759242/unit-testing-in-app-purchase,"['android', 'unit-testing', 'in-app-purchase']",333,FALSE,0,1
When is unit testing appropriate?,"<p>I'm following along with a program tutorial and in it, the teacher is having a bunch of functions return a boolean to indicate success. They are written like so:</p>

<pre><code>bool SomeFunc()
{
   //code....
   return true;
}
</code></pre>

<p>This means that you can write unit test which expect true for these functions and are one way to show that the whole function ran properly. To me, the way this would work is if, at a bunch of different points within that function, you had a bunch of different checks for things that returned false if an error occurs:</p>

<pre><code>bool SomeFunc()
{
   if(!someThing)
      return false;

   return true;
}
</code></pre>

<p>But what if instead you just had a bunch of asserts within the function doing your checks:</p>

<pre><code>bool SomeFunc()
{
   assert(someThing, ""Error: thing not working"");

   return true;
}
</code></pre>

<p>Then would there be a reason to still unit test this function if the asserts will just catch any bugs? The only thing reason I could think of is if you want your unit tests to work in release mode for these functions and then you would add both asserts and the if statements (since asserts are usually turned off in release mode). </p>
",https://stackoverflow.com/questions/43038007/when-is-unit-testing-appropriate,"['c++', 'unit-testing', 'assert']",60,FALSE,0,1
Golang unit testing python function,"<p>I have an API handler in Golang that calls a python function. How can I mock the response from the python function to avoid dependence of that function running correctly to test the Golang function?</p>
",https://stackoverflow.com/questions/44915711/golang-unit-testing-python-function,"['python', 'unit-testing', 'go']",345,FALSE,0,1
Unit Testing Callbacks in Scala.js,"<p>Hi so I have an actor model set up using Akka, and I am setting up a JS facade using callbacks.</p>

<p>Pretty much each actor does some kind of long computation and calls a js provided callback with the results.</p>

<p>I want to unit test this but having issues figuring out a way to do it. It isn't a response but rather something the actor calls when finished.</p>

<p>I need a way to use an assertion inside of the a function literal. Like below.</p>

<pre><code>val cb = (result: Double): Unit =&gt; {
  assert(result == Math.PI)
}
</code></pre>

<p>And then I can pass it to the actor.</p>

<pre><code>mathActor ! Compute(""foo"", cb)
</code></pre>

<p>The actor then does computations and calls cb.</p>

<pre><code>case Compute(foo, cb) =&gt;
    // compute foo
    cb(foo)
</code></pre>

<p>Thanks</p>
",https://stackoverflow.com/questions/45641816/unit-testing-callbacks-in-scala-js,"['scala', 'unit-testing', 'callback', 'scala.js']",203,FALSE,0,2
Unit testing STM32 with Ceedling,"<p>I need to do some unit testing in my C project, which will be used in STM32F0 processor. I could test my abstraction code on x64 gcc, but the problem is i need a platform with little-endian (STM32F0 is little-endian by default). I tried to do some mods in project.yml file.</p>

<pre><code>:project:
  :use_exceptions: FALSE
  :use_test_preprocessor: TRUE
  :use_auxiliary_dependencies: TRUE
  :build_root: build
#  :release_build: TRUE
  :test_file_prefix: test_

#:release_build:
#  :output: MyApp.out
#  :use_assembly: FALSE

:environment:

:extension:
  :executable: .out

:paths:
  :test:
    - +:test/**
    - -:test/support
  :source:
    - ../CDynTransport/src/
  :support:
    - test/support

:defines:
  # in order to add common defines:
  #  1) remove the trailing [] from the :common: section
  #  2) add entries to the :common: section (e.g. :test: has TEST defined)
  :commmon: &amp;common_defines []
  :test:
    - *common_defines
    - TEST
  :test_preprocess:
    - *common_defines
    - TEST

:cmock:
  :mock_prefix: mock_
  :when_no_prototypes: :warn
  :enforce_strict_ordering: TRUE
  :plugins:
    - :ignore
    - :callback
  :treat_as:
    uint8:    HEX8
    uint16:   HEX16
    uint32:   UINT32
    int8:     INT8
    bool:     UINT8

:tools:
  :test_compiler:
    :executable: arm-none-eabi-gcc
    :arguments:
      - ""${1}""
      - '-c'
      - '-g'
      - '-mcpu=cortex-m0'
      - '-mthumb'
      - '-Wall'
      - '-Wno-address'
      #- '-std=c99'
      #- '-pedantic'
      - -I""$"": COLLECTION_PATHS_TEST_TOOLCHAIN_INCLUDE               #expands to -I search paths
      - -I""$"": COLLECTION_PATHS_TEST_SUPPORT_SOURCE_INCLUDE_VENDOR   #expands to -I search paths
      - -D$: COLLECTION_DEFINES_TEST_AND_VENDOR  #expands to all -D defined symbols
      - -I""$"": COLLECTION_PATHS_SOURCE_INCLUDE_VENDOR
      - '-DTEST'
      - '-DUNITY_EXCLUDE_STDINT_H'
      - '-DUNITY_EXCLUDE_LIMITS_H'
      - '-DUNITY_EXCLUDE_SIZEOF'
      - '-DUNITY_INCLUDE_DOUBLE'
      - '-DUNITY_SUPPORT_TEST_CASES'
      - '-DUNITY_INT_WIDTH=32'
      - '-DUNITY_LONG_WIDTH=32'
      - '-DUNITY_INCLUDE_CONFIG_H'
  :test_linker:
    :executable: arm-none-eabi-gcc
    :arguments:
      - '-lm'
      - '-mcpu=cortex-m0'
      - '-mthumb'
      - '-specs=nosys.specs'
      #- '-T targets/gcc_armcortexM3/qemu.ld'
  :test_simulator:
    :executable: qemu-system-arm
    :arguments:
      - -cpu cortex-m3
      - -M lm3s6965evb
      - -no-reboot
      - -nographic
      - -kernel

:plugins:
  :load_paths:
    - vendor/ceedling/plugins
  :enabled:
    - stdout_pretty_tests_report
    - module_generator
</code></pre>

<p>But still i have problems with compilation. For example:</p>

<pre><code>Test 'test_command.c'
---------------------
Generating runner for test_command.c...
Compiling test_command_runner.c...
In file included from /home/slawek/CentralInterface/CDynTransportTest/vendor/ceedling/vendor/unity/src/unity.h:16:0,
                 from build/test/runners/test_command_runner.c:22:
/home/slawek/CentralInterface/CDynTransportTest/vendor/ceedling/vendor/unity/src/unity_internals.h:11:26: fatal error: unity_config.h: No such file or directory
 #include ""unity_config.h""
                          ^
compilation terminated.
ERROR: Shell command failed.
&gt; Shell executed command:
'arm-none-eabi-gcc build/test/runners/test_command_runner.c -c -g -mcpu=cortex-m0 -mthumb -Wall -Wno-address -I""test"" -I""test/support"" -I""../CDynTransport/src"" -I""/home/slawek/CentralInterface/CDynTransportTest/vendor/ceedling/vendor/unity/src"" -I""/home/slawek/CentralInterface/CDynTransportTest/vendor/ceedling/vendor/cmock/src"" -I""build/test/mocks"" -DTEST -I""../CDynTransport/src"" -DTEST -DUNITY_EXCLUDE_STDINT_H -DUNITY_EXCLUDE_LIMITS_H -DUNITY_EXCLUDE_SIZEOF -DUNITY_INCLUDE_DOUBLE -DUNITY_SUPPORT_TEST_CASES -DUNITY_INT_WIDTH=32 -DUNITY_LONG_WIDTH=32 -DUNITY_INCLUDE_CONFIG_H'
&gt; And exited with status: [1].

rake aborted!
ShellExecutionException: ShellExecutionException
/home/slawek/CentralInterface/CDynTransportTest/vendor/ceedling/lib/ceedling/tool_executor.rb:78:in `exec'
/home/slawek/CentralInterface/CDynTransportTest/vendor/ceedling/lib/ceedling/generator.rb:95:in `generate_object_file'
/home/slawek/CentralInterface/CDynTransportTest/vendor/ceedling/lib/ceedling/rules_tests.rake:17:in `block in &lt;top (required)&gt;'
/home/slawek/CentralInterface/CDynTransportTest/vendor/ceedling/lib/ceedling/task_invoker.rb:74:in `invoke_test_results'
/home/slawek/CentralInterface/CDynTransportTest/vendor/ceedling/lib/ceedling/test_invoker.rb:68:in `block in setup_and_invoke'
/home/slawek/CentralInterface/CDynTransportTest/vendor/ceedling/lib/ceedling/test_invoker.rb:32:in `setup_and_invoke'
/home/slawek/CentralInterface/CDynTransportTest/vendor/ceedling/lib/ceedling/tasks_tests.rake:11:in `block (2 levels) in &lt;top (required)&gt;'
Tasks: TOP =&gt; build/test/results/test_command.pass =&gt; build/test/out/test_command.out =&gt; build/test/out/test_command_runner.o
(See full trace by running task with --trace)
</code></pre>

<p>Do someone has ready-to-go configuration for Ceedling for STM32 microcontroller?</p>
",https://stackoverflow.com/questions/42115221/unit-testing-stm32-with-ceedling,"['testing', 'makefile', 'stm32', 'ceedling']",2298,FALSE,0,0
WPF Unit Testing - OnstartUp method,"<p>I need to write unit test methods for <code>OnStartUp</code> method. </p>

<p>As it is a <code>protected</code> method, how do I access and test it?</p>

<pre><code>protected override void OnStartUp(StartupEventArgs s)
{

}
</code></pre>
",https://stackoverflow.com/questions/47646032/wpf-unit-testing-onstartup-method,"['c#', 'wpf', 'unit-testing']",257,TRUE,-1,1
Trouble when using Unit testing,"<p>Is anyone know, in unit testing, how can we test buttons, function and tableView in Swift 3. </p>

<p>Example I have a button action: </p>

<pre><code>@IBAction func BellAction(_ sender: Any) {
    let searchVC = self.storyboard?.instantiateViewController(withIdentifier:StoryBoardIDs.Notification.rawValue)
    self.navigationController?.pushViewController(searchVC!, animated: true)
}
</code></pre>

<p>To test this:</p>

<pre><code>let home = HomeDashnboard() //  This is my class 
home.viewDidLoad() // test viewDidLoad()
home.BellAction() // shows an error
</code></pre>
",https://stackoverflow.com/questions/43470667/trouble-when-using-unit-testing,"['ios', 'swift', 'unit-testing', 'xcode-ui-testing']",39,TRUE,0,1
Unit Testing Local Asp WebForm,"<p>I am new at unit testing. The tool I am using is Selenium webdriver in visual studio
For practice I initially redirected to different Urls and tested their controls to find that the working is correct. Then I created my own Asp webform for the testing purpose. So what I want now is to redirect to the localhost web form in the test method which I am not able to do.
even if I do so:</p>

<pre><code>    [TestMethod]

    public void TestAspForm()
    {
        driverGC.Url = (""http://localhost:55311/AspForm.aspx"");
     }
</code></pre>

<p>The page never loads.I get the following:
<a href=""https://i.stack.imgur.com/clhBq.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/clhBq.png"" alt=""enter image description here""></a> Can someone please guide me??</p>
",https://stackoverflow.com/questions/44903371/unit-testing-local-asp-webform,"['c#', 'asp.net', 'visual-studio', 'unit-testing', 'selenium']",110,FALSE,0,1
Unit Testing/Mocking in Python,"<p>So let's say I have this bit of code:</p>

<pre><code>import coolObject

def doSomething():
   x = coolObject()
   x.coolOperation()
</code></pre>

<p>Now it's a simple enough method, and as you can see we are using an external library(<code>coolObject</code>). 
In unit tests, I have to create a mock of this object that roughly replicates it. Let's call this mock object <code>coolMock</code>. </p>

<p>My question is how would I tell the code when to use <code>coolMock</code> or <code>coolObject</code>? I've looked it up online, and a few people have suggested dependency injection, but I'm not sure I understand it correctly.</p>

<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/45044180/unit-testing-mocking-in-python,"['python', 'unit-testing', 'dependency-injection', 'mocking']",66,TRUE,0,2
Unit testing Linear Search method,"<p>Im trying to learn some unit testing for more complicated methods. I have a linear search method that searches an array and returns another array that contains the indexes of the ""target"" if found. How would I go about writing a test for this method?  here is the method below. </p>

<pre><code>public static &lt;T extends Comparable&gt; int[] linearSearch3 (T[] data, T 
       target)

   int count = 0;
   int index = 0;
   int[] indices = new int[data.length];


   for (int i = 0; i &lt; data.length;i++){
       if (data[i] == null) break;
       if (data[i].compareTo(target) == 0){ 
           indices[count] = i;
           count++;
       }
    }
    Arrays.copyOf(indices, count);
    int[] copy = Arrays.copyOf(indices,count);

    if(count != 0){
     return copy;
    }
    else 
        return null;
</code></pre>

<p>Here is what i have so far in my test method. The two arrays are fields of my test class. intArray being the array i'm searching. and newArray being the array i want to return? however, i am not sure if i'm even going about doing this correctly.  Im getting an incompatible types error on the second line. ""no instances of type variables T exist so that int[] conforms to Integer where T is a type-variable"".</p>

<pre><code>private final Integer[] intArray = {2, 5, 6, 8, 12, 17, 3, 45, 29, 88, 76, 54, 
1, 12, 5, 41, 12, 99};

private final Integer[] newArray = {2};

     @Test
     public &lt;T extends Comparable&gt; void testLinearSearch3() {

    System.out.println(""Testing LinearSearch3"");
    Integer result = Searching.linearSearch3(intArray,(Integer)2);
</code></pre>

<p>any help would be appreciated. thank you.</p>
",https://stackoverflow.com/questions/46720564/unit-testing-linear-search-method,"['java', 'unit-testing']",1125,FALSE,0,2
Unit testing for UI validation,"<p>Imagine a very simple <strong>Angular</strong> form with two input fields bound to two scope variables and a submit button which calls a controller function as to send the input data in the database. </p>

<p>My question is <strong><em>if unit testing may be applied to this scheme</em></strong>. Is it possible for example to test the UI - input validation? </p>

<p>My guess is no, since I think it must be applied <strong>end to end testing</strong> (e.g. Selenium).</p>

<p>I am struggling as to find an appropriate test: for example <em>how may I test not allow some characters inside an input field?</em> </p>

<blockquote>
  <p>Am I right to think that unit testing is only for testing the controller methods and the services' ones?</p>
</blockquote>
",https://stackoverflow.com/questions/42099384/unit-testing-for-ui-validation,"['angularjs', 'unit-testing', 'selenium', 'karma-jasmine']",613,TRUE,-1,1
Unit Testing Prism Navigation Callbacks,"<p>I am running into a situation where on a view, I have 2 content regions and I want to unit test navigation away from the parent view. Before I navigate from this view I want to verify that both of the views being displayed in the content regions will allow me to navigate. To do this, all three view models for the views implement the <code>IConfirmNavigationRequest</code> interface.</p>

<p>For my main view, the <code>ConfirmNavigationRequest</code> call looks similiar to this where <code>RegionManager</code> is an implementation of <code>IRegionManager</code>:</p>

<pre><code>public void ConfirmNavigationRequest(NavigationContext navigationContext, Action&lt;bool&gt; continuationCallback)
{
    /* setup code */
    RegionManager.RequestNavigate(""regionA"",
        new Uri(""viewA, UriKind.Relative), ViewACallback,
        navigationResult?.Context?.Parameters);
}

private void ViewACallback(NavigationResult navigationResult)
{
    if(!navigationResult.Result ?? false) return;
    /*Some Code */
    RegionManager.RequestNavigate(""regionB"",
        new Uri(""viewB, UriKind.Relative), ViewBCallback,
        navigationResult?.Context?.Parameters);
}
private void ViewBCallback(NavigationResult navigationResult)
{
    /* some logic */
}
</code></pre>

<p>With a mocked instance of <code>IRegionManager</code> I am able to mock the region request callbacks and implement unit tests. The issue I have is that every step further in the chain I am ending up with duplicate code from the previous tests. It is giving off code smell all over the place and I am just looking on how to clean this up. </p>

<p>My current thought is to abstracting the callbacks into their own classes with interfaces and being able to mock the chain that way, but that seems like a lot of overhead. Another thought was exposing the callbacks as internal and verifying that the callbacks passed on the <code>RequestNavigate</code> calls were to the correct callback and then testing those independently. This seemed cleaner to me, but that would be the only reason to expose these as internals. </p>

<p>Just looking for some thoughts or direction to some articles on how to properly unit test callbacks in a scenario like this.</p>
",https://stackoverflow.com/questions/42660710/unit-testing-prism-navigation-callbacks,"['c#', 'wpf', 'prism']",722,FALSE,0,0
React PropTypes vs Unit Testing,"<p>PropTypes of React allow to create custom validators that look like this:</p>

<pre><code> static propTypes = {  
    myPassedArray: PropTypes.array.isRequired,
    customProp: function(props, propName, componentName) {
        if (!/matchme/.test(props[propName])) {
          return new Error(
            'Invalid prop `' + propName + '` supplied to' +
            ' `' + componentName + '`. Validation failed.'
          );
        }
      },
    }
</code></pre>

<p>For example, for the value:</p>

<pre><code>[{propOne: 'string', propTwo: 2}, {propOne: 1, propTwo: 'value'}];
</code></pre>

<p>It is possible to validate whether:</p>

<ul>
<li>this value is an array</li>
<li>this value consists of objects</li>
<li>objects are not instances of arrays</li>
<li>this value's length is 2</li>
<li>each object of this value has exactly 2 props</li>
<li>the value of the first prop of the first object is a string</li>
<li>the key of the first prop of the first object is propOne</li>
<li>a.s.o for each value</li>
</ul>

<p>Should I write this kind of prop validation using PropTypes or it is better to stick to shallow validation with PropTypes and dedicate most of the job to Unit Testing?</p>
",https://stackoverflow.com/questions/47598927/react-proptypes-vs-unit-testing,"['reactjs', 'unit-testing', 'testing', 'react-proptypes']",467,TRUE,0,1
Angular2 - HTTP call unit testing,"<p>I am a beginner of angular2.  </p>

<p>My service.ts will be,</p>

<pre><code>import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import {Headers, RequestOptions, URLSearchParams}  from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable()
export class HomeService {

    url : string;

    constructor(private _http: Http) {}

    getUserInfo(userId : string) {

        this.url = ""http://localhost:9080/GetUserData"";

        let content = new URLSearchParams();
        content.set('userId', userId.toString());

        let headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');

        return this._http
            .post(this.url, content.toString(), {headers: headers})
            .map((res: Response) =&gt; res.json())
            .catch(this.handleError);
    }

    handleError (error: Response | any) {

        let errMsg: string;
        if (error instanceof Response) {
            const body = error.json() || '';
            const err = body.error || JSON.stringify(body);
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Observable.throw(errMsg);
    }

}
</code></pre>

<p>I have written the unit test case as,</p>

<pre><code>import { TestBed, async, inject } from '@angular/core/testing';
import { HomeService } from './home.service';
import { BaseRequestOptions, Response, ResponseOptions, Http } from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';
import {Observable} from 'rxjs/Observable';

describe('FacilityPopupService', () =&gt; {
  let subject: HomeService = null;
  let backend: MockBackend = null;
  let userid=""UID1"";

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
        providers: [
          HomeService,
          Response,
        BaseRequestOptions,
        MockBackend,
        {
          provide: Http,
          useFactory: (backend: MockBackend, defaultOptions: BaseRequestOptions) =&gt; {
            return new Http(backend, defaultOptions);
          },
          deps: [MockBackend, BaseRequestOptions],
        }

          ]
    });
  });

  beforeEach(inject([HomeService, MockBackend], (userService: HomeService, mockBackend: MockBackend) =&gt; {
    subject = userService;
    backend = mockBackend;

  }));

  it('get Facility list should call endpoint and return it\'s result', (done) =&gt; {
      backend.connections.subscribe((connection: MockConnection) =&gt; {
          let options = new ResponseOptions({
            body: JSON.stringify({ success: true })
          });
          connection.mockRespond(new Response(options));
      });

      subject.getUserInfo(userid)
        .subscribe((response) =&gt; {
            expect(response).toEqual({ success: true });
            done();
      });

  });

});
</code></pre>

<p>I want to write the test case for both success case and error case. I don't know how how to execute <strong>catch</strong> block. Also I don't know how to write test case for  <strong>handleError</strong> method . </p>

<p>I cannot cannot cover all the possible scenarios here. Can you please help me to get 100% coverage for the service.ts.</p>
",https://stackoverflow.com/questions/42557567/angular2-http-call-unit-testing,"['angular', 'jasmine', 'karma-jasmine']",3131,TRUE,0,2
Rails 2 and unit testing,"<p>I'm going to be working on upgrading a Rails 2 app to Rails 3. The app currently has no test coverage.</p>

<p>It's unclear to me if rspec-rails has a version that is compatible with Rails 2. </p>

<p>Any ideas?</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/44889789/rails-2-and-unit-testing,"['ruby-on-rails', 'rspec-rails']",11,FALSE,0,0
Unit Testing map.catch angular4 services,"<p>Can any one please suggest how to test the below catch function in spec.ts file?  </p>

<pre><code> getTemplate(){
        this._http.get('http//localhost:8080/new').map((response : Response) =&gt; response.json())).catch(this.serverError);
      }
      private serverError(err: any) {
        console.log('sever error:', err); // debug
        if(err instanceof Response) {
         //return Observable.throw(err.json().error || 'backend server error');
          // if you're using lite-server, use the following line
          // instead of the line above:
        return Observable.throw(err.text() || 'backend server error');
        }
        return Observable.throw(err || 'backend server error');
      }
</code></pre>
",https://stackoverflow.com/questions/47810981/unit-testing-map-catch-angular4-services,"['angular', 'angular2-services']",634,FALSE,0,1
Unit testing Avro Generic deseralisation,"<p>In my spark job I save a dataset to Avro format with:</p>

<pre><code>val ds: Dataset[Foo] = ...
ds.write.mode(SaveMode.Overwrite).avro(path)
</code></pre>

<p>In a downstream application I parse the Avro files with a custom deserialiser:</p>

<pre><code>def foo(record: GenericRecord): Foo = Foo(
  bar = record.get(""bar"").asInstanceOf[Int]
  baz = record.get(""baz"").asInstanceOf[Utf8].toString
)
</code></pre>

<p>I want to write a spec for the custom parser without having to bring Spark into the dependencies for the downstream app. But I am uncertain about how to emulate the serialisation behaviour in Spark. The Spark source has a lot of custom handling outside of Avro itself.</p>

<p>Can I reliably emulate Spark Avro serialisation to use as input for my spec?</p>
",https://stackoverflow.com/questions/44642519/unit-testing-avro-generic-deseralisation,"['scala', 'apache-spark', 'avro']",1751,TRUE,0,2
Spring and Unit Testing DeferredResult,"<p>I have this REST controller</p>

<pre><code>@RequestMapping(path = ""/hello"", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
@ApiOperation(code = CREATED, value = ""Blah"", response = SomeResponse.class)
@ApiResponses(value = {
        @ApiResponse(code = CREATED, message = ""blah"")
})
public DeferredResult&lt;SomeResponse&gt; hello(@RequestBody final SomeRequest req) {

    DeferredResult&lt;SomeResponse&gt; callback = new DeferredResult&lt;&gt;();
    if (req.someProperty.equals(""notimportant"")) {
        // return a new SomeResponse obj
        SomeResponse sr = new SomeResponse();
        sr.setOneThing(""whocares"");
        sr.andAnother(""snore"");

        //...?
    } else {
        // does something asynchronously
        someService.doSomething(req, callback::setResult);
    }
    return callback;
}
</code></pre>

<p>It returns a <code>DeferredResult&lt;&gt;</code>.  I want to just return a response under a certain condition (see the <code>if()</code> condition above).  What's the best way to go about this?  Do I create another thread and call <code>callback.setResult()</code>?</p>

<p>Another question is how I test this (using MockMVC) :</p>

<pre><code>@Test
public void testWhatever() throws Exception {
    SomeRequest request = createRequest();
    String requestContent = this.xmlObjectMapper.writeValueAsString(request);

    MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.post(""/api/hello"")
            .contentType(MediaType.APPLICATION_XML).content(requestContent).accept(MediaType.APPLICATION_XML))
            .andReturn();

    this.mockMvc.perform(asyncDispatch(mvcResult)).andExpect(MockMvcResultMatchers.status().isCreated())
            .andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaType.APPLICATION_XML));

    String responseString = mvcResult.getResponse().getContentAsString();
    SomeResponse resp = this.xmlObjectMapper.readValue(responseString,SomeResponse.class);

    Assert.assertNotNull(resp);
    // more assertions...
}
</code></pre>

<p>This isn't doing anything, getting a NPE.  Any clarifications appreciated, thanks!</p>
",https://stackoverflow.com/questions/46927012/spring-and-unit-testing-deferredresult,"['java', 'spring', 'junit', 'mockmvc']",1866,TRUE,0,1
Angular2 async unit testing with jasmine,"<p>I'm writing an angular2 app and having trouble understanding how to write tests for async code using jasmine. For whatever reason, I'm not seeing a lot of examples that seem terribly applicable to my situation.</p>

<p>I'm currently trying to test a service (not a component) that has a async dependency on another service. I'm not 100% sure at what point in the test it's valid to check the results of the async call. Can you just call <code>expect()</code> inside the async handler for your service?</p>

<pre><code>service.foo()
    .then((data) =&gt; {
        //do I check the results in here?
        expect(data).toEqual({ a: 1, b: 2 });
        expect(mockDep.get).toHaveBeenCalled();
    });
</code></pre>

<p>Here is the full test.</p>

<pre><code>import { TestBed, inject } from '@angular/core/testing';
import { MyService } from './my.service.ts';
import { MyDependency } from './dependency.service.ts';

class MockDependency {
    doSomething(): Promise&lt;any&gt; {
        throw Error('not implemented');
    };
}

describe('some tests', () =&gt; {
    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            providers: [
                MyService,
                {
                    provide: MyDependency, useClass: MockDependency
                }
            ]
        });
    });
});

it('should do something', inject([MyService, MyDependency], (service: MyService, mockDep: MyDependency) =&gt; {
    spyOn(mockDep, 'doSomething').and.callFake(function () {
        return Promise.resolve({ a: 1, b: 2 });
    });

    service.foo()
        .then((data) =&gt; {
            //do I check the results in here?
            expect(data).toEqual({ a: 1, b: 2 });
            expect(mockDep.get).toHaveBeenCalled();
        });
}));
</code></pre>
",https://stackoverflow.com/questions/42911591/angular2-async-unit-testing-with-jasmine,"['unit-testing', 'angular', 'asynchronous', 'jasmine']",8864,TRUE,7,1
aws lambda js unit testing,"<p>I've been looking into aws lambda. How are people testing the harness for api gateway requests responses? In Java I have a lambda that's a bit like this.</p>

<pre><code>import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
...
@Test
void turnsBarToFooTest() {

    TestContext ctx = new TestContext(); //implements  com.amazonaws.services.lambda.runtime.Context

    Fooer handler = new Fooer();

    APIGatewayProxyRequestEvent request = new APIGatewayProxyRequestEvent();
    Map&lt;String, String&gt; params = HashMap.of(""thing_to_foo"", ""bar"");
    request.setPathParameters(params.toJavaMap());

    APIGatewayProxyResponseEvent response = handler.handleRequest(request, ctx);
    assertEquals(200, response.getStatusCode().intValue());
    assertEquals(""foo"", response.getBody());
}
</code></pre>

<p>I'd love to do something really simple with Jest and ES6 to replicate the above. Are there similar known events objects to use? How can I wire them up with jest. </p>
",https://stackoverflow.com/questions/47268736/aws-lambda-js-unit-testing,"['ecmascript-6', 'aws-lambda', 'aws-api-gateway', 'jestjs']",1025,TRUE,0,2
AngularJS unit testing Conditional responses,"<p>I am using angularjs with karma/jasmine for my testing.</p>

<p>How would I unit test the successCallback with the 3 conditional if responses? I have this function in my angularjs project:</p>

<pre><code>function loginCtrl($scope, $http, $log, $window) {
    $scope.error = '';
    $scope.submit = function () {
    $http({
        method: 'POST',
        url: '/login',
        headers: {'Content-Type': 'application/json'},
        data: {'username': $scope.username, 'password': $scope.userpassword},
    }).then(function successCallback(response, data) {
        if (response.data.successful) {
            //Success
            console.info('INFO: checkboxes.js::/login successful');
            $window.location.href = '/';                
        } else if (response.data.error) {
            //Error invalid credientials
            $scope.error = 'ERROR: ' + response.data.error;
            console.error('ERROR: checkboxes.js::/login error:', response.data.error);
        } else {
            //Error no creds sent. Empty body
            $scope.error = 'Invalid login: username and password combination'
            console.error('ERROR: checkboxes.js::/login invalid credentials')
        }
    }, function errorCallback(response) {
        $scope.error = 'An error occured, please try again later.'
        console.error('ERROR: checkboxes.js::/login', response.error)
    });
};
}
</code></pre>

<p>I tried the below test code to try and hit the first if block with no success. </p>

<pre><code>    it('expects POST on /login success and reroutes to home page', function () {
        var response = {data:{successful:true}}
        var url = '/login',
            data = {
                'username': 'test.person', 
                'password': 'test'
            },
            header = {'Content-Type': 'application/json'},
            successCallback = jasmine.createSpy('success'),
            errorCallback = jasmine.createSpy('error');

        $httpBackend.expectPOST(url, data, header
        ).respond(200, response.data.successful)
        scope.submit();

        expect(successCallback).not.toHaveBeenCalled();
        $httpBackend.flush;
        expect(fakeWindow.location.href).toBe('/');
    }); 
</code></pre>
",https://stackoverflow.com/questions/45044686/angularjs-unit-testing-conditional-responses,"['angularjs', 'jasmine']",191,FALSE,0,1
Swift project unit testing fail,"<p>Is it normal to add all files to tests target? I think that if you make @testable import TragetName it must automatically use all files from imported target or I'm not right?</p>
",https://stackoverflow.com/questions/43892249/swift-project-unit-testing-fail,"['swift', 'xcode', 'unit-testing', 'target']",74,FALSE,0,0
Unit testing AngularJS Directives with Jest,"<p>I feel I am missing something crucial in this extremely simplified angular directive unit test:</p>

<pre><code>import * as angular from 'angular'
import 'angular-mocks'

const app = angular.module('my-app', [])

app.directive('myDirective', () =&gt; ({
    template: 'this does not work either',
    link: (scope, element) =&gt; { // have also tried compile fn
        console.log('This does not log')
        element.html('Hi!')
    }
}))

describe('myDirective', () =&gt; {
    var element, scope

    beforeEach(app)

    beforeEach(inject(($rootScope, $compile) =&gt; {
        scope = $rootScope.$new()
        element = $compile('&lt;my-directive /&gt;')(scope)
        scope.$digest()
    }))

    it('should actually do something', () =&gt; {
        expect(element.html()).toEqual('Hi!')
    })
})
</code></pre>

<p>When jest runs it appears the directive has not been linked/compiled/whatever</p>

<pre><code> FAIL  test/HtmlToPlaintextDirective.spec.js
  ● myDirective › should actually do something

    expect(received).toEqual(expected)

    Expected value to equal:
      ""Hi!""
    Received:
      """"
</code></pre>
",https://stackoverflow.com/questions/43110646/unit-testing-angularjs-directives-with-jest,"['angularjs', 'jestjs', 'angular-mock']",6834,TRUE,7,2
express.js router unit testing error,"<p>I have a node/express application with a controller and service. While running the unit test for controller via <code>Grunt/Jasmine</code>, the test runs fine but after the coverage summary I get the following error:</p>

<blockquote>
  <p>error: Error on SAVE state TypeError: Cannot read property 'apply' of undefined
      at /node_modules/express/lib/router/index.js:603:14
      at next (/node_modules/express/lib/router/index.js:246:14)
      at next (/node_modules/express/lib/router/route.js:100:14)</p>
</blockquote>

<p>Controller.js</p>

<pre><code>var express = require('express'),
router = express.Router();
module.exports = function(app) {
  app.use('/api', router);
  router.post('/save', function(req, res, next) {
     // Service code is invoked here with the success/error callback
     // on success - res.json(response);
     // on error - res.status(err.status);
  });
}
</code></pre>

<p>ControllerSpec.js</p>

<pre><code>var app = require('../mockApp'); // the app.js and the express app is mocked here
var httpMocks = require('node-mocks-http');
var request = require('request'); 
describe(""Controller SAVE Action"", function () {
   it(""With Error"", function () {
      spyOn(service, ""save"").andCallFake(function (req, res, headers, callback) {
      callback({category: ""Error""});
      });
      var rout = app.getRouter(""/state""); // the mocked app.js contains a getRouter function which returns the corresponding router which is simply express.Router()
      var request = httpMocks.createRequest({
        method: 'POST',
        url: '/save',
        headers: {""authorization"": ""success""}
      });
      var response = httpMocks.createResponse();
      rout(request, response);
      var data = JSON.parse(response._getData());
      expect(data.code).toEqual(400);
   });
});
</code></pre>

<p>Mocked app.js </p>

<pre><code>var m = {};
var routers = {};
module.exports = {
 get: function (name) {
  return m[name];
 }, set: function (name, obj) {
  m[name] = obj;
 }, use: function (path, router) {
  if (router) {
    routers[path] = router;
  }
 }, getRouter: function (path) {
  return routers[path];
 }
};
</code></pre>

<p>Mocked Express.js</p>

<pre><code>var app = require('./app'); // Mocked app.js
var services = {};
var serviceFiles = glob.sync(rootPath + '/app/services/*.js');
serviceFiles.forEach(function (file) {
  var service = require(file)(app);
  services[service.serviceName] = service;
 });
 app.set(""services"", services);

var controllers = glob.sync(rootPath + '/app/controllers/*.js');
controllers.forEach(function (controller) {
  require(controller)(app);
});
</code></pre>
",https://stackoverflow.com/questions/47958513/express-js-router-unit-testing-error,"['javascript', 'node.js', 'unit-testing', 'express']",385,FALSE,0,0
Unit testing and Integration testing,"<p>i'm currently developping a nodejs/express rest api (personal project), and i wanted to learn as much as i ca from this project.</p>

<p>So in my project i'm using <code>sequelize</code> as an <code>ORM</code> layer, i have a model named `bus, and i have build CRUD endpoint to this model.</p>

<p>now i want to do some test this model/api i have developped, i read some tutorial about testing and found that there are multiple type of testing seperated in two big categories : white-box vs black-box.</p>

<p>So i have written some integration tests that test my api(integration test are black-box testing)</p>

<p>and i want right know to write some unit-testing, but i don't know what to test, the <code>bus</code> model is a Sequelize model, so everything that i would test would be already tested in the <code>sequelize</code> library it self. and testing the api endpoints is done via integration tests.</p>

<p>PS: its my first time writing tests.</p>

<p>i'm using the following technologies :  <code>nodejs</code>, <code>sequelize</code>, <code>express</code>, <code>mocha</code>, <code>chai</code>.</p>

<p><strong>Bus Model Definition</strong></p>

<pre><code>const Sequelize = require('sequelize');

module.exports = function(sequelize) {

    let Bus =  sequelize.define('bus', {
        name: {
            type: Sequelize.STRING,
        },
    });


    Bus.associate = function(models) {
        Bus.hasOne(models.LaneBus, {
            foreignKey: 'busId'
        });
    };

    return Bus;
} 
</code></pre>

<p><strong>Bus Api endpoint testings</strong> </p>

<pre><code>const request = require('superagent');
const expect = require('chai').expect;

const app = require('../../src/app');
var http = require('http');

const models = require('../../src/models');


describe(""bus"", function () {

    var bus_id;

    it('should create bus', function (done) {

        request.post('http://localhost:3000/bus')
            .type('form')
            .send({
                name: 'bus_test_1',
            }).set('Accept', 'application/json')
            .set('Authorization', global.JWT_TOKEN_TEST_ADMIN)
            .end((err, res) =&gt; {
                expect(res.status).to.be.eq(201, 'invalid return code');
                expect(res.body.status).to.be.eq('success', 'invalid retun status');

                bus_id = res.body.id;

                done();
            })
    });

    it('should get list of bus', function (done) {

        request.get('http://localhost:3000/bus')
            .set('Accept', 'application/json')
            .end((err, res) =&gt; {
                expect(res.status).to.be.eq(200, 'invalid return code');
                expect(res.body.metadata).to.not.be.undefined

                done();
            })
    });


    it('should modify bus', function (done) {

        request.put(`http://localhost:3000/bus/${bus_id}`)
            .type('form')
            .send({
                name: 'bus_test_2'
            })
            .set('Authorization', global.JWT_TOKEN_TEST_ADMIN)
            .end((err, res) =&gt; {
                expect(res.status).to.be.eq(200, 'invalid return code');
                expect(res.body.status).to.be.eq('success', 'invalid retun status');
                done();
            });
    });

    it('modify bus should get error because bus dont exists', function (done) {

        request.put(`http://localhost:3000/bus/aaa`)
            .type('form')
            .send({
                name: 'bus_test_2'
            })
            .set('Authorization', global.JWT_TOKEN_TEST_ADMIN)
            .end((err, res) =&gt; {
                expect(res.status).to.be.eq(404, 'invalid return code');
                expect(res.body.status).to.be.eq('failure', 'invalid return code');
                done();
            });
    });


    it('should get bus', function (done) {

        request.get(`http://localhost:3000/bus/${bus_id}`)
            .end((err, res) =&gt; {
                expect(res.status).to.be.eq(200, 'invalid return code');
                expect(res.body.name).to.be.eq('bus_test_2');
                done();
            });
    });

    it('get bus should return error because bus dont exist', function (done) {

        request.get(`http://localhost:3000/bus/aaaa`)
            .end((err, res) =&gt; {
                expect(res.status).to.be.eq(404, 'invalid return code');
                expect(res.body.status).to.be.eq('failure', 'invalid return code');
                done();
            });
    });



    it('user role cannot create bus', function (done) {
        request.post('http://localhost:3000/bus')
            .type('form')
            .send({
                name: 'bus_test_1',
            }).set('Accept', 'application/json')
            .set('Authorization', global.JWT_TOKEN_TEST_USER)
            .end((err, res) =&gt; {
                expect(res.body.status).to.be.eq('failure', 'invalid retun status');


                done();
            })
    })

    it('user role cannot modify bus', function (done) {
        request.put(`http://localhost:3000/bus/${bus_id}`)
            .type('form')
            .send({
                name: 'bus_test_2'
            })
            .set('Authorization', global.JWT_TOKEN_TEST_USER)
            .end((err, res) =&gt; {
                expect(res.body.status).to.be.eq('failure', 'invalid retun status');
                done();
            });
    })


    it('user role cannot delete bus', function (done) {
        request.delete(`http://localhost:3000/bus/${bus_id}`)
            .set('Authorization', global.JWT_TOKEN_TEST_USER)
            .end((err, res) =&gt; {
                expect(res.body.status).to.be.eq('failure', 'invalid return code');
                done();
            });
    })


    it('should delete bus', function (done) {

        request.delete(`http://localhost:3000/bus/${bus_id}`)
            .set('Authorization', global.JWT_TOKEN_TEST_ADMIN)
            .end((err, res) =&gt; {
                expect(res.status).to.be.eq(200, 'invalid return code');
                done();
            });
    });

    it('delete bus should get error because bus dont exist', function (done) {

        request.delete(`http://localhost:3000/bus/${bus_id}`)
            .set('Authorization', global.JWT_TOKEN_TEST_ADMIN)
            .end((err, res) =&gt; {
                expect(res.status).to.be.eq(404, 'invalid return code');
                expect(res.body.status).to.be.eq('failure', 'invalid return code');
                done();
            });
    });





});
</code></pre>
",https://stackoverflow.com/questions/44724136/unit-testing-and-integration-testing,"['node.js', 'unit-testing', 'express', 'testing', 'mocha.js']",602,TRUE,-1,2
Unit testing a jee filter,"<p>I am trying to test this filter:</p>

<pre><code>public class HttpMethodOverrideHeaderFilter extends OncePerRequestFilter {
    private static final String X_HTTP_METHOD_OVERRIDE_HEADER = ""X-HTTP-Method-Override"";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        if (isMethodOverriden(request)) {
            HttpServletRequest wrapper = new HttpMethodRequestWrapper(request, request.getHeader(X_HTTP_METHOD_OVERRIDE_HEADER).toUpperCase(Locale.ENGLISH));
            filterChain.doFilter(wrapper, response);
        }
        else {
            filterChain.doFilter(request, response);
        }

    }

    private boolean isMethodOverriden(HttpServletRequest request) {
        String methodOverride = request.getHeader(X_HTTP_METHOD_OVERRIDE_HEADER);
        return RequestMethod.POST.name().equalsIgnoreCase(request.getMethod()) &amp;&amp;
                (RequestMethod.PUT.name().equalsIgnoreCase(methodOverride) || RequestMethod.DELETE.name().equalsIgnoreCase(methodOverride));
    }

    protected static class HttpMethodRequestWrapper extends HttpServletRequestWrapper {
        private final String method;

        public HttpMethodRequestWrapper(HttpServletRequest request, String method) {
            super(request);
            this.method = method;
        }

        @Override
        public String getMethod() {
            return this.method;
        }
    }

}
</code></pre>

<p>And this is the unit test:</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)
public class HttpMethodOverrideHeaderFilterTest {

    private static final String X_HTTP_METHOD_OVERRIDE_HEADER = ""X-HTTP-Method-Override"";

    private HttpMethodOverrideHeaderFilter httpMethodOverrideHeaderFilter;

    @Mock
    private HttpServletRequest httpServletRequest;

    @Mock
    private HttpServletResponse httpServletResponse;

    @Mock
    private FilterChain filterChain;

    @Before
    public void setUp() {
        httpMethodOverrideHeaderFilter = new HttpMethodOverrideHeaderFilter();
    }

    @Test
    public void testDoFilterInternalWithPUTMethodAsOverrideHeader() throws Exception {
        when(httpServletRequest.getHeader(X_HTTP_METHOD_OVERRIDE_HEADER)).thenReturn(""PUT"");
        when(httpServletRequest.getMethod()).thenReturn(""POST"");

        HttpServletRequest wrapper = new HttpMethodOverrideHeaderFilter.HttpMethodRequestWrapper(httpServletRequest, ""PUT"");

        httpMethodOverrideHeaderFilter.doFilterInternal(httpServletRequest, httpServletResponse, filterChain);
        verify(filterChain).doFilter(wrapper, httpServletResponse);
    }

}
</code></pre>

<p>The test is not passing as wrapper is not the same instance. Basically what I need to know is if the wrapper was set the PUT method. Any ideas?</p>
",https://stackoverflow.com/questions/42113674/unit-testing-a-jee-filter,"['testing', 'junit']",239,FALSE,0,1
Spring Unit Testing File Upload,"<p>I am trying to test file upload using spring test.</p>

<pre><code>@Test
    public void testUploadDocument() {

File f = new File(""C:\\Users\\JC\\Documents\\sample_test_2.xlsx"");
        System.out.println(f.isFile()+""  ""+f.getName()+f.exists());
        FileInputStream fi1 = new FileInputStream(f);
        MockMultipartFile fstmp = new MockMultipartFile(""file"", f.getName(), ""text/plain"", fi1);
        MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
        mockMvc.perform(MockMvcRequestBuilders.fileUpload(""http://"" + hostPort + ""/AdminService/rest/document/saveDocument"")
                .file(fstmp)
                .param(""siteId"",""555"").param(""docTypeId"",""550"").param(""docSubTypeId"", ""5051"").param(""contentDate"", ""06-Oct-2017"").param(""contentDescription"", """")
                .param(""docName"", ""Test Co-op Unit 2"").param(""isNewFile"", ""true""))              
                .andExpect(MockMvcResultMatchers.status().isOk());
}
</code></pre>

<p>It is throwing Requested Method POST not supported even though I declared it as POST. Also I tried MockMvcRequestBuilders.post. But same problem.</p>

<pre><code> @RequestMapping(value = ""/saveDocument"", method = RequestMethod.POST)
        public ResponseEntity&lt;String&gt; saveDocument(
                @RequestParam(""siteId"") Integer siteId, @RequestParam(""docTypeId"") Integer docTypeId,
                @RequestParam(""docSubTypeId"") Integer docSubTypeId, @RequestParam(""docName"") String docName,
                @RequestParam(value = ""contentDescription"", required = false) String contentDescription,
                @RequestParam(value = ""contentDate"", required = false) String contentDate, @RequestParam(value = ""docId"", required = false) Integer docId,
            @RequestParam(value = ""isNewFile"", required = false) boolean isNewFile,
            @RequestParam(value = ""file"", required = false) MultipartFile file)
</code></pre>
",https://stackoverflow.com/questions/46607564/spring-unit-testing-file-upload,"['java', 'spring', 'unit-testing']",416,FALSE,0,0
Angular 5: Unit testing getters and setters,"<p>I am unable to test getter and setter functions in Angular 5 using Karma. Any ideas as to where I'm going wrong?</p>

<p>The value is set and then the test waits a short duration for the setter function to resolve before calling the getter function. Here is the code:</p>

<p><strong>service.ts</strong></p>

<pre><code>set header(h: string) {
    this.zone.run(() =&gt; {
        this._header = h;
    });
}

get header(): string {
    return this._header;
}
</code></pre>

<p><strong>test.ts</strong></p>

<pre><code>before(() =&gt; {
    service = new Service()
});

it('updates header', (done) =&gt; {
    const header = 'test header';
    service.header = header;

    // Give header time to update
    return Promise.delay(200)
    .then(() =&gt; {
         expect(service.header).to.equal(header);
    })
});
</code></pre>

<p>I would expect the assertion to resolve successfully however I get an error </p>

<blockquote>
  <p>AssertionError: expected undefined to equal 'test header'</p>
</blockquote>
",https://stackoverflow.com/questions/47698144/angular-5-unit-testing-getters-and-setters,"['angular', 'unit-testing', 'karma-runner']",14179,TRUE,14,1
Unit testing: Am I doing right when using another method in unit testing a method?,"<p>To my best knowledge, unit testing should be done on each public API separately. But, I have been experiencing with a situation in which I have not found out a clear way to unit test each API independently as shown in the following example:</p>

<pre><code>class MyStorage {
private:
    std::vector&lt;int&gt; int_vec_;

public:
    bool insert_int(int value);
    int get_value_at(int idx);
}
</code></pre>

<p>I used GooogleTest framework and wrote unit tests as follows:</p>

<pre><code>int int_tenth(int x) { return x * 10; }

TEST_F(MyStorageTest, insert_int) {
    for(int i = 0; i &lt; 10; i++) {
        int value = int_tenth(i);
        bool ret = my_storage.insert_int(value);
        ASSERT_TRUE(ret);
    }
}

TEST_F(MyStorageTest, get_value_at) {
    for(int i = 0; i &lt; 10; i++) {
        int value = int_tenth(i);
        my_storage.insert_int(value);
    }

    for(int i = 0; i &lt; 10; i++) {
        int expected_value = int_tenth(i);
        int value = my_storage.get_value_at(i);
        ASSERT_EQ(expected_value, value);
    }
}
</code></pre>

<p>Am I doing right? If not, how can I make unit tests for this example?</p>
",https://stackoverflow.com/questions/44994780/unit-testing-am-i-doing-right-when-using-another-method-in-unit-testing-a-metho,"['unit-testing', 'tdd', 'googletest']",244,TRUE,1,1
Angular 5 unit testing http response,"<p>I'm trying to unit test my http.get/post/etc responses.</p>

<p>I found this tutorial that was extremely helpful: <a href=""https://medium.com/spektrakel-blog/angular-testing-snippets-httpclient-d1dc2f035eb8"" rel=""noreferrer"">https://medium.com/spektrakel-blog/angular-testing-snippets-httpclient-d1dc2f035eb8</a></p>

<p>Going through and following that, I've configured my unit tests and I'm able to get everything working, but there's one part that I have that is inconsistent with the tutorial...</p>

<p>In the tutorial, it shows to test the service login function like this:</p>

<pre><code> it(`should emit 'true' for 200 Ok`, async(inject([HttpClientFeatureService, HttpTestingController],
    (service: HttpClientFeatureService, backend: HttpTestingController) =&gt; {
      service.login('foo', 'bar').subscribe((next) =&gt; {
        expect(next).toBeTruthy();
      });

      backend.expectOne('auth/login').flush(null, { status: 200, statusText: 'Ok' });
  })));
</code></pre>

<p>And here's the actual method on the service that is being tested:</p>

<pre><code>login(user: string, password: string): Observable&lt;boolean&gt; {
    const body = new HttpParams()
      .set(`user`, user)
      .set(`password`, password);
    const headers = new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' });

    return this.http.post(`auth/login`, body.toString(), { headers, observe: 'response' })
      .map((res: HttpResponse&lt;Object&gt;) =&gt; res.ok)
      .catch((err: any) =&gt; Observable.of(false));
  }
</code></pre>

<p>Here's my login function:</p>

<pre><code>login(username: string, password: string): Observable&lt;any&gt; {
    this.loggingService.log('LoginService | login | username: ' + username + '; password: xxxxx');

    return this.http.post(this.loginUrl, { username: username, password: password })
        .map((response: any) =&gt; {
            console.log('response: ' + JSON.stringify(response));

            if (response &amp;&amp; response.length &gt; 0) {
                return response;
            } else {
                return this.parseErrorResponse(response);
            }
        });
}
</code></pre>

<p>And here's my unit test:</p>

<pre><code>it('login should return a valid JWT', async(inject([LoginService, HttpTestingController], (service: LoginService, backend: HttpTestingController) =&gt; {
    service.login('user', 'password').subscribe((next) =&gt; {
        expect(next).toEqual('asdfasdfasdf');
    });

    backend.expectOne(environment.authenticationServiceBaseUrl + 'api/login')
        .flush('asdfasdfasdf', { status: 200, statusText: 'Ok' });
})));
</code></pre>

<p>You'll notice the difference here is in the map response section. My version is getting back just a string from the unit test's http.post call, while the example shows that it's returning an HttpResponse object and is just checking that the <code>statusText</code> property is equal to 'Ok'.</p>

<p>Why is my version returning just the string, while the examples version is returning the actual HttpResponse (which includes status and statusText)? I WANT the tutorial version here...</p>

<p>The example shows that it returns <code>null</code> in the body of the response via the flush function call, while I had to add my dummy JWT value in there in order to get my test to pass. Even when I specify that as <code>null</code> to be like the test, then the response that I get in the unit test is <code>null</code>.</p>

<p>Where am I going wrong here?</p>
",https://stackoverflow.com/questions/47929136/angular-5-unit-testing-http-response,"['unit-testing', 'mocking', 'angular5']",12789,TRUE,6,1
Unit-testing EF&#39;s state management code,"<p>I'm writing a bunch of unit tests for my ASP.NET MVC app using Entity Framework (against a SQL Server database).</p>

<p>I'm using Rowan Miller's excellent Nuget packages ""EntityFramework.Testing"" and ""EntityFramework.Testing.Moq"" to allow me to unit test EF code (without actually having a real SQL Server database around).</p>

<p>This is my NUnit 3.5 test fixture (in reality, it has a lot more tests - but it's just to show how things are set up):</p>



<pre class=""lang-cs prettyprint-override""><code>[TestFixture]
public class ContactsUseCaseTests : MyUnitTestBase
{
    private Mock&lt;MyModel&gt; _mockDbContext;
    private MockDbSet&lt;Contact&gt; _mockDbSetContact;
    private IContactsUseCase _usecase;

    [SetUp]
    public void InitializeTest()
    {
        SetupTestData();
        _usecase = new ContactsUseCase(_mockDbContext.Object);
    }

    [Test]
    public void TestSaveEntryNotNewButNotFound()
    {
        // Arrange
        Contact contact = new Contact { ContactId = 99, FirstName = ""Leo"", LastName = ""Miller"" };

        // Act
        _usecase.SaveContact(contact, false);

        // Assert
        _mockDbSetContact.Verify(x =&gt; x.Add(It.IsAny&lt;Contact&gt;()), Times.Once);
        _mockDbContext.Verify(x =&gt; x.SaveChanges(), Times.Once);
    }

    private void SetupTestData()
    {
        var contacts = new List&lt;Contact&gt;();

        contacts.Add(new Contact { ContactId = 12, FirstName = ""Joe"", LastName = ""Smith"" });
        contacts.Add(new Contact { ContactId = 17, FirstName = ""Daniel"", LastName = ""Brown"" });
        contacts.Add(new Contact { ContactId = 19, FirstName = ""Frank"", LastName = ""Singer"" });

        _mockDbSetContact = new MockDbSet&lt;Contact&gt;()
            .SetupAddAndRemove()
            .SetupSeedData(contacts)
            .SetupLinq();

        _mockDbContext = new Mock&lt;MyModel&gt;();
        _mockDbContext.Setup(c =&gt; c.ContactList).Returns(_mockDbSetContactList.Object);
        _mockDbContext.Setup(c =&gt; c.Contact).Returns(_mockDbSetContact.Object);
    }
}
</code></pre>

<p>As you can see, in the <code>[SetUp]</code> method, I'm calling <code>SetupTestData</code> which is creating the <code>Mock&lt;MyModel&gt;</code> for mocking the entire <code>DbContext</code>, and it sets up a <code>MockDbSet&lt;Contact&gt;</code> to handle my contacts.</p>

<p>Most tests works just fine against this setup - until I came across the <code>SaveContact</code> method here:</p>

<pre class=""lang-cs prettyprint-override""><code>public void SaveContact(Contact contactToSave, bool isNew) {
    if (isNew) {
        ModelContext.Contact.Add(contactToSave);
    } else {
        ModelContext.Entry(contactToSave).State = EntityState.Modified;
    }
    ModelContext.SaveChanges();
}
</code></pre>

<p>As you can see, if I'm trying to save a <code>Contact</code> that already exists, all I'm doing is setting it's <code>State</code> flag to <code>Modified</code> and letting EF handle all the rest.</p>

<p>Works great <strong>at runtime</strong> - but here in the test, it causes the test code to want to connect to the database - which I don't have at hand.</p>

<p>So what do I need to do additionally to make it possible to unit-test this line of code using my EF Mocking infrastructure? Can it be done at all?</p>

<pre class=""lang-cs prettyprint-override""><code>ModelContext.Entry(contactToSave).State = EntityState.Modified;
</code></pre>
",https://stackoverflow.com/questions/47392982/unit-testing-efs-state-management-code,"['c#', 'unit-testing', 'mocking', 'entity-framework-6', 'moq']",725,TRUE,5,1
Unit testing with Realm in iOS,"<p>I followed the guide on Realm's website, but my test are still producing varying results, depending on the random order they are done.</p>

<p>Either they succeed when run individually, or fail because the data was already set. For example:</p>

<pre><code>XCTAssert(observer.events[0].value.element == """", ""Initail hub name is expected to be equal to be an empty string but was \(String(describing: observer.events[0].value.element))"")
XCTAssert(observer.events[1].value.element == testHubName, ""Initail hub name is expected to be equal to be the name we set but was \(String(describing: observer.events[1].value.element))"")
</code></pre>

<p>In this example, <code>event[0]</code> is already set to <code>testHubName</code>.
Or it gets a <code>@throw RLMException(@""Object has been deleted or invalidated."");</code><br>
So I guess there is some kind race going around, but this is in my <code>setup</code> method:</p>

<pre><code>func setupRealm() {
    testRealm = try! Realm(configuration: Realm.Configuration(inMemoryIdentifier: ""DORSessionViewModelTestsRealm""))
    try! self.testRealm.write {
        self.testRealm.deleteAll()
    }
}
</code></pre>

<p>So as far as I understand I should have a fresh Realm for every test, so where is the race going on?</p>

<p>Edit: 
Adding a bigger part of the class</p>

<pre><code>class DORSessionViewModelTests: XCTestCase {

var disposeBag: DisposeBag = DisposeBag()
var scheduler = TestScheduler(initialClock: 0)
var testRealm: Realm!


override func setUp() {

    super.setUp()
    setupRealm()
    setupRx()
}


override func tearDown() {
    super.tearDown()
}

func testHubNameLabelTextUpdate() {
    let expectation = self.expectation(description: ""expect hub name text to update"")
    let testHubName = ""testHubName""
    let viewModel = getSessionViewModel()

    let observer = scheduler.createObserver(String.self)
    scheduler.start()
    let hubNameDriver = viewModel.hubNameLabelText()
    hubNameDriver.asObservable().subscribe(observer).disposed(by: disposeBag)
    hubNameDriver.asObservable().skip(1).subscribeNext { _ in expectation.fulfill()}.disposed(by: disposeBag)

    try! self.testRealm.write {
        viewModel.dependencies..hub.name = testHubName
    }


    waitForExpectations(timeout: 5, handler: { error in
        XCTAssert(observer.events[0].value.element == """", ""Initail hub name is expected to be equal to be an empty string but was \(String(describing: observer.events[0].value.element))"")
        XCTAssert(observer.events[1].value.element == testHubName, ""Initail hub name is expected to be equal to be the name we set but was \(String(describing: observer.events[1].value.element))"")
    })
}

func setupRx() {
    disposeBag = DisposeBag()
    scheduler = TestScheduler(initialClock: 0)
}
</code></pre>
",https://stackoverflow.com/questions/44695727/unit-testing-with-realm-in-ios,"['ios', 'swift', 'realm']",4202,FALSE,5,0
Unit testing for uploading to S3,"<p>I'm having trouble writing unit tests for a method that overwrites a file to a S3 bucket. The method grabs the original metadata of the file, and then overwrites the file with a new modified version and the same original metadata. </p>

<p>What I want the test to do is verify the inner methods like <code>getObjectMetadata</code> and <code>putObject</code> are called correctly with the right parameters</p>

<p>Here is the method:</p>

<pre><code> public void upload(File file, String account, String bucketName) {
        String key = ""fakekey"";
        ObjectMetadata objMData = client.getObjectMetadata(bucketName, key).clone();
        try {
            // cloning metadata so that overwritten file has same metadata as original file
            client.putObject(new PutObjectRequest(bucketName, key, file).withMetadata(objMData));
        } catch(AmazonClientException e) {
            e.printStackTrace();
        } 
</code></pre>

<p>Here is my test method:</p>

<pre><code>@Mock
private AmazonS3 client = new AmazonS3Client();

public void testUpload() {

    S3Uploader uploader = new S3Uploader(client);

    File testFile = new File(""file.txt"");
    String filename = ""file.txt"";
    String bucketname = ""buckettest"";
    String account = ""account"";

    String key = account+filename;
    ObjectMetadata objMetadata = Mockito.mock(ObjectMetadata.class);
    when(client.getObjectMetadata(bucketname, key).clone()).thenReturn(objectMetadata);

    // can I make this line do nothing? doNothing()??
    doNothing.when(client.putObject(Matchers.eq(new PutObjectRequest(bucketName, key, file).withMetadata(objMData))));

    uploader.upload(aFile, anAccount, bucketName);

    // how do I verify that methods were called correctly??
    // what can I assert here?

}
</code></pre>

<p>I'm getting a <code>NullPointerException</code> at the line in my test     </p>

<pre><code>when(client.getObjectMetadata(bucketname, key).clone()).thenReturn(objectMetadata);
</code></pre>

<p>I'm not even able to reach the method call. Honestly, what I'm pretty much asking is, how do I verify that this <code>upload()</code> method is correct?</p>
",https://stackoverflow.com/questions/45293647/unit-testing-for-uploading-to-s3,"['java', 'unit-testing', 'amazon-s3', 'junit']",29213,TRUE,5,2
Unit testing class library using Realm.Net,"<p>I'm developing a class library(<code>RealmClassLibrary</code>) which using Realm Xamarin(.NET).
I want to test the library using xunit(<code>RealmClassLibrary.Test</code>). 
And I got a <code>TypeInitializationException</code> when the library code calls <code>Realm.GetInstance(config)</code></p>

<p>This exception is not thrown when I embedded class library in Windows Application(<code>RealmClassLibrary</code>.Example).</p>

<p>How could I fix this problem?
Is there best practice to unit test realm based project?</p>

<p>Any helps appreciated.</p>

<h2>Simple regeneration code</h2>

<p><a href=""https://github.com/engraphia/RealmClassLibrary"" rel=""noreferrer"">https://github.com/engraphia/RealmClassLibrary</a></p>

<h3>Error log</h3>

<pre><code>RealmClassLibrary.Tests.Class1Test.testMain [FAIL]
  System.TypeInitializationException : The type initializer for 'Realms.Realm' threw an exception.
  ---- System.DllNotFoundException : Unable to load DLL 'realm-wrappers': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
  Stack Trace:
       at Realms.Realm.GetInstance(RealmConfigurationBase config)
    \\RealmClassLibrary\RealmClassLibrary\MainClass.cs(14,0): at RealmClassLibrary.MainClass.Main()
    \\RealmClassLibrary\RealmClassLibrary.Tests\Class1Test.cs(16,0): at RealmClassLibrary.Tests.Class1Test.testMain()
    ----- Inner Stack Trace -----
       at Realms.NativeCommon.register_notify_realm_changed(NotifyRealmCallback callback)
       at Realms.Realm..cctor()
</code></pre>

<h2>version</h2>

<ul>
<li>Visual Studio (windows)

<ul>
<li>2015 update3</li>
</ul></li>
<li>.NETFramework

<ul>
<li>v4.6.1</li>
</ul></li>
<li>Realm Xamarin (.NET)

<ul>
<li>1.5.0</li>
</ul></li>
</ul>

<h2>project structure</h2>

<ul>
<li>RealmClassLibrary

<ul>
<li>target class library</li>
</ul></li>
<li>RealmClassLibrary.Tests

<ul>
<li>unit test project</li>
</ul></li>
<li>RealmClassLibrary.Example

<ul>
<li>windows application project</li>
</ul></li>
</ul>
",https://stackoverflow.com/questions/46403638/unit-testing-class-library-using-realm-net,"['c#', 'realm', 'xunit']",355,FALSE,5,0
LNK2019: unresolved external symbol in VS unit-testing,"<p>I get the error as stated in the title. I ensured the following:<br>
- The Include directory, include library and additional include directory are set correctly<br>
- In the properties, Subsystem is set to CONSOLE  </p>

<p>Comments to my code:
LifeLib is a project that contains classes of that I want to test some methods. The classes are defined in namespace LifeLib. One of them is StornoTafel. testVariables is NOT defined in any namespace.<br>
I get the linking error 3 times, for 2 constructors and 1 method in StornoTafel (noted in the code).</p>

<pre><code>//project Tester
#include ""stdafx.h""
#include ""CppUnitTest.h""

#include ""../LifeLib/StornoTafel.h""
#include ""../LifeLib/testVariables.h""

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace Tester
{       
    TEST_CLASS(AggSelTest)
    {
    public:
        LifeLib::StornoTafel stornoTafel_; // LNK2019
        LifeLib::StornoTafel *stornoTafel_; // no error, but I need an instance and not a reference to proceed -&gt; see init method
        LifeLib::testVariables test_vars_; // everything is fine

        TEST_METHOD_INITIALIZE(init) {
            stornoTafel_ = StornoTafel(test_vars_.lapseProb); // when this line is commented out I only get the first error (see below)
        }
    }
}

// testVariables.h
#pragma once
#include &lt;iostream&gt;
#include &lt;vector&gt;

class testVariables {
public:
    testVariables() {};
// here are a lot of vectors with values for testing purposes
std::vector&lt;double&gt; _lapseProb= {0,1,2}; // [...]
};

// StornoTafel.h
#pragma once
#include ""masterheader.h""

namespace LifeLib {
    class StornoTafel {
    public:

        StornoTafel(); //LNK2019
        StornoTafel(std::vector&lt;double&gt; ProbabilityOfLapseInYearT); //LNK2019

        StornoTafel(const StornoTafel &amp;obj); //no error

        StornoTafel operator=(StornoTafel const&amp; rhs); //LNK2019

        //! \name Getter
        //@{ 
        const std::vector&lt;double&gt;&amp; Stornowahrscheinlichkeit() const;
        //@}
    protected:
        std::vector&lt;double&gt; Stornowahrscheinlichkeit_;
    };
    inline const std::vector&lt;double&gt;&amp; StornoTafel::Stornowahrscheinlichkeit() const {
        return Stornowahrscheinlichkeit_;
    }
}

//StornoTafel.cpp
#include ""StornoTafel.h""

LifeLib::StornoTafel::StornoTafel() {
}

LifeLib::StornoTafel::StornoTafel(std::vector&lt;double&gt; ProbabilityOfLapseInYearT) {
    Stornowahrscheinlichkeit_ = ProbabilityOfLapseInYearT;
}

LifeLib::StornoTafel::StornoTafel(const StornoTafel &amp;obj) {
    Stornowahrscheinlichkeit_ = obj.Stornowahrscheinlichkeit_;
}

LifeLib::StornoTafel LifeLib::StornoTafel::operator=(StornoTafel const&amp; rhs) {
    Stornowahrscheinlichkeit_ = rhs.Stornowahrscheinlichkeit_;
    return *this;
}

//masterheader.h
#pragma once
#include &lt;fstream&gt;
#include &lt;iostream&gt;
#include &lt;sstream&gt;
#include &lt;string&gt;

#include &lt;algorithm&gt;
#include &lt;ctime&gt;
</code></pre>

<p>errors in detail:</p>

<blockquote>
  <ol>
  <li>LNK2019    unresolved external symbol ""public: __cdecl
  LifeLib::StornoTafel::StornoTafel(void)""
  (??0StornoTafel@LifeLib@@QEAA@XZ) referenced in function ""public:
  __cdecl AggSelTester::AggSelTest::AggSelTest(void)"" (??0AggSelTest@AggSelTester@@QEAA@XZ)</li>
  <li>LNK2019  unresolved external
  symbol ""public: __cdecl LifeLib::StornoTafel::StornoTafel(class
  std::vector >)""
  (??0StornoTafel@LifeLib@@QEAA@V?$vector@NV?$allocator@N@std@@@std@@@Z)
  referenced in function ""public: void __cdecl
  AggSelTester::AggSelTest::init(void)""
  (?init@AggSelTest@AggSelTester@@QEAAXXZ)</li>
  <li>LNK2019  unresolved external
  symbol ""public: class LifeLib::StornoTafel __cdecl
  LifeLib::StornoTafel::operator=(class LifeLib::StornoTafel const &amp;)""
  (??4StornoTafel@LifeLib@@QEAA?AV01@AEBV01@@Z) referenced in function
  ""public: void __cdecl AggSelTester::AggSelTest::init(void)""
  (?init@AggSelTest@AggSelTester@@QEAAXXZ)</li>
  </ol>
</blockquote>

<p>Why do they arise?</p>
",https://stackoverflow.com/questions/47515089/lnk2019-unresolved-external-symbol-in-vs-unit-testing,"['c++', 'visual-studio', 'unit-testing', 'linker-errors', 'lnk2019']",10059,TRUE,19,5
Unit testing of potential concurrency problems,"<p>I have had recently a small contest with one of my colleagues (whom I very respect) regarding a theoretical possibility to test whether some code is thread-safe or not.</p>

<p>Let us suppose that we have a some ""black-box"" class <code>FooUnknown</code> taken from the 3rd party library, so we don't have an access to its original source code. Furthermore, it might be that it internally uses some native methods (if this is a matter). </p>

<p>Can we write such an unit test which will tell us that usage of this class (for example, its instance shared between several threads) is 100% thread-safe or not?</p>

<p>My conclusion, that <strong>it is not possible</strong>. For me it is obvious and straightforward: although one can write a code which will lead to some concurrency problems which is possible to detect. But an absent of such results doesn't guarantee that there are not concurrency issues at all.</p>

<p>Also I believe, that this question is not <strong>too broad</strong>. For certainty let us say we have a class <code>some.FooUnknown</code> and we want to use it in the following way:</p>

<pre><code>@ApplicationScoped
public class FooService {
    private some.FooUnkown foo = new some.FooUnknown();

    public void someStuff() {
        // ...
        String result = foo.doSomeStuff();
        // ...
    }
}
</code></pre>

<p>How to test it to be sure that it is thread-safe, that we don't need to wrap it into <code>ThreadLocal&lt;FooUnknown&gt;</code> for instance?</p>
",https://stackoverflow.com/questions/47680844/unit-testing-of-potential-concurrency-problems,"['java', 'multithreading', 'unit-testing', 'concurrency', 'thread-safety']",743,TRUE,5,3
Xamarin - Cross Platform Unit Testing #2,"<p>This is a <a href=""https://stackoverflow.com/questions/26550090/xamarin-cross-platform-unit-testing"">common question</a>, it's really quite astounding to me how difficult such a simple task is turning out to be ...</p>

<p>I have a Visual Studio (formerly Xamarin) C# cross-platform library.  It has some code in the shared ""abstract"" library, and a few machine-specific implementation classes for Android, iOS, and UWP libraries.  It also has a few automated (non-UI) unit tests that use the Microsoft.VisualStudio.TestTools.UnitTesting package.  This is a great start, when Visual Studio 2017 is feeling generous it runs my unit tests and life is good.</p>

<p>Now I want to run the unit tests on simulators of the actual devices, from a command line (so I can run them from Jenkins and capture the output).  So, for example, I want to run my unit tests on a simulator of an iPad.  From various web sites I get the feeling that I can't use the Microsoft package for this, so I need to switch to either Xunit or NUnit.  I gave up on Xunit earlier today, here's how NUnit went.</p>

<ol>
<li>Go into the Unit Test project and remove the NuGet packages for Microsoft.NET.Test.Sdk, MSTest.TestFramework, and MSTest.TestAdapter.</li>
<li>Add NUnit instead (version 3.7.0).</li>
<li>Go into each CS file, change to ""using NUnit.Framework"", change [TestMethod] to [Test], and [TestClass] to [TestFixture].</li>
<li>Project:Manage NuGet Packages, add the NUnit3TestAdapter.</li>
<li>Test Explorer: Run All</li>
</ol>

<p>At this point I get this weird error for the UWP machine-specific library:</p>

<pre><code>The ""XamlCTask"" task could not be initialized with its input parameters
The ""DebugType"" parameter is not supported by the ""XamlCTask"" task.  Verify the parameter exists on the task, and it is a settable public instance property.
</code></pre>

<p>That's a really strange message, and if I Rebuild the UWP library, it rebuilds without errors.  Not sure why it's building the UWP library as part of the Unit Tests, the only thing listed under ""Projects"" is the abstract (non-machine-specific) library.</p>

<p>Also strange that building the Unit Test library works, it's only when I do the Test Explorer: Run All that I get these errors.</p>

<p>OK fine, it's a <a href=""https://forums.xamarin.com/discussion/95818/error-executing-task-xamlctask-task-does-not-have-property-debugtype-defined"" rel=""nofollow noreferrer"">known error</a>.</p>

<p>Close VS2017, delete bin and obj folders, reopen, no better. Close VS2017, hack the Xamarin.form.targets as listed.  Same error.  Realize error is in the global Xamarin.Forms.targets, not the one in my solution.  Hack it.  Close &amp; reopen solution, rebuild.  No error this time!</p>

<p>Test Explorer: Run all.  Nothing.  Output:Build shows no failures, Output:Tests is completely empty.  Close &amp; reopen solution.  Get new errors:</p>

<pre><code>[Failure] Could not find file 'C:\Workspace\PopComm.iOS\obj\Debug\TemporaryGeneratedFile_5937a670-0e60-4077-877b-f7221da3dda1.cs'.
[Failure] Could not find file 'C:\Workspace\PopComm.iOS\obj\Debug\TemporaryGeneratedFile_E7A71F73-0F8D-4B9B-B56E-8E70B10BC5D3.cs'.
[Failure] Could not find file 'C:\Workspace\PopComm.iOS\obj\Debug\TemporaryGeneratedFile_036C0B5B-1481-4323-8D20-8F5ADCB23D92.cs'.
</code></pre>

<p>Test Explorer: Run all.  This time get more interesting errors:</p>

<pre><code>------ Discover test started ------
NUnit Adapter 3.7.0.0: Test discovery starting
Assembly contains no NUnit 3.0 tests: 
C:\Workspace\PopComm.iOS\bin\iPhone\Debug\PopComm.dll
NUnit Adapter 3.7.0.0: Test discovery complete
========== Discover test finished: 0 found (0:00:00.0530024) ==========
</code></pre>

<p>Of course that assembly doesn't contain any unit tests!  It's not my unit test project!</p>

<p>Sigh.</p>

<p>OK, create a new project of type ""NUnit 3 Unit Test Project"".  Move my test classes into this new project and add a dependency to my non-machine-specific library.</p>

<p>Test Explorer: Run all - Tests!  There are tests!  And they even run successfully.</p>

<p>Close VS2017, open again, Test Explorer: Run all.  No tests.  Output:Tests is empty.</p>

<p>Close project, delete all bin and obj folders, Rebuild Solution, Test Explorer: Run All.  No tests.</p>

<p>Push code to git, pull on the Mac.</p>

<p>Open solution in Visual Studio for the Mac.</p>

<p>Use the mostly-hidden View:Test feature to bring up the Unit Tests window, run the tests.  Tests found and run.  Yippee!</p>

<p>Now I want to run my unit tests on an iPad simulator, not inside VSMac.</p>

<p>Add a new project to my solution, type iOS:Tests:Unified API:Unit Test App.</p>

<p>Wizard asks what is the minimum iOS version I want to support.  I figure I should match the iOS version that my machine-specific library targets, so I go looking in the VSMac options for the project.  The iOS target version isn't shown anywhere.  Use the default (10.3) for the Unit Test App.</p>

<p>Do I have to copy all of my unit test CS files into this new app now?  Or can I somehow reference my cross-platform unit test project in this Unit Test App?</p>

<p>Pushing everything and pulling on the Windows machine, I try adding a reference to my unit test library but get an error:</p>

<pre><code>The project 'NUnit.Tests' cannot be referenced.  The referenced project is targeted to a different framework family (.NETFramwork)
</code></pre>

<p>Hum.  I wonder what framework the new NUnit.Tests.iOS application is targeting.  Check its options - it doesn't say anywhere.  Remove the reference from the Unit Test App back to the unit test files, and just copy the unit test source files over (non-optimal).</p>

<p>Run the application in the iPad simulator, it finds &amp; runs the tests, but I don't know how to (1) run it from the command line, and (2) capture the unit test statuses in a file.</p>

<p>So after all this, I still don't know how to run my unit tests (1) from the command line, (2) on an iPad simulator, and (3) capturing the output in a text file.</p>
",https://stackoverflow.com/questions/44378482/xamarin-cross-platform-unit-testing-2,"['c#', 'ios', 'unit-testing', 'visual-studio-2017']",937,FALSE,4,0
Unit Testing No provider for ChangeDetectorRef,"<p>version: Angular 4.</p>

<p>I am injecting a parent component into child component to access parent method through child component.</p>

<p>In parent-component I had to use ChangeDetectorRef because it has a property which will update runtime.</p>

<p>Now code is working fine but child-component spec is throwing error for ""ChangeDetectorRef"" which is injected in parent component.</p>

<blockquote>
  <p>Error: No provider for ChangeDetectorRef!</p>
</blockquote>

<p>Parent Component</p>

<pre><code>import { Component, AfterViewChecked, ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'parent-component',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ParentComponent implements AfterViewChecked {

  stageWidth: number;

  constructor(private ref: ChangeDetectorRef) {
    this.ref = ref;
  }

  //call this function as many times as number of child components within parent-component.
  parentMethod(childInterface: ChildInterface) {
    this.childInterfaces.push(childInterface);
  }

  ngAfterViewChecked() {
    this.elementWidth = this.updateElementWidthRuntime();
    this.ref.detectChanges();
  }
}
</code></pre>

<p>Child Component</p>

<pre><code>import { Component, AfterViewInit } from '@angular/core';
import { ParentComponent } from '../carousel.component';

@Component({
  selector: 'child-component',
  templateUrl: './carousel-slide.component.html',
  styleUrls: ['./carousel-slide.component.scss'],
})
export class ChildComponent implements AfterViewInit {

  constructor(private parentComponent: ParentComponent) {
  }

  ngAfterViewInit() {
    this.parentComponent.parentMethod(this);
  }
}
</code></pre>

<p>app.html</p>

<pre><code>&lt;parent-component&gt;
    &lt;child-component&gt;
      &lt;div class=""box""&gt;Content of any height and width&lt;/div&gt;
    &lt;/child-component&gt;
    &lt;child-component&gt;
      &lt;div class=""box""&gt;Content of any height and width&lt;/div&gt;
    &lt;/child-component&gt;
    &lt;child-component&gt;
      &lt;div class=""box""&gt;Content of any height and width&lt;/div&gt;
    &lt;/child-component&gt;
&lt;/parent-component&gt;
</code></pre>

<p><strong>Unit test for Child Component</strong></p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { ParentComponent } from '../parent.component';
import { ChildComponent } from './child.component';

describe('ChildComponent', () =&gt; {
  let component: ChildComponent;
  let fixture: ComponentFixture&lt;ChildComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ChildComponent],
      providers: [ParentComponent]
    })
      .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(ChildComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create \'ChildComponent\'', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p>When I am trying to add ChangeDetectorRef in providers in child spec, I am getting following error.</p>

<blockquote>
  <p>Failed: Encountered undefined provider! Usually this means you have a
  circular dependencies (might be caused by using 'barrel' index.ts
  files.)</p>
</blockquote>

<p>After googling and trying many things I am unable to find solution. Any help appreciated.</p>
",https://stackoverflow.com/questions/43106708/unit-testing-no-provider-for-changedetectorref,"['unit-testing', 'karma-jasmine', 'angular']",6516,TRUE,4,2
Unit Testing with Fat-Free-Framework,"<p>Is there a way to use PHPUnit where I have a test folder with indexTest.php inside that tests routes in my index.php file? </p>

<p>The fat-free guide gives snippets of code for mocking route requests and POSTS.  I have only managed to get such a test to work if I generate the route directly in my test file with whatever functionality in it.  </p>

<p>What I would like is to mock a route with tokens, allow it to run from a route in index.php and through the controller and test f3 variables that should be set by running the route.</p>

<pre><code>&lt;?php

class indexTest extends \PHPUnit_Framework_TestCase
{
    public function test()
    {
        $f3 = Base::instance();
// Don't write to STDOUT
        $f3-&gt;set('QUIET', true);
        $f3-&gt;route('GET /path', function(){ echo 'TEXT'; });

        $this-&gt;assertNull($f3-&gt;mock('GET /path'));
        $this-&gt;assertSame('TEXT', $f3-&gt;get('RESPONSE'));

        $f3-&gt;route('GET /verify/@answer/@value',
            function($f3, $params){
                $errors = array();

                $answer = $params['answer'];
                $value = $params['value'];

                $prefix = substr($answer, 0, 3);  //pre, ans, pos
                $id = (int)substr($answer, 3);      //question id number (1, 2, 3, 4)
//$value is the input value from user

                $result = check_id($prefix, $id, $value);

                if($result !== true){
                    $errors[] = $result;
                }
                $f3-&gt;set('errors', $errors);
                return $errors;
            });

        function check_id($prefix, $id, $value)
        {
            if($prefix == 'pre' || $prefix == 'pos'){

                if($value &lt;= 0 || $value &gt; 180 || $value === NULL){
                    echo 'The input value of ' . $prefix . $id . ' question was out of bounds';
                    return 'The input value of ' . $prefix . $id . ' question was out of bounds';
                }else{
                    return true;
                }

            }else if($prefix == 'ans'){

                if($value &lt; 0 || $value &gt; 10 || $value === NULL){
                    echo 'The value of quiz ans' + $id + ' was out of bounds';
                    return 'The value of quiz ans' + $id + ' was out of bounds';
                }else{
                    return true;
                }

            }else {
                return 'The prefix does not match';
            }
        }

        $this-&gt;assertNotNull($f3-&gt;mock('GET /verify/ans1/8'));
        $this-&gt;assertEmpty($f3-&gt;get('RESPONSE')[0]);

        $this-&gt;assertNotNull($f3-&gt;mock('GET /verify/dsk4/6'));
        $this-&gt;assertSame('6', $f3-&gt;get('PARAMS.value'));
        $this-&gt;assertSame('dsk4', $f3-&gt;get('PARAMS.answer'));
        $this-&gt;assertEmpty($f3-&gt;get('RESPONSE')[0]);

        $this-&gt;assertNotNull($f3-&gt;mock('GET /verify/pre4/250'));
        $this-&gt;assertSame('The input value of pre4 question was out of bounds', $f3-&gt;get('errors')[0]);
        $this-&gt;assertNotSame('pre4', $f3-&gt;get('PARAMS.answer'));

        $f3-&gt;set('QUIET',FALSE); // allow test results to be shown later

        $f3-&gt;clear('ERROR');  // clear any errors
    }
}
</code></pre>

<p>I'd prefer not to declare the entire route like this, maybe I am entirely wrong and this is not possible?  The above code works running vendor/bin/phpunit. Relative examples and tutorials are difficult to find on this.  </p>
",https://stackoverflow.com/questions/44313940/unit-testing-with-fat-free-framework,"['phpunit', 'fat-free-framework']",955,TRUE,4,1
Unit testing redux-saga task cancellation,"<p>I was wondering if anyone had any tips on how to unit-test the following redux-saga login/logout flow:</p>

<pre><code>let pollingTask = null

function * handleLogin () {
  try {
    const token = yield call(loginHandler)
    pollingTask = yield fork(handlePolls, token)
    yield put('LOGIN_SUCCSES')
  } catch (e) {
    yield put('LOGIN_FAILURE')
  }
}

function * handlePolls (token) {
  while (true) {
    try {
      yield call(pollHandler, token)
      yield put('POLL_SUCCESS')
    } catch (e) {
      yield put('POLL_FAILURE')
    } finally {
      if (yield cancelled()) {
        yield call(pollCancelled)
      }
    }
  }
}

function * handleLogout () {
  try {
    yield call(logoutHandler)
    yield cancel(pollingTask) 
    yield put('LOGOUT_SUCCESS')
  } catch (e) {
    yield put('LOGOUT_FAILURE')
  }
}
</code></pre>

<p>Since I need to cancel the <code>pollingTask</code> on logout, I tried using <a href=""https://github.com/redux-saga/redux-saga/blob/master/docs/advanced/TaskCancellation.md#testing-generators-with-fork-effect"" rel=""nofollow noreferrer"">createMockTask()</a> in my tests but I always get its value as <code>undefined</code> when I invoke the <code>handleLogout()</code> saga, although I know that my <code>handleLogin()</code> would always be started first and it would initialize the <code>pollingTask</code>.</p>

<p>Any help would be much appreciated!</p>
",https://stackoverflow.com/questions/46166401/unit-testing-redux-saga-task-cancellation,"['unit-testing', 'redux', 'redux-saga', 'saga']",1631,TRUE,4,1
Unit Testing local function in Lua,"<p>So I'm using Busted to create unit tests for an existing Lua file, without changing the code in the file if possible. The file imports another file, and then stores various methods from that file in local functions, like so.</p>

<pre><code>[examplefile.lua]
local helper = require ""helper.lua""
local helper_accept = helper.accept
local helper_reject = helper.reject

foo = new function()
  -- do something which uses helper_accept
  -- do something which uses helper_reject
end
</code></pre>

<p>I want to spy on these methods in my tests to ensure that they have been called at the right places. However, I can't find any way to do this from the test.
I've tried simply mocking out the helper methods, as in:</p>

<pre><code>[exampletest.lua]

local helper = require ""helper.lua""
local examplefile = require ""examplefile.lua""

-- mock the helper function to simply return true
helper.accept = new function() return true end
spy.on(helper, ""accept"")
examplefile:foo
assert.spy(helper).was().called()
</code></pre>

<p>but that doesn't work as the real file uses the helper_accept and helper_reject methods, not helper.accept and helper.reject. </p>

<p>Can this be done without changing the code? 
Thanks. </p>
",https://stackoverflow.com/questions/44424819/unit-testing-local-function-in-lua,"['unit-testing', 'lua', 'local', 'lua-busted']",1535,TRUE,4,1
Unit testing Typescript in Visual Studio,"<p>I have been searching for a way to test Typescript in Visual Studio for 2 days now. It seems that there is an issue in doing this. I have tried using different frameworks i just cannot get this to work in a separate project. Does anyone have any suggestions on how to get this to work in a separate project? Do I need to create a web interface where this can be run? </p>

<p>Thank you. </p>
",https://stackoverflow.com/questions/47096752/unit-testing-typescript-in-visual-studio,"['unit-testing', 'typescript', 'visual-studio-2017']",1616,TRUE,4,1
Unit testing of Azure Data Factory,"<p>I have a VSTS CI/CD pipeline that deploys the Azure Data Factory project setup in my local to the existing data factory in Azure platform. Is there a way I can unit test my project? I understand that there is a visual studio test task in build definition. How do I create a unit test project for ADF ? Any suggestions will help. </p>
",https://stackoverflow.com/questions/44632904/unit-testing-of-azure-data-factory,"['unit-testing', 'azure', 'azure-data-factory']",3219,TRUE,4,4
Unit testing ag-grid in Angular 2,"<p>Has someone worked on unit testing ag-grid components in Angular 2?</p>

<p>For me, this.gridOptions.api remains undefined when the test cases run.</p>
",https://stackoverflow.com/questions/42299256/unit-testing-ag-grid-in-angular-2,"['unit-testing', 'angular', 'ag-grid']",7374,TRUE,11,3
Unit testing IO actions with Hspec,"<p>I have found other questions on similar lines but nothing that answers my question in this particular scenario. Furthermore, there seem to be few resources which succinctly cover the subject of unit testing IO actions in Haskell.</p>

<p>Let's say I have this typeclass for my database communication:</p>

<pre><code>data Something = Something String deriving Show

class MonadIO m =&gt; MonadDB m where
  getSomething :: String -&gt; m Something
  getSomething s = do
    ... -- assume a DB call is made and an otherwise valid function

instance MonadDB IO 
</code></pre>

<p>and this function which uses it:</p>

<pre><code>getIt :: MonadDB m =&gt; m (Int, Something)
getIt = do
  s@(Something str) &lt;- getSomething ""hi""
  return (length str, s) -- excuse the contrived example
</code></pre>

<p>I wish to test this <code>getIt</code> function with hspec but without it talking to the database, which presumably means replacing which <code>MonadDB</code> it uses, but how do I achieve that?</p>
",https://stackoverflow.com/questions/41694407/unit-testing-io-actions-with-hspec,"['haskell', 'hspec']",1882,TRUE,4,1
Unit testing Sails JS 1.0 helpers,"<p>I'm trying to setup unit testing in my SailsJS 1.0 application. I want to mock the DB and <em>not</em> have to run sails lift to test.</p>

<p>I have a very simple actions2 (node machine) helper that queries the DB:</p>

<pre><code>fn: async function (inputs, exits) {
  Users.findOne({id: inputs.userId})
    .exec((err, data) =&gt; {
      if (err) {
        return exits.error(err);
      }

      if (!data) {
        return exits.success([]);
      }

      return exits.success(data);
    });
}
</code></pre>

<p>I am using mocha as my test framework. How can I mock Users?</p>
",https://stackoverflow.com/questions/47407689/unit-testing-sails-js-1-0-helpers,"['javascript', 'node.js', 'unit-testing', 'mocking', 'sails.js']",397,FALSE,4,1
trouble unit testing reactive form fields in angular,"<p>I'm learning Angular 2 and unit testing using @angular/cli 1.0.0-beta.30 and had a bit of success testing one aspect of a form field's validity, but not all. I'm using an inline template in my component for the time being to remove a layer of complexity for now (a form template in a separate file introduces asynchronicity, correct?). </p>

<p>The <code>ngOnInit()</code> defines a <code>name</code> property  that includes the validators for ""required"" and ""minLength"". Currently an empty form field will correctly trigger the ""required"" validator but not the ""minLength"" validator. The <code>name.errors</code> array in the test does not contain any reference to required at all, <code>name.errors['minLength']</code> returns <code>undefined</code>. Does minLength need to be handled asynchronously? I'm having trouble finding docs or examples that fit my problem.</p>

<pre><code>// signup-form.component.ts
...
export class SignupFormComponent implements OnInit {

    user: FormGroup;

    constructor(private fb: FormBuilder) {
    }

    ngOnInit() {
        this.user = this.fb.group({
            name: ['', [Validators.required, Validators.minLength(2)]],
            account: this.fb.group({
                email: ['', Validators.required, Validators.pattern(""[^ @]*@[^ @]*"")],
                confirm: ['', Validators.required]
            })
        })
    }

    onSubmit({ value, valid }: { value: User, valid: boolean }) {
        console.log(value, valid);
    }

}
</code></pre>

<p><strong>My test</strong></p>

<pre><code>// signup-form.component.spec.ts
import { SignupFormComponent } from './signup-form.component';

describe('SignupFormComponent', () =&gt; {
    let component: SignupFormComponent;
    let fixture: ComponentFixture&lt;SignupFormComponent&gt;;

    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            declarations: [SignupFormComponent],
            imports: [
                ReactiveFormsModule,
                FormsModule
            ]
        })
            .compileComponents();
    }));

    beforeEach(() =&gt; {
        fixture = TestBed.createComponent(SignupFormComponent);
        component = fixture.componentInstance;
        component.ngOnInit();
        fixture.detectChanges();
    });

    it('should create', () =&gt; {
        expect(component).toBeTruthy();
    });

    it('form invalid when empty', () =&gt; {
        expect(component.user.valid).toBeFalsy();
    });

    it('name field validity', () =&gt; {
        let name = component.user.controls['name'];
        expect(name.valid).toBeFalsy();

        let errors = {};
        name.setValue("""");
        errors = name.errors || {};
        expect(errors['required']).toBeTruthy(); // this works
        expect(errors['minLength']).toBeTruthy(); // this fails, ""undefined""
    });

});
</code></pre>
",https://stackoverflow.com/questions/42143815/trouble-unit-testing-reactive-form-fields-in-angular,"['javascript', 'forms', 'validation', 'unit-testing', 'angular']",44194,TRUE,18,6
unit testing async task in csharp,"<p>I'm new to unit testing and async operations in visual studio/c#. Appreciate any help on this.</p>

<p><strong>My Main class</strong></p>

<pre><code>class Foo 
{
    public async Task&lt;string&gt; GetWebAsync()
    {
        using (var client = new HttpClient())
        {
            var response = await client.GetAsync(""https://hotmail.com"");
            return await response.Content.ReadAsStringAsync();
        }
    }
}
</code></pre>

<p><strong>Unit Test</strong></p>

<pre><code>[TestMethod]
public void TestGet()
{
    Foo foo = new Foo();

    foo.GetWebAsync().ContinueWith((k) =&gt;
    {
        Console.Write(k);
        Assert.IsNotNull(null, ""error"");
    });
}
</code></pre>
",https://stackoverflow.com/questions/42027432/unit-testing-async-task-in-csharp,"['c#', '.net', 'unit-testing', 'async-await']",15724,TRUE,4,1
Unit testing RouterLink in Angular2 component,"<p>I am trying to test a click on a routerLink in my component:</p>

<pre><code>  &lt;div class=""side-menu-boards-container""&gt;
    &lt;ul class=""side-menu-boards-list""&gt;
      &lt;li *ngFor=""let board of boards""&gt;
        &lt;a [routerLink]=""['/board', board.id]""&gt;{{board.name}}&lt;/a&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/div&gt;
</code></pre>

<p>using this test: </p>

<pre><code>it('should navigate to correct board url',
    async(inject([Location], (location: Location) =&gt; {
      let nativeElement = fixture.nativeElement;
      let link = nativeElement.querySelector('.side-menu-boards-list li a');
      link.click();

      fixture.whenStable().then(() =&gt; {
        expect(location.path()).toEqual('/board/1');
      });    
})));
</code></pre>

<p>but my expect is failing with the following message: <code>Expected '/' to equal '/board/1'</code></p>

<p>Here is my test setup:</p>

<pre><code>import { async, inject, ComponentFixture, TestBed } from '@angular/core/testing';
import { Component, NO_ERRORS_SCHEMA, DebugElement } from '@angular/core';
import { By } from '@angular/platform-browser';
import { Location } from '@angular/common';
import { RouterTestingModule } from '@angular/router/testing';

import { SideMenuComponent } from './side-menu.component';
import { BoardComponent } from '../board/board.component';
import { BoardMenuItem } from './models/board-menu-item';

describe('SideMenuComponent', () =&gt; {
  let component: SideMenuComponent;
  let fixture: ComponentFixture&lt;SideMenuComponent&gt;;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [SideMenuComponent, BoardComponent],
      schemas: [NO_ERRORS_SCHEMA],
      imports: [RouterTestingModule.withRoutes([
        { path: 'board/:id', component: BoardComponent }
      ])]
    })
      .compileComponents();
  });
</code></pre>

<p>I 've already followed the answers from two other SO related questions (<a href=""https://stackoverflow.com/questions/39577920/angular-2-unit-testing-components-with-routerlink"">here</a> and <a href=""https://stackoverflow.com/questions/37056785/testing-routerlink-directive-in-angular-2"">here</a>) but to no avail.</p>

<p>Any ideas on what am i doing wrong?</p>
",https://stackoverflow.com/questions/41793405/unit-testing-routerlink-in-angular2-component,"['angular', 'routerlink']",2596,TRUE,4,1
Unit testing a function containing setTimeout,"<p>I have a function containing setTimeouts. I am trying to do unit testing but on the code coverage report it is always showing that the code inside the setTimeout is not executing.<br><br>Here is the code.</p>

<pre><code>var func = function(str, type) {
  var t1 = setTimeout(function() {
    document.getElementById(""ledtext"").style.color = ""#631313"";
  }, 100);
  var t2 = setTimeout(function() {
    document.getElementById(""ledtext"").style.color = ""#ea0707"";
  }, 300);
  var t3 = setTimeout(function() {
    document.getElementById(""ledtext"").style.color = ""#631313"";
  }, 500);
  var t4 = setTimeout(function() {
    document.getElementById(""ledtext"").style.color = ""#ea0707"";
    localThisObject.startSequence(type);
  }, 700);
}
</code></pre>

<p><a href=""https://i.stack.imgur.com/nLcNx.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/nLcNx.jpg"" alt=""enter image description here""></a></p>

<p>Code Coverage<br><br>
How to do unit testing of the above code using Karma-jasmine?<br>
Here is a list of devDependencies:<br></p>

<pre><code>""devDependencies"": {
    ""jasmine-core"": ""^2.2.0"",
    ""karma"": ""^0.12.31"",
    ""karma-chrome-launcher"": ""^0.1.7"",
    ""karma-coverage"": ""^1.1.1"",
    ""karma-fixture"": ""^0.2.6"",
    ""karma-htmlfile-reporter"": ""^0.3.5"",
    ""karma-jasmine"": ""^0.3.5"",
    ""karma-phantomjs-launcher"": ""^1.0.4""
}
</code></pre>

<p><a href=""https://jsfiddle.net/tj8f8mL2/2/"" rel=""nofollow noreferrer"">jsfiddle</a><br>
P.S.I have checked <a href=""https://stackoverflow.com/questions/10955201/how-to-test-a-function-which-has-a-settimeout-with-jasmine"">this</a> question. It's not solving my problem.</p>
",https://stackoverflow.com/questions/45464391/unit-testing-a-function-containing-settimeout,"['javascript', 'unit-testing', 'karma-jasmine', 'code-coverage', 'settimeout']",900,FALSE,3,0
TriggerEventHandler in unit testing angular 4,"<p>I had an element</p>

<pre><code>&lt;button class=""next-btn"" (mouseup)=""someMethod()""&gt;Next&lt;/button&gt;
</code></pre>

<p>I want to simulate mouseup event in testing and i do this </p>

<pre><code>const nextBtnElem = fixture.debugElement.nativeElement;
const elem = nextBtnElem.getElementsByTagName('button')[1]
elem.triggerEventHandler('mouseup', null);
</code></pre>

<p>it doesn't work, but if i change it like this </p>

<pre><code>const nextBtnElem = fixture.debugElement.query(By.css('.next-btn');
nextBtnElem.triggerEventHandler('mouseup', null);
</code></pre>

<p>Now its working. I can't understand why first optional doesn't work?</p>
",https://stackoverflow.com/questions/47753863/triggereventhandler-in-unit-testing-angular-4,"['angular', 'unit-testing', 'jasmine']",18907,TRUE,3,1
Unit testing Placeholder defaultValue in @RequestParam,"<p>I'm trying to test my controller that has a handler with a RequestParam configured with a default value pointed to a placeholder:</p>

<pre><code>@Controller     
public class AgeController {
    @GetMapping(""/age"")
    public String home(@RequestParam(name=""current"", defaultValue=""${default.age}"") Integer age) {
        return ""age""+age;
    }
}
</code></pre>

<p>This works fine when I'm testing through my browser but when I use the following test case, it throws an exception:</p>

<p>Test Case:</p>

<pre><code>public class AgeControllerTest {
    AgeController controller
    MockMvc mockMvc;

    @Before 
    public void setUp() {
        ageController = new AgeController();
        mockMvc = MockMvcBuilders.standaloneSetup(controller).addPlaceholderValue(""default.age"", ""10"").build();
    }

    @Test
    public void test() {
        mockMvc.perform(get(""/age"")).andExpect(status().isOk());
    }

}
</code></pre>

<p>Exception:</p>

<pre><code>Caused by: java.lang.NumberFormatException: For input string: ""${default.age}""
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.valueOf(Unknown Source)
    at org.springframework.util.NumberUtils.parseNumber(NumberUtils.java:208)
    at org.springframework.beans.propertyeditors.CustomNumberEditor.setAsText(CustomNumberEditor.java:113)
    at org.springframework.beans.TypeConverterDelegate.doConvertTextValue(TypeConverterDelegate.java:468)
    at org.springframework.beans.TypeConverterDelegate.doConvertValue(TypeConverterDelegate.java:441)
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:199)
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:108)
    at org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:64)
    at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:47)
    at org.springframework.validation.DataBinder.convertIfNecessary(DataBinder.java:713)
    at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:120)
</code></pre>
",https://stackoverflow.com/questions/46540579/unit-testing-placeholder-defaultvalue-in-requestparam,"['unit-testing', 'spring-mvc', 'mocking', 'mockmvc']",980,FALSE,3,1
Unit testing of class using File.OpenRead(),"<p>I would like to test a class that is using the method <code>File.OpenRead()</code> to obtain the content of a file. After reading the content of the file then it processes them. I have create an interface and a class that wraps the static <code>OpenRead()</code> method. But I encounter the problem that <code>OpenRead()</code> returns a <code>FileStream</code> and I have no idea how to ""mock"" the file stream.</p>

<p>Currently, I am creating a file just to create a <code>FileStream</code>... Of course, the tests are regularly failing with a <code>IOException</code> because the file is still in use...</p>

<p>Stripped Example:
Class:</p>

<pre><code>class FileProcessor
{
  public FileProcessor(IFileWrap fileWrap) // fileWrap only redirects the calls to the static methods of File class
  { ... }

  public void Process(string file)
  {
    var content = fileWrap.ReadAllLines(file);

    // process content
  }
}
</code></pre>

<p>And the test:</p>

<pre><code>[TestClass]
public class FileProcessor_Test
{
  [TestMethod]
  Process_FileNotReadable_Exception()
  {
    File.WriteAllText(testFile, ""something"");
    var fileWrapMock = new Mock&lt;IFileWrap&gt;();
    FileProcessor dut = new FileProcessor(fileWrapMock.Object);
    var actualException = AssertException.Throws&lt;Exception&gt;(() =&gt; dut.Process(testFile));
  }
}
</code></pre>

<p>I would like to avoid creating an abstraction of <code>FileStream</code>, too.</p>

<p>I was hoping that I could create a <code>MemoryStream</code> and somehow use this as the input, but this would require to change the file wrapper and deviate from the actual <code>File</code> class.</p>

<p>Any input is appreciated :)</p>

<p>Edit:
The processing includes computing a MD5 checksum by calling <code>ComputeHash()</code> from the the class <code>MD5</code>.</p>
",https://stackoverflow.com/questions/47158223/unit-testing-of-class-using-file-openread,"['c#', 'unit-testing', 'moq']",2218,TRUE,3,3
Unit Testing ValueTuple with Microsoft Fakes,"<p>I am trying to use ValueTuples (current NuGet package ), and while most things I need it for have been seamless an issue has come up when trying to Unit Test certain scenarios related to inheritance.  I have made a simple Interface/Implementation test that anyone can repeat which also fails for virtual/override examples.  </p>

<p>First create a simple console project and a simple unit test and link the two.  Then create a Fakes (Microsoft.QualityToole.Testing.Fakes) object for the main project.  Create the following classes.</p>

<pre><code>public interface IModelClass
{
    (string val1, int val2) Run();
}

public class ModelClass : IModelClass
{
    public (string val1, int val2) Run()
    {
        throw new NotImplementedException();
    }
}
</code></pre>

<p>This can be proven without the need for implementing the interface as it is the interface itself that fails to <strong>compile</strong> when building the fakes.</p>

<p>Building the solution yields this error:</p>

<ul>
<li><strong>Severity</strong>: Error  </li>
<li><strong>Code</strong>: CS8141 </li>
<li><strong>Description</strong>: The tuple element names in the signature of method 'StubIModelClass.IModelClass.Run()' must match the tuple element names of interface method 'IModelClass.Run()' (including on the return type). </li>
</ul>

<p>The error stems from the f.cs file in the fakes build directory as it implements the Run() method stub as:</p>

<pre><code>svt::System.ValueTuple&lt;string, int&gt; vt::ValueTuple.IModelClass.Run()
</code></pre>

<p>Where the return signature does not match that of the named ValueTuple on the interface.  If we remove the naming and just have (string, int) everywhere it all builds, but you are then limited with simple Tuples and Item1, Item2, ...  This seems to defeat the purpose of ValueTuple.  </p>

<p>After much searching I end up here, asking if anyone has been able to get inheritance with ValueTuple working on UnitTests and if not, what solution have you resorted to other than </p>

<ol>
<li>Removing the unit tests</li>
<li>Converting the TupleValue to a class</li>
<li>Using simple Tuples</li>
</ol>

<p>I would like to avoid these if possible.</p>
",https://stackoverflow.com/questions/43369733/unit-testing-valuetuple-with-microsoft-fakes,"['c#', 'unit-testing', 'inheritance', 'microsoft-fakes', 'valuetuple']",536,FALSE,3,0
Angular unit Testing : TypeError: Cannot read property &#39;root&#39; of undefined,"<p>I'm working on unit testing under my Angular app.</p>

<p>My version of Angular is 4.0.0.</p>

<p>My component look like this:</p>

<p><code>component.ts</code>: </p>

<pre><code>import { GdfaClientService } from '../../../service/gdfa-client.service';
import { SharedclientService } from '../../../service/sharedclient.service';
import { Client } from '../../model/client';
import { RouteNavigator } from '../../util/route-navigator';
import { Component, OnInit } from '@angular/core';
import {MonitoringService} from '../../../service/monitoring.service';
@Component({
  selector: 'app-queue-again',
  templateUrl: './queue-again.component.html',
  styleUrls: ['./queue-again.component.css'],
})
export class QueueAgainComponent implements OnInit {

  //-- variables --//
  showError = false;
  queueChoices = [];
  selectedQueue;
  selectedReason;
  requestInProgress = false;
  client: Client;
  errorMessage: string;
  queues: any;
  bankNotAllowed: boolean = false;

  constructor(private sharedclientService: SharedclientService, private gdfaClientService: GdfaClientService
    , private router: RouteNavigator, private monitoringService: MonitoringService) { }

  ngOnInit() {
    this.client = this.sharedclientService.getShared360Client();
    this.getQueues();
    this.bankNotAllowed = this.sharedclientService.bankNotAllowed;
  }


  goToPrevious() {
    this.router.goToHomeAccordingToProfile();
  }

  queueAgain() {
    let currentNd = """";
    let currentUniverse = """";
    let currentCuid = """";
    if (!this.selectedReason) {
      return;
    }
    this.requestInProgress = true;

    let reg = {
      registrationId: this.client.registration.gdfaId,
      gdfaQueueId: this.selectedQueue.id,
      gdfaReasonId: this.selectedReason.id,
      firstProfile: (this.client.firstProfile ? true : false)
    };

    this.gdfaClientService.queueAgain(reg).then(any =&gt; {
        currentCuid = this.client.clientIdentity.customerId;

        if (this.client.fromAdvSearch == undefined || this.client.fromAdvSearch == false) {

      currentNd = this.client.nd;
      if (currentNd != undefined &amp;&amp; currentNd != """") {
        if (currentNd == ""0000000000"") {
          currentNd = """";
          currentUniverse = """";
        }
        if (currentNd.substring(0, 2) == ""06"" || currentNd.substring(0, 2) == ""07"") {
          currentUniverse = ""Mobile"";
        } else {
          currentUniverse = ""Fixe"";
        }
      }
        }
      this.trackReinsertClient(currentCuid, currentNd, currentUniverse);
      this.requestInProgress = false;
      this.showError = false;
      this.sharedclientService.setShared360Client(new Client());
      this.goToPrevious();
    })
      .catch(error =&gt; {
        this.requestInProgress = false;
        this.showError = true;
        switch (error.status) {
          case 403:
            this.errorMessage = ""Erreur lors de la réinjection du client : utilisateur inconnu"";
            console.log(this.errorMessage);
            break;
          case 500:
            this.errorMessage = ""Réinscription impossible"";
            console.log(this.errorMessage);
            break;
          default:
            this.errorMessage = ""Erreur lors de la réinjection du client"";
            console.log(this.errorMessage);
        }
      });
  };


  trackReinsertClient(cuid, nd, universe) {
    let uri = ""/api/gdfa/client/registration/reinsert"";
    let httpMethod = ""PUT"";
    let name = ""réinjection d'un client dans la file d'attente"";
    console.log('trackReinsertClient &lt;' + cuid + '&gt;');
    this.monitoringService.trackingAction(name, uri, httpMethod, null, cuid, nd, universe);

  }

  selectQueue(queue) {
    this.selectedQueue = queue;
    this.selectedReason = false;
  };

  isSelectedQueue(queue) {
    return this.selectedQueue.shortName == queue.shortName;
  }

  getQueues() {
    let queueList = this.client.registration.queueAgainChoices;
    // Search for residentiel queue and put it as selectedQueue
    let indexSAVSAUMobile = -1;
    let indexSAVSAUInternet = -1;
    for (let queue of queueList) {
      if (queue.shortName == 'RES')
        this.selectedQueue = queue;
    }

    this.queues = queueList;
    return queueList;
  }

  selectReason(reason) {
    this.selectedReason = reason;

  }


  isSelectedReason(reason) {
    if (this.selectedReason) {
      return this.selectedReason.id == reason.id;
    }
    return null
  }

  getReasons(queue) {
    let reasonList = this.selectedQueue.reasons;
    return reasonList;
  }
}
</code></pre>

<p><code>component.html</code>:</p>

<pre><code>&lt;div&gt;
    &lt;div [hidden]=""!requestInProgress"" id=""div-spinner""&gt;
        &lt;img src=""/assets/images/indicateur-attente-grand.gif""
            class=""spinner-loader"" /&gt;
    &lt;/div&gt;
    &lt;div class=""row""&gt;
        &lt;!-- fermeture de la recherche avancée --&gt;
        &lt;div class=""col-xs-1 pull-right closeCross""&gt;
            &lt;img id=""ngClick_goToPreviousFromQueueAgain""
                src=""/assets/images/asset_icon_close_popup_gray.png""
                class=""pull-right mousePointer"" (click)=""goToPrevious()"" /&gt;
        &lt;/div&gt;
    &lt;/div&gt;
    &lt;div class=""row""&gt;
        &lt;div class=""col-xs-10 col-xs-offset-1 error-message""
            *ngIf=""showError""&gt;{{errorMessage}}&lt;/div&gt;
        &lt;div
            class=""col-xs-10 col-xs-offset-1 col-sm-3 col-sm-offset-0 register-bloc""&gt;
            &lt;div class=""titre_bloc""&gt;File d'attente&lt;/div&gt;
            &lt;div id=""files-bloc""&gt;
                &lt;div id=""ngClick_selectQueueAgain"" class=""file-cell ""
                    *ngFor=""let queue of queues | orderBy : 'id'""       
                    [ngClass]=""{ 'selected-shop-queue': isSelectedQueue(queue)}""
                    (click)='selectQueue(queue)'&gt;
                    &lt;div class=""vertical-center horizontal-middle file_nom""&gt;
                        &lt;div&gt;{{queue.name}}&lt;/div&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/div&gt;
        &lt;div
            class=""col-xs-10 col-xs-offset-1 col-sm-6 col-sm-offset-0 register-bloc""&gt;
            &lt;div class=""titre_bloc""&gt;Motifs&lt;/div&gt;
            &lt;div id=""motifs-bloc""&gt;
                &lt;div id=""ngClick_queueAgain"" class=""motif-cell""
                    [ngClass]=""{'motif-cell-pro': selectedQueue?.reasons?.length == 4, 'motif-cell-selected':isSelectedReason(reason),
                    'hide-class': (bankNotAllowed &amp;&amp; reason.id === 12)}"" [hidden]=""bankNotAllowed &amp;&amp; reason.id === 12""
                    *ngFor=""let reason of selectedQueue?.reasons | orderBy : 'motifOrder'""
                    (click)='selectReason(reason)'&gt;
                    &lt;div *ngIf=""!bankNotAllowed || reason.id !== 12"" class=""mIcon""&gt;
                            &lt;img
                                src=""/bower_components/nomadis/images-no-cache/{{reason?.imageName}}""
                                [ngClass]=""{'motif-unique': client?.registration?.queue?.reasons?.length == 1}"" /&gt;
                            &lt;span&gt;{{reason.name}}&lt;/span&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
            &lt;div class=""col-sm-offset-4 col-sm-4  btn-validate-reinsert""&gt;
                &lt;input id=""validateReinsertBtn"" type=""submit"" value=""Valider""
                    [ngClass]=""{'queueAgain-disabled': !selectedReason}""
                    class=""btn btn-lg btn-primary btn-block""
                    (click)='queueAgain()' /&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;

&lt;/div&gt;
&lt;router-outlet&gt;&lt;/router-outlet&gt;
</code></pre>

<p>As you can see I'm not using <code>routeLink</code>.</p>

<p>Within my test file config I've done this: </p>

<p><code>component.spec.ts</code>:</p>

<pre><code>import {async, ComponentFixture, TestBed, tick, fakeAsync} from '@angular/core/testing';
import {QueueAgainComponent} from './queue-again.component';
import {OrderByPipe} from 'app/home/pipe/order-by.pipe';
import {SharedclientService} from 'app/service/sharedclient.service';
import {GdfaClientService} from 'app/service/gdfa-client.service';
import {AuthHttp, AuthConfig, AUTH_PROVIDERS, provideAuth} from 'angular2-jwt';
import {HttpModule} from '@angular/http';
import {EnvVarsService} from 'app/service/env-vars.service';
import {RouteNavigator} from 'app/home/util/route-navigator';
import {Router} from '@angular/router';
import {Observable} from 'rxjs/Observable';
import * as QueueAgainMocks from 'TU/mocks/queue-again-mocks';
import {RouterTestingModule} from '@angular/router/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';

describe('QueueAgainComponent', () =&gt; {
    let comp: QueueAgainComponent;
    let fixture: ComponentFixture&lt;QueueAgainComponent&gt;;
    let sharedclientService: SharedclientService;
    let gdfaClientService: GdfaClientService;
    let getShared360Client: jasmine.Spy;
    let queueAgain: jasmine.Spy;
    let client = QueueAgainMocks.CUSTOMER_MOCK;
    let selectedQueue = QueueAgainMocks.SELECTED_QUEUE_MOCK;
    let selectedReason = QueueAgainMocks.SELECTED_REASON;
    let mockRouter = {
        navigate: jasmine.createSpy('navigate')
    };

    // TestBed preparation (async)
    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            imports: [HttpModule , RouterTestingModule],
            declarations: [QueueAgainComponent, OrderByPipe],
            providers: [SharedclientService, GdfaClientService, AuthHttp, EnvVarsService, RouteNavigator,
                {provide: Router, useValue: mockRouter},
                provideAuth({
                    headerName: 'Authorization',
                    headerPrefix: 'bearer',
                    tokenName: 'token',
                    tokenGetter: (() =&gt; localStorage.getItem('id_token')),
                    globalHeaders: [{'Content-Type': 'application/json'}],
                    noJwtError: true
                })
            ],
            schemas: [ NO_ERRORS_SCHEMA ]
        }).compileComponents();
    }));

    // Fixture &amp; Spies declarations
    beforeEach(() =&gt; {
        // Creation of the component fixture
        fixture = TestBed.createComponent(QueueAgainComponent);
        comp = fixture.componentInstance;
        fixture.detectChanges();  // this line will call components ngOnInit() method


        // Getting Services instances from fixture
        sharedclientService = fixture.debugElement.injector.get(SharedclientService);
        gdfaClientService = fixture.debugElement.injector.get(GdfaClientService);

        // Call of fake methods of `sharedclientService` from the AlertServiceSpy
        getShared360Client = spyOn(sharedclientService, 'getShared360Client').and.returnValue(client);
        // Call of fake methods of `gdfaClientService` from the AlertServiceSpy
        queueAgain = spyOn(gdfaClientService, 'queueAgain').and.callFake((reg) =&gt; {
            return Observable.of('ok');
        });

        comp.ngOnInit();
    });
    // Test case of component compilation
    it('should be defined', () =&gt; {
        expect(comp).toBeDefined();
    });
});
</code></pre>

<p>Although I've imported <code>NO_ERRORS_SCHEMA</code> and I've used a <code>mockRouter</code>, it seems that something is still going wrong with routing with this error:</p>

<pre><code>TypeError: Cannot read property 'root' of undefined

      at rootRoute (node_modules/@angular/router/bundles/router.umd.js:6110:30)
      at _callFactory (packages/core/src/view/ng_module.ts:185:1)
      at _createProviderInstance$1 (packages/core/src/view/ng_module.ts:124:1)
      at resolveNgModuleDep (node_modules/@angular/core/bundles/core.umd.js:9517:17)
      at _createClass (packages/core/src/view/ng_module.ts:158:1)
      at _createProviderInstance$1 (packages/core/src/view/ng_module.ts:121:1)
      at resolveNgModuleDep (node_modules/@angular/core/bundles/core.umd.js:9517:17)
      at NgModuleRef_.Object.&lt;anonymous&gt;.NgModuleRef_.get (node_modules/@angular/core/bundles/core.umd.js:10609:16)
      at resolveDep (node_modules/@angular/core/bundles/core.umd.js:11112:45)
      at createClass (node_modules/@angular/core/bundles/core.umd.js:10976:32)
      at createDirectiveInstance (node_modules/@angular/core/bundles/core.umd.js:10796:37)
      at createViewNodes (packages/core/src/view/view.ts:354:1)
      at createRootView (node_modules/@angular/core/bundles/core.umd.js:12139:5)
      at callWithDebugContext (packages/core/src/view/services.ts:815:1)
      at Object.debugCreateRootView [as createRootView] (node_modules/@angular/core/bundles/core.umd.js:12842:12)
      at ComponentFactory_.Object.&lt;anonymous&gt;.ComponentFactory_.create (node_modules/@angular/core/bundles/core.umd.js:9904:46)
      at initComponent (node_modules/@angular/core/bundles/core-testing.umd.js:924:49)
      at ZoneDelegate.Object.&lt;anonymous&gt;.ZoneDelegate.invoke (node_modules/zone.js/dist/zone-node.js:392:26)
      at ProxyZoneSpec.Object.&lt;anonymous&gt;.ProxyZoneSpec.onInvoke (node_modules/zone.js/dist/proxy.js:79:39)
      at ZoneDelegate.Object.&lt;anonymous&gt;.ZoneDelegate.invoke (node_modules/zone.js/dist/zone-node.js:391:32)
      at Object.onInvoke (node_modules/@angular/core/bundles/core.umd.js:3922:33)
      at ZoneDelegate.Object.&lt;anonymous&gt;.ZoneDelegate.invoke (node_modules/zone.js/dist/zone-node.js:391:32)
      at Zone.Object.&lt;anonymous&gt;.Zone.run (node_modules/zone.js/dist/zone-node.js:142:43)
      at NgZone.Object.&lt;anonymous&gt;.NgZone.run (node_modules/@angular/core/bundles/core.umd.js:3853:69)
      at TestBed.Object.&lt;anonymous&gt;.TestBed.createComponent (packages/core/testing/src/test_bed.ts:471:1)
      at Function.Object.&lt;anonymous&gt;.TestBed.createComponent (node_modules/@angular/core/bundles/core-testing.umd.js:691:29)
      at src/app/home/advisor/queue-again/queue-again.component.spec.ts:53:27
</code></pre>

<p>From the last line of the log that points on the 53:27 line which is exactly:</p>

<pre><code>fixture = TestBed.createComponent(QueueAgainComponent);
</code></pre>

<p>So it seems that it's not able to create the <em>fixture</em>.</p>

<p>Any ideas?</p>
",https://stackoverflow.com/questions/47140560/angular-unit-testing-typeerror-cannot-read-property-root-of-undefined,"['angular', 'unit-testing', 'typescript', 'jasmine', 'testbed']",25621,TRUE,31,2
Auto injecting dependencies for unit testing,"<p>Coming from Java background, I am working on php codebase and want to add unit tests for my code.</p>

<p>I have a service class which has a DAO class as below :</p>

<pre><code>class ServiceClass {

  private $daoClass;

  public function methodToTest(){}
}
</code></pre>

<p>I don't provide a constructor nor do I add a setter method for the <code>daoClass</code> property. This is because it will get injected using PHP-DI IoC container.</p>

<p>For unit testing, I am using <code>phpunit</code>, so I am mocking the <code>daoClass</code> object and using reflection to inject that property directly (as there is no constructor or setter for that property).</p>

<p>In java, we can easily do this without the reflection stuff using <code>@InjectMocks</code> annotation or <code>MockitoAnnotations.initMocks</code> method.</p>

<p>I am not able to find a similar way to do this in <code>phpunit</code>.</p>

<p>Also, a different but related question, is there any way in my test I can create a private property and annotate it with some tag, and it automatically gets converted to a mock object instance? Like how mockito in Java does it <code>@Mock</code> annotation.</p>
",https://stackoverflow.com/questions/45495208/auto-injecting-dependencies-for-unit-testing,"['java', 'php', 'unit-testing', 'mocking', 'phpunit']",256,FALSE,3,1
Unit Testing on U-SQL Procedures,"<p>I am trying to figure out how to write and perform U-SQL Unit Testing on U-SQL Procedures. Do you have an example or template?</p>
",https://stackoverflow.com/questions/43328635/unit-testing-on-u-sql-procedures,"['unit-testing', 'azure-data-lake', 'u-sql']",529,TRUE,2,1
MVC controller unit testing - entity framework,"<p>I would like to test GetTaskToDo() controller method(i.e check if there is any return result) that take some data from db.</p>

<p>In Unit Test project I added app.config file with connection strings, but after invoking GetTaskToDo() method i get error:</p>

<blockquote>
  <p>System.Data.Entity.Core.EntityException : The underlying provider
  failed on Open.   ----> System.Data.SqlClient.SqlException : Cannot
  attach the file
  'aspnet-test-20170222081336.mdf'
  as database 'aspnet-test-20170222081336'.</p>
</blockquote>

<p><strong>MVC Controller:</strong></p>

<pre><code>public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public JsonResult GetTasksToDo()
        {
            var tasks = new List&lt;Tasks&gt;();
            using (Entities dc = new Entities())
            {
                tasks = dc.Tasks.Where(a =&gt; a.State == ""ToDo"").ToList();
                tasks = tasks.OrderBy(a =&gt; a.Order).ToList();
            }
            return new JsonResult { Data = tasks, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
</code></pre>

<p><strong>Simple Unit test:</strong></p>

<pre><code>        [Test]
        public void Test_GetTasksToDo()
        {
            var sut = new HomeController();

            var test = sut.GetTasksToDo();
        }
</code></pre>

<p>How should I test this? Should I somehow mock entity framework which is used by that method? I'm quite new in this, I would be very grateful for every hint.</p>
",https://stackoverflow.com/questions/42536191/mvc-controller-unit-testing-entity-framework,"['asp.net-mvc', 'entity-framework', 'unit-testing', 'asp.net-mvc-5', 'mocking']",474,FALSE,2,0
Angular - Unit Testing Modal Factory Call,"<p>I'm trying to verify that a factory function is called from within a modal function, if passed a valid file object. The factory is injected into the modal controller and when the test is run the factory is undefined. What is the proper way to test that a factory function is called from within a modal?</p>

<p><strong><em>modal controller</em></strong></p>

<pre><code>  angular.module('vicModule')
  .controller('vicModalController', vicModalController);

  vicModalController.$inject = [
    '$uibModalInstance',
    '$uibModal',
    'utilFunctionsFactory'
  ]

  function vicModalController($uibModalInstance, $uibModal, utilFunctionsFactory) {
    mvm.uploadVICs = uploadVICs;

    function uploadVICs(file, error) {
      if (file == null) {
        data.errorMessage = 'file is not found or not supported';
        return;
      }
      if(error.length &gt; 0) {
        $uibModalInstance.close();
        data.errorMessage = 'reading file error';
        return;
      } else {
        var fileData = utilFunctionsFactory.validateCSV(file, error);
      }
    }
  }
</code></pre>

<p><strong><em>modal controller test</em></strong></p>

<pre><code>describe('vicModalController', function() {
  var $controller, vicModalController, vicFactory, utilFunctionsFactory, $q, $scope, $httpBackend, deferred, $uibModalInstance;
  beforeEach(module('fotaAdminPortal'));
  beforeEach(module('vicModule'));
  beforeEach(inject(function(_$controller_, _vicFactory_, _utilFunctionsFactory_, _$q_, _$rootScope_, _$httpBackend_) {
    $controller = _$controller_;
    vicFactory = _vicFactory_;
    utilFunctionsFactory: _utilFunctionsFactory_;
    $q = _$q_;
    $rootScope = _$rootScope_;
    $scope = $rootScope.$new();
    $httpBackend = _$httpBackend_;
    $uibModalInstance = { // Create a mock object using spies
      close: jasmine.createSpy('modalInstance.close'),
      dismiss: jasmine.createSpy('modalInstance.dismiss'),
      result: {
        then: jasmine.createSpy('modalInstance.result.then')
      }
    };
    vicModalController = $controller('vicModalController', {
      vicFactory: vicFactory,
      utilFunctionsFactory: utilFunctionsFactory,
      $uibModalInstance: $uibModalInstance
    });
  }));
  it('should be defined', function() {
    expect(vicModalController).toBeDefined();
  });
  describe('uploadVICS()', function() {
    beforeEach(inject(function(_utilFunctionsFactory_) {
      utilFunctionsFactory = _utilFunctionsFactory_;
      spyOn(utilFunctionsFactory, 'validateCSV').and.callFake(function() {
        return {};
      });
    }));
    it('should call validateCSV() with valid file', function() {
      vicModalController.uploadVICs({}, []);
      expect(utilFunctionsFactory.validateCSV()).toHaveBeenCalledWith({}, []);
    });
  });
});
</code></pre>

<p><strong><em>edit</em></strong></p>

<p>I had the assignment wrong in the beforeEach:</p>

<p>utilFunctionsFactory: <em>utilFunctionsFactory</em>; //incorrect colon
utilFunctionsFactory = <em>utilFunctionsFactory</em>; // should be assigned</p>
",https://stackoverflow.com/questions/45515700/angular-unit-testing-modal-factory-call,"['angularjs', 'unit-testing', 'karma-jasmine']",133,TRUE,2,1
Unit testing an event in HttpModule,"<p>I have an CustomHttp module in my application to remove the unwanted response headers as below.</p>

<pre><code> public class RemoveServerHeadersModule : IHttpModule
        {
            public void Init(HttpApplication context)
            {
                context.PreSendRequestHeaders += OnPreSendRequestHeaders;
            }

            public void Dispose() { }

            public void OnPreSendRequestHeaders(object sender, EventArgs e)
            {
                HttpContext.Current.Response.Headers.Remove(""X-Powered-By"");
                HttpContext.Current.Response.Headers.Remove(""X-AspNet-Version"");
                HttpContext.Current.Response.Headers.Remove(""X-AspNetMvc-Version"");
                HttpContext.Current.Response.Headers.Remove(""Server"");
            }
        }
</code></pre>

<p>I need to write unit test for this .</p>

<p>Tried few like below but unable to do that , getting error.</p>

<pre><code> HttpRequest httpRequest = new HttpRequest("""", """", """");
 StringWriter stringWriter = new StringWriter();
 HttpResponse httpResponse = new HttpResponse(stringWriter);
 HttpContext httpContextMock = new HttpContext(httpRequest, httpResponse);

 var application = new Mock&lt;HttpApplication&gt;();
 application.Setup(ct =&gt; ct.Context).Returns(httpContextMock);

 var module = new RemoveServerHeadersModule();
 HttpApplication httpApplication = new HttpApplication();
 module.Init(httpApplication);
 module.OnPreSendRequestHeaders(httpApplication, EventArgs.Empty);
</code></pre>

<p>Getting error when trying to set the Context in HttpApplication.
Please could you help me out</p>
",https://stackoverflow.com/questions/46733045/unit-testing-an-event-in-httpmodule,"['asp.net-mvc', 'unit-testing', 'c#-4.0']",1238,TRUE,2,1
Unit Testing URL Parameters in Swift,"<p>I am trying to unit a <code>URL</code> in Swift by using TDD. I want to ensure that the <code>URL</code> is equal to the expected <code>URL</code>. I am using a <code>Router</code> <code>enum</code>, using <code>Alamofire</code>, to create my <code>URL</code>s. So, as property of the <code>Router</code> <code>enum</code>, I have a <code>Dictionary&lt;String,String&gt;?</code> property because I may not need parameters for other <code>URL</code>s. However, I do need parameters for the authentication <code>URL</code>.</p>

<p>The <code>parameters</code> <code>Dictionary&lt;String,String&gt;?</code> follows:</p>

<pre class=""lang-swift prettyprint-override""><code>internal enum Router: URLConvertible {

    internal static let baseURLString = ""https://xxx.xxxxxx.xxx""

    case authentication(clientID: String)

}

extension Router {

    var pathString: String {
        switch self {
            case .authentication: return ""xxxxx/xxxxx/xxxxxxxxx""
        }
    }

    var method: HTTPMethod {
        switch self {
            case .authentication: return .get
        }
    }

    var parameters: Dictionary&lt;String, String&gt;? {
        switch self {
            case .authentication(let clientID): return [""xxxxx"": ""xxxx"", ""client_id"": clientID]
        }
    }

    func asURL() throws -&gt; URL {
        switch self {
            case .authentication:
               return URL(string: ""https://xxx.xxxxxx.xxx/xxxxx/xxxxx/xxxxxxxxx?xxxxx=xxxx&amp;client_id=xxxxxxxxxx"")!
        }
    }

}
</code></pre>

<p>I have been able to successfully code everything the TDD way up to this point. Where I am stuck is testing the returned <code>URL</code>. Since <code>parameters</code> is of type <code>Dictionary&lt;String,String&gt;?</code>, I want to iterate <code>parameters</code> by using the following logic:</p>

<pre class=""lang-swift prettyprint-override""><code>var parametersStringArray = Array&lt;Dictionary&lt;String,String&gt;&gt;()

for (key, value) in parameters {
    // Create a parameter string from each set
    // Something like the following:
    let parameterString = String(describing: \(key)=\(value))
    parametersStringArray.append(parameterString)
}

let parametersString = parametersStringArray.joined(separator: ""&amp;"")
let fullURLString = baseURLString + ""?\(parametersString)""
return URL(string: fullURLString)!
</code></pre>

<p>By creating the parameters like this, when I test the expected <code>URL</code> against the returned <code>URL</code> from the <code>Router</code> <code>enum</code> in <code>asURL() throws -&gt; URL</code>, it could fail part of the time since the parameters are added to the <code>URL</code> string without an expected order. In other words, If my expected URL is <code>https://xxx.xxxxxx.xxx?xxxxx=xxxx&amp;client_id=xxxxxxxxxx</code>, it could either match or fail by returning the parameters in the reverse order, like so: <code>https://xxx.xxxxxx.xxx?client_id=xxxxxxxxxx&amp;xxxxx=xxxx</code>.</p>

<p>Is there a better solution for me testing the <code>URL</code>s to ensure that the correct <code>URL</code> is returned when the parameters can be in any order since they are added to the <code>URL</code>'s string when iterating them?</p>

<p>Should I create two <code>URL</code>s with the parameters both ways and match against either? The reason that I don't see that being appropriate is because the more parameters you have, the more <code>URL</code>s you have to create to test against.</p>

<p>My current tests for testing the <code>URL</code> for authentication follow:</p>

<pre class=""lang-swift prettyprint-override""><code>import XCTest
import Alamofire
@testable import Projects

class AuthenticationURLTests: XCTestCase {

    func test_API_BaseURLString_IsCorrect() {
        let baseURLString = Router.baseURLString
        let expectedBaseURLString = ""https://xxx.xxxxxx.xxx/""
        XCTAssertEqual(baseURLString, expectedBaseURLString, ""Base URL does not match expected base URL. Expected base URLs to match."")
    }

    func test_API_OAuthPath_IsCorrect() {
        let pathString = Router.authentication(clientID: ""xxxxxxxxxx"").pathString
        let expectedPathString = ""xxxxx/xxxxx/xxxxxxxxx""
        XCTAssertEqual(pathString, expectedPathString, ""Path string does not match expected path string. Expected path strings to match."")
    }

    func test_API_OAuthMethod_IsCorrect() {
        let method = Router.authentication(clientID: ""xxxxxxxxxx"").method
        let expectedMethod = HTTPMethod.get
        XCTAssertEqual(method, expectedMethod, ""HTTP methods do not match. Expected HTTP methods to match."")
    }

    func test_API_OAuth_ParametersContainsKeyForXXXXX() {
        let scopeString = Router.authentication(clientID: ""xxxxxxxxxx"").parameters?[""xxxxx""]
        let expectedScopeString = ""xxxx""
        XCTAssertEqual(scopeString, expectedScopeString, ""Scope strings do not match. Expected scope strings to match."")
    }

    func test_API_OAuth_ParametersContainsKeyForClientID() {
        let clientID = Router.authentication(clientID: ""12345abcde"").parameters?[""client_id""]
        let expectedClientID_Fake = ""12345abcde""
        XCTAssertEqual(clientID, expectedClientID_Fake, ""Client IDs do not match. Expected client IDs to match."")
    }

    func test_API_OAuth_URLIsCorrect() {
        do {
            let url = try Router.authentication(clientID: ""12345abcde"").asURL()
            // Here, I want to ensure that the `URL`s match:
            let expectedURL = URL(string: https://xxx.xxxxxx.xxx?xxxxx=xxxx&amp;client_id=xxxxxxxxxx)!
        } catch { XCTFail(""Could not create URL for OAuth"") }
    }

}
</code></pre>

<p>Sorry for all of the <code>x</code>s within the provided code. I wanted to ensure that I didn't provide any information regarding my client's application.</p>
",https://stackoverflow.com/questions/41539039/unit-testing-url-parameters-in-swift,"['swift', 'url', 'tdd']",2172,TRUE,2,1
Using ref for unit testing callbacks,"<p>Suppose I have a ReactJS class something like this: </p>

<pre><code>class MyComponent extends Component {
  onTouch = () =&gt; {
    if(this.calendar1) {
      this.calendar1.getValue();
      this.calendar1.setValue('something');
      this.setState({key: 'something'});
    }
  }

  render() {
    return (&lt;div&gt;
              &lt;AnotherComponent onTouch={this.onTouch} ref={node =&gt; this.calendar1 = node}/&gt;  
            &lt;/div&gt;);
  }
}
</code></pre>

<p>How do I write a testcase to unit test the functionality of the callback?
I read through this page 
<a href=""https://reactjs.org/blog/2016/11/16/react-v15.4.0.html#mocking-refs-for-snapshot-testing"" rel=""nofollow noreferrer"">https://reactjs.org/blog/2016/11/16/react-v15.4.0.html#mocking-refs-for-snapshot-testing</a>
But this doesn't work for me as element.type is only html elements.</p>
",https://stackoverflow.com/questions/47455929/using-ref-for-unit-testing-callbacks,"['reactjs', 'jestjs', 'enzyme']",234,FALSE,2,0
Unit Testing a custom Web API AuthorizeAttribute,"<p>I am trying to unit test, with NUnit in C#, a custom Authorize Attribute. In particular that a particular http status code and message have been returned in the case of not being authorized. </p>

<p>My attribute is super simple - looks like this:</p>

<pre><code>public class AuthorizationAttribute : AuthorizeAttribute
{

    public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        if (IsAuthorized(actionContext))
            return;

        HandleUnauthorizedRequest(actionContext);
    }

    protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Forbidden, ""You are not authorized to access this resource"");
    }
}
</code></pre>

<p>So to test this (and currently new in the field of testing) I have cobbled together the following code. In it, i am attaching a generic identity with a username and some role data.</p>

<pre><code>public void Given_UserIsNotInAuthorizedRoles_When_Auhtorizing_ReturnsForbidden()
{

    // Arrange

    IPrincipal principal = new GenericPrincipal(new GenericIdentity(""TestName""), new[] { ""TestRole"" });

    HttpActionContext mockActionContext = new HttpActionContext()
    {
        ControllerContext = new HttpControllerContext()
        {
            Request = new HttpRequestMessage(),
            RequestContext = new HttpRequestContext() { Principal = principal }
        },
        ActionArguments = { { ""SomeArgument"", ""null"" } }
    };

    mockActionContext.ControllerContext.Configuration = new HttpConfiguration();
    mockActionContext.ControllerContext.Configuration.Formatters.Add(new JsonMediaTypeFormatter());

    // Act
    AuthorizationAttribute authAttr = new AuthorizationAttribute();
    authAttr.OnAuthorization(mockActionContext);

    // Assert
    Assert.IsTrue(mockActionContext.Response.StatusCode == System.Net.HttpStatusCode.Forbidden);

}
</code></pre>

<p>The mock controller looks like this:    </p>

<pre><code>[Authorization(Roles = ""AdminRoleOnly"", Users = ""A user"")]
internal class MockController : ApiController { }
</code></pre>

<p>When I'm debugging, i am finding that <code>if (IsAuthorized(actionContext))</code> is returning <code>true</code> - which i don't understand. </p>

<p>Can someone point me in the direction of why my authorize attribute is passing this identity as good?</p>

<p>For what it's worth, this code works in production. I'm back-filling some tests.</p>

<hr>

<p>Somewhat related, are these ones</p>

<p>I've read through the question and answer on a similar question <a href=""https://stackoverflow.com/questions/18701433/asp-net-mvc-unit-testing-custom-authorizeattribute"">ASP.NET MVC unit testing custom AuthorizeAttribute</a> though neither really either work nor relate, especially given they're for MVC controllers and not Api Controllers. </p>

<p>I've also read and tried to implement the code in the answer on this question too <a href=""https://stackoverflow.com/questions/17230081/mocking-httpactioncontext-actionarguments-when-testing-web-api-actionfilter"">Mocking HttpActionContext.ActionArguments when testing Web.Api ActionFilter</a></p>

<hr>

<p>The latter gets me somewhere near in that my authorization attribute is firing in a test and I am able to pass in the required context information.</p>
",https://stackoverflow.com/questions/44395940/unit-testing-a-custom-web-api-authorizeattribute,"['c#', 'unit-testing', 'asp.net-web-api', 'nunit']",7956,TRUE,9,1
Unit testing higher order functions in F#,"<p>Take the following F# example:</p>

<pre><code>let parse mapDate mapLevel mapMessge (groups : string list) = 
    {
        DateTime = 
            mapDate(
                groups.[2] |&gt; Int32.Parse, 
                groups.[0] |&gt; Int32.Parse, 
                groups.[1] |&gt; Int32.Parse)
        Level = mapLevel groups.[3]
        Message = mapMessge  groups.[4]
    }
</code></pre>

<p>I can unit test the map functions independently that's ok,  but how do I unit test that this function calls the functions passed in as arguments correctly?</p>

<p>In C# I would use mocks and verify the calls to them. I recently watched a pluralsight video that talked about how functional languages tend to use stubs instead of mocks. Here I could pass in a function that throws if it doesn't get the expected arguments but I'm not really sold on this approach.</p>

<p>I was just wondering if there were any patterns in functional programming in general for unit testing higher-order functions like this?</p>
",https://stackoverflow.com/questions/42892313/unit-testing-higher-order-functions-in-f,"['unit-testing', 'f#', 'functional-programming', 'higher-order-functions']",404,TRUE,9,2
Unit testing logic inside promise callback,"<p>I have an ES6 / Aurelia app that I am using jasmine to test.  The method I am trying to test looks something like this:</p>

<pre><code>update() {
    let vm = this;
    vm.getData()
        .then((response) =&gt; {
            vm.processData(response);
        });
}
</code></pre>

<p>Where <code>this.getData</code> is a function that returns a promise.</p>

<p>My spec file looks something like this:</p>

<pre><code>describe('my service update function', () =&gt; {
    it('it will call the other functions', () =&gt; { 
        myService = new MyService();
        spyOn(myService, 'getData').and.callFake(function() {
            return new Promise((resolve) =&gt; { resolve(); });
        });
        spyOn(myService, 'processData').and.callFake(function() { return; });
        myService.update();

        // this one passes
        expect(myService.getData).toHaveBeenCalled();

        // this one fails
        expect(myService.processData).toHaveBeenCalled();
    });
});
</code></pre>

<p>I understand why this fails - promises are asynchronous and it hasn't been resolved by the time it hits the expect.   </p>

<p>How can I push the promises to resolve from my test so that  I can test the code inside the call back?</p>

<p>jsfiddle of failed test: <a href=""http://jsfiddle.net/yammerade/2aap5u37/6/"" rel=""nofollow noreferrer"">http://jsfiddle.net/yammerade/2aap5u37/6/</a></p>
",https://stackoverflow.com/questions/42727660/unit-testing-logic-inside-promise-callback,"['javascript', 'jasmine', 'aurelia', 'es6-promise']",1794,TRUE,2,2
mocking API calls in unit testing,"<p>I am fairly new to Python and having a hard time wrapping my head around how to mock patch API calls in unit testing.
FYI, I am using Python 2.7 and using nosetest for my unit testing needs.</p>

<p>I have the following module (myRedis.py) which I want to unit test:</p>

<pre><code>import logging
import redis

redispool = None

class myRedis(object):

def __init__(self, redisHost, redisPort, redisDBNum):
    if not redisPort.isdigit():
        raise TypeError('Exception: Expected int for redisPort')

    if not redisDBNum.isdigit():
        raise TypeError('Exception: Expected int for redisDBNum')

    self._redis_instance = None

    self._redishost = redisHost
    self._redisport = redisPort
    self._redisdb = redisDBNum

    global redispool
    redispool = redis.ConnectionPool(host=self._redishost,
                                          port=self._redisport,
                                          db=self._redisdb)

    def redis_connect(self):
         LOGGER.info('Connecting Redis client to %s:%s:%s', self._redishost,
         self._redisport, self._redisdb)
         self._redis_instance = redis.StrictRedis(connection_pool=redispool)

    def write_redis(self, key, value):
         retval = self._redis_instance.set(key, value)
         LOGGER.info('Writing data to redis (%s, %s). Retval=%s', key, value, retval)
         return retval

    def read_redis(self, key):
         retval = self._redis_instance.get(key) 
         LOGGER.info('Reading data from redis: key=%s. Retval=%s', key, retval)
         return retval
</code></pre>

<p>As far as unit testing goes, I have the following so far. </p>

<pre><code>from nose.tools import *
import mock
from myRedis import myRedis

def setup():
    pass
def teardown():
    pass

@mock.patch('redis.StrictRedis')
def test_mock_redis_StrictRedis(mock_conn_pool):
    mock_conn_pool.return_value = True
    assert(True)

def test_myRedis():

    assert_raises(TypeError, myRedis, 
              'test', '1234', 'a11')

    assert_raises(TypeError, myRedis, 
              'test', 'a1234', '11')

    myRedisObj = myRedis('localhost', '8888', '11')
    assert_equal(myRedisObj._redishost, 'localhost')
    assert_equal(myRedisObj._redisport, '8888')
    assert_equal(myRedisObj._redisdb, '11')

    myRedisObj.redis_connect()
    #oclRedis.read_redis('test')
    #oclRedis.write_redis('test', 'test')
</code></pre>

<p>I am able to patch the redis.StrictRedis() call without any problems. But how do I patch the redis' get() and set() calls since they are invoked on an object (_redis_instance in myRedis.py). I tried a few different versions of @mock.patch.object, but that didn't work for me. Looking for some guidance.</p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/42819073/mocking-api-calls-in-unit-testing,"['python', 'unit-testing', 'mocking']",948,TRUE,2,1
ASP.NET Unit testing doesn&#39;t map routes,"<p>I have a web API project that I want to test with unit tests.</p>

<p>In the test class I create a <code>HttpClient</code> that is supposed to redirect the HTTP calls directly to my controllers:</p>

<pre><code>public static HttpClient GetInMemoryServerClient(HttpConfiguration serverConfig)
{
    var config = serverConfig ?? new HttpConfiguration();
    MyService.WebApiConfig.Register(config, isTest: true);
    var server = new HttpServer();
    server.Configuration.Services.Replace(typeof(IHttpActionInvoker), server.Configuration.Services.GetActionInvoker());
    return new HttpClient(server) { BaseAddress = new Uri(""http://fakehost:9999/"") };
}
</code></pre>

<p>In the service project I have this class that calls <code>config.MapHttpAttributeRoutes()</code>, which works in prod but not when called by the test:</p>

<pre><code>public class WebApiConfig{
    //...
    public static void Register(HttpConfiguration config) // this is called in Global.asax.cs
    {
        Register(config, false);
    }

    public static Register(HttpConfiguration config, bool isTest){
        //... various config and dependency injection setup here
        config.MapHttpAttributeRoutes();
    }
}
</code></pre>

<p>My controllers use attribute routing:</p>

<pre><code>[RoutePrefix(""api/groups/{groupId}/sets/{setId:minlength(1)}/items"")]
public class ItemsController : BaseController
{
    [Route(""{itemId:minlength(1)}"")]
    [HttpGet]
    public async Task&lt;API.Item&gt; Get(string groupId, string setId, string itemId)
    {...}
}
</code></pre>

<p>When I use the <code>HttpClient</code> to make a call I get </p>

<blockquote>
  <p>{""Message"":""No HTTP resource was found that matches the request URI
  <code>'http://fakehost:9999/api/groups/abc/sets/xyz/items/item123'</code>.""}</p>
</blockquote>

<p>and inspecting the <code>httpClient</code> with the debugger I see <code>httpClient.handler.Configuration.Routes.Count == 0</code>, so mapping the routing attributes didn't work</p>

<p><strong>Q:</strong> What is the correct way to set up the fake <code>HttpClient</code> so my unit tests can use it to call the controllers?</p>
",https://stackoverflow.com/questions/43503754/asp-net-unit-testing-doesnt-map-routes,"['c#', 'asp.net', 'integration-testing', 'asp.net-web-api-routing', 'attributerouting']",430,TRUE,2,1
Unit testing coroutines on UI thread,"<p>I'm using coroutines to do an asynchronous call on pull to refresh like so:</p>

<pre><code>class DataFragment : Fragment(), SwipeRefreshLayout.OnRefreshListener {

    // other functions here

    override fun onRefresh() {
        loadDataAsync()
    }

    private fun loadDataAsync() = async(UI) {
        swipeRefreshLayout?.isRefreshing = true
        progressLayout?.showContent()

        val data = async(CommonPool) {
            service?.getData() // suspending function
        }.await()

        when {
            data == null -&gt; showError()
            data.isEmpty() -&gt; progressLayout?.showEmpty(null, parentActivity?.getString(R.string.no_data), null)
            else -&gt; {
                dataAdapter?.updateData(data)
                dataAdapter?.notifyDataSetChanged()
                progressLayout?.showContent()
            }
        }

        swipeRefreshLayout?.isRefreshing = false
    }
}
</code></pre>

<p>Everything here works fine when I actually put it on a device. My error, empty, and data states are all handled well and the performance is good. However, I'm also trying to unit test it with Spek. My Spek test looks like this:</p>

<pre><code>@RunWith(JUnitPlatform::class)
class DataFragmentTest : Spek({

    describe(""The DataFragment"") {

        var uut: DataFragment? = null

        beforeEachTest {
            uut = DataFragment()
        }

        // test other functions

        describe(""when onRefresh"") {
            beforeEachTest {
                uut?.swipeRefreshLayout = mock()
                uut?.onRefresh()
            }

            it(""sets swipeRefreshLayout.isRefreshing to true"") {
                verify(uut?.swipeRefreshLayout)?.isRefreshing = true // says no interaction with mock
            }
        }
    }           
}
</code></pre>

<p>The test is failing because it says that there was no interaction with the <code>uut?.swipeRefreshLayout</code> mock. After some experimenting, it seems this is because I'm using the UI context via <code>async(UI)</code>. If I make it just be a regular async, I can get the test to pass but then the app crashes because I'm modifying views outside of the UI thread.</p>

<p>Any ideas why this might be occurring? Also, if anyone has any better suggestions for doing this which will make it more testable, I'm all ears.</p>

<p>Thanks.</p>

<p><strong>EDIT:</strong> Forgot to mention that I also tried wrapping the <code>verify</code> and the <code>uut?.onRefresh()</code> in a <code>runBlocking</code>, but I still had no success.</p>
",https://stackoverflow.com/questions/47781377/unit-testing-coroutines-on-ui-thread,"['android', 'unit-testing', 'kotlin', 'kotlinx.coroutines']",982,TRUE,2,1
HDFS Unit testing in Spark 1.6,"<p><br>
   I am writing unit test in Spark 1.6 application and have to mock a HDFS. Is using the MiniDFSCluster <a href=""https://wiki.apache.org/hadoop/HowToDevelopUnitTests"" rel=""nofollow noreferrer"">https://wiki.apache.org/hadoop/HowToDevelopUnitTests</a> as described here. I don't see any examples in the current Spark 1.6 code that use MiniDFSCluster. </p>
",https://stackoverflow.com/questions/42047559/hdfs-unit-testing-in-spark-1-6,['apache-spark'],1104,TRUE,2,1
Asp.net core unit testing with nunit,"<p>I cant't find enough information about how to test controllers and classes in asp.net core, when dependency injection is needed.</p>

<p>Using nunit, how to test a class like this:</p>

<pre><code>public class EventServices : Service&lt;EventBase&gt;, IEventServices
{
    private readonly IMemoryCache memCache;
    private readonly UserManager&lt;ApplicationUser&gt; userManager;
    private readonly IHttpContextAccessor accessor;

    public EventServices(
        IRepository&lt;Evento&gt; repository,
        IMemoryCache memCache,
        UserManager&lt;ApplicationUser&gt; userManager,
        IHttpContextAccessor accessor
     ) : base(repository)
    {
        this.memCache = memCache;
        this.userManager = userManager;
        this.accessor = accessor;

    }

    public IQueryable&lt;Evento&gt; MyMethod(string message)
    {
     ....
</code></pre>

<p>This classe is registered in Startup class:</p>

<pre><code>services.AddScoped&lt;IEventServices, EventServices&gt;();
</code></pre>

<p>like other classes in the constructor.</p>
",https://stackoverflow.com/questions/42903627/asp-net-core-unit-testing-with-nunit,"['asp.net-core', 'nunit']",1053,TRUE,2,1
Unit testing Rxjava observables that have a delay,"<p>I want to be able to unit test an <code>Observable</code> that has a delayed emission, but without actually waiting for the delay time. Is there a way to do this? </p>

<p>I'm currently using a CountDownHatch to delay the assert, and that works fine, but increases the test run time.</p>

<p>Example:</p>

<pre><code>val myObservable: PublishSubject&lt;Boolean&gt; = PublishSubject.create&lt;Boolean&gt;()
fun myObservable(): Observable&lt;Boolean&gt; = myObservable.delay(3, TimeUnit.SECONDS)

@Test
fun testMyObservable() {
    val testObservable = myObservable().test()
    myObservable.onNext(true)

    // val lock = CountDownLatch(1)
    // lock.await(3100, TimeUnit.MILLISECONDS)
    testObservable.assertValue(true)
}
</code></pre>
",https://stackoverflow.com/questions/47296993/unit-testing-rxjava-observables-that-have-a-delay,"['android', 'unit-testing', 'kotlin', 'rx-java', 'rx-java2']",11114,TRUE,16,3
Unit testing android presenter with callback,"<p>I want to test a function on the Android presenter that have a callback on it. This is the function: </p>

<pre><code>public void findRandomUsers() {
        view.showProgress();
        mDataManager.getRandomUsers(USERS_SEARCH_NUMBER, new Callback&lt;UserList&gt;() {
            @Override
            public void onResponse(Call&lt;UserList&gt; call, Response&lt;UserList&gt; response) {
                if(view == null) return;
                view.hideProgress();
                if(response.body().getUsers().isEmpty()){
                    view.showIsEmptyError();
                }
                users = response.body();
                users.setUsers(CheckRemovedUsers.avoidRemoveds(users.getUsers(), removedUsers.getRemovedUsers()));
                users.setUsers(CheckDuplicatedUsers.removeDuplicated(users.getUsers()));
                if(isFirstTime)
                    view.showUsersList(users);
                else
                    view.updateUserList(users);
            }

            @Override
            public void onFailure(Call&lt;UserList&gt; call, Throwable throwable) {
                if(view == null) return;
                view.hideProgress();
                view.showError(throwable.getMessage());
            }
        });
    }
</code></pre>

<p>The Callback is a retrofit2.Callback object USERS_SEARCH_NUMBER is an int object. If it is possible I want to control what the callback response to control if when it returns an empty response or it fails it shows the correct answer. </p>
",https://stackoverflow.com/questions/43018084/unit-testing-android-presenter-with-callback,"['android', 'unit-testing', 'callback']",405,FALSE,1,1
Specflow and Angular JS Unit Testing,"<p>I have been a fan of BDD type testcases..Is it possible to combine Specflow with Angular JS Unit Testing (Jasmine?)</p>

<p>Has anyone ever tried it?</p>
",https://stackoverflow.com/questions/43064029/specflow-and-angular-js-unit-testing,"['angularjs', 'jasmine', 'specflow']",654,TRUE,1,1
angular2 unit testing with dependent services,"<p>I'm new to angular2 and trying to write tests for services. I have a userservice in my application which is a dependent service on multiple other services and params. The user service is making an rest-api call in the backend to pull user information.</p>

<p>I'm having a hard time to understand what is the correct way to inject the dependent services to this user service, so it can make a http call and get response. </p>

<p>user-service.ts</p>

<pre><code>export class UserService extends HttpService {

private _authToken: string;
private _persistent: boolean;

constructor(http: Http, private sessionService: SessionService, private router: Router) {
    super(http);
    this._authToken = localStorage.getItem(AUTH_TOKEN_KEY);
}

get authToken(): string {
    return this._authToken;
}
</code></pre>

<p>session-service.ts</p>

<pre><code>export class SessionService extends HttpService {

constructor(http: Http) {
    super(http);
    this.rootUrl = Constants.API_ROOT;
}

addSession(authToken: string, persistent:boolean=false): Observable&lt;any&gt; {
    return this.post(SESSIONS_ROOT, {persistent: persistent}, TokenService.AuthHeader(authToken));
}
</code></pre>

<p>user-service.spec.ts</p>

<pre><code> describe(' #######  User Service Test Cases  ####### ', () =&gt;  beforeEach(() =&gt; {
TestBed.configureTestingModule({
  providers: [
    // {
    //   provide: Router, 
    //   useClass: class { navigate = jasmine.createSpy(""navigate"")},  
    // },
    BaseRequestOptions,
    MockBackend,
    {
      provide: Http,
      useFactory: (backend: MockBackend, defaultOptions: BaseRequestOptions) =&gt; {
        return new Http(backend, defaultOptions);
      },
      deps: [MockBackend, BaseRequestOptions],
    },
    SessionService,
    UserService
  ],
  imports: [RouterTestingModule]
});   });   it('test method', inject([UserService], (userService: UserService) =&gt; {
    expect(userService.isEmailAvailable('a@a.com')).toBe('true');
 }));
</code></pre>

<p>});</p>

<p>But, I'm getting error when executing. </p>

<blockquote>
  <p>#######  User Service Test Cases  #######
      ×should return response when email is already subsribed
          Expected AnonymousSubject({ _isScalar: false, observers: [  ], closed: false, isStopped: false, hasError: false, thrownError: null, destination: AnonymousSubject({ _isScalar: false, observers: [  ], closed: false, isStopped: false, hasError: false, thrownError: null, destination: AnonymousSubject({ _isScalar: false, observers: [  ], closed: false, isStopped: false, hasError: false, thrownError: null, destination: ReplaySubject({ _isScalar: false, observers: [  ], closed: false, isStopped: false, hasError: false, thrownError: null, scheduler: undefined, _events: [  ], _bufferSize: 1, _windowTime: Infinity }), source: ReplaySubject({ _isScalar: false, observers: [  ], closed: false, isStopped: false, hasError: false, thrownError: null, scheduler: undefined, _events: [  ], _bufferSize: 1, _windowTime: Infinity }), operator: TakeOperator({ total: 1 }) }), source: AnonymousSubject({ _isScalar: false, observers: [  ], closed: false, isStopped: false, hasError: false, thrownError: null, destination: ReplaySubject({ _isScalar: false, observers: [  ], closed: false, isStopped: false, hasError: false, thrownError: null, scheduler: undefined, _events: [  ], _bufferSize: 1, _windowTime: Infinity }), source: ReplaySubject({ _isScalar: false, observers: [  ], closed: false, isStopped: false, hasError: false, thrownError: null, scheduler: undefined, _events: [  ], _bufferSize: 1, _windowTime: Infinity }), operator: TakeOperator({ total: 1 }) }), operator: MapOperator({ project: Function, thisArg: undefined }) }), source: AnonymousSubject({ _isScalar: false, observers: [  ], closed: false, isStopped: false, hasError: false, thrownError: null, destination: AnonymousSubject({ _isScalar: false, observers: [  ], closed: false, isStopped: false, hasError: false, thrownError: null, destination: ReplaySubject({ _isScalar: false, observers: [  ], closed: false, isStopped: false, hasError: false, thrownError: null, scheduler: undefined, _events: [  ], _bufferSize: 1, _windowTime: Infinity }), source: ReplaySubject({ _isScalar: false, observers: [  ], closed: false, isStopped: false, hasError: false, thrownError: null, scheduler: undefined, _events: [  ], _bufferSize: 1, _windowTime: Infinity }), operator: TakeOperator({ total: 1 }) }), source: AnonymousSubject({ _isScalar: false, observers: [  ], closed: false, isStopped: false, hasError: false, thrownError: null, destination: ReplaySubject({ _isScalar: false, observers: [  ], closed: false, isStopped: false, hasError: false, thrownError: null, scheduler: undefined, _events: [  ], _bufferSize: 1, _windowTime: Infinity }), source: ReplaySubject({ _isScalar: false, observers: [  ], closed: false, isStopped: false, hasError: false, thrownError: null, scheduler: undefined, _events: [  ], _bufferSize: 1, _windowTime: Infinity }), operator: TakeOperator({ total: 1 }) }), operator: MapOperator({ project: Function, thisArg: undefined }) }), operator: CatchOperator({ selector: Function, caught:  }) }) to be 'true'.
              at webpack:///src/app/test/user.spec.ts:75:69 &lt;- config/karma-test-shim.js:87887:71 [ProxyZone]</p>
</blockquote>

<p>I'm not sure what to understand from the error. Any help on how to proceed or inject dependent services correctly and create there instances will be help. 
Thank you so much. Appreciate the help. </p>
",https://stackoverflow.com/questions/42343663/angular2-unit-testing-with-dependent-services,"['unit-testing', 'angular', 'angular2-services']",404,FALSE,1,0
Laravel 5.5 Unit testing controller method,"<p>I am trying to setup a simple unit test for one my controller method.</p>

<p>The goals is to test if the a view has an expected value.</p>

<pre><code>/**
 * Does the homepage receive all companies when there is no licensekey provided.
 *
 * @return void
 */
public function testAllCompaniesOnHomepageWithoutLicensekey()
{
    $this-&gt;call('GET', '/');

    $allCompanies = Company::all();

    $this-&gt;assertViewHas('allCompanies', $allCompanies);
} 
</code></pre>

<p>In my conosle I get the following error:</p>

<blockquote>
  <p>Error: Call to undefined method
  Tests\Unit\ExampleTest::assertViewHas()</p>
</blockquote>

<p>I am not sure if this is no longer availbale in Laravel 5.5?</p>

<p>Anyone knows how I can test my goal?</p>
",https://stackoverflow.com/questions/46603484/laravel-5-5-unit-testing-controller-method,"['php', 'laravel', 'unit-testing', 'laravel-5']",731,TRUE,1,1
Unit testing WebRequest.CreateHttp within a library,"<p>My scenario is this -- I have a concrete class (RestSupport) behind an interface (IRestSupport) that has two core methods: CreateRequest and GetResponse. This class is designed to allow me to talk to web endpoints via JSON. This class gets called by another class that has the higher level business logic to provide the exact JSON that needs to be sent.</p>

<p>I need to be able to unit test those two methods such that they don't call the endpoints during testing. CreateRequest relies on HttpWebRequest because I need to add information to the Headers collection. There is more code than this, but below gives you an example.</p>

<pre><code>var request = WebRequest.Create(url) as HttpWebRequest;
request.Headers.Add(""Authorization"", AuthorizationHeader);
</code></pre>

<p>I see many examples on the web of using IWebRequestCreate such that you can control the request creation. The problem that I'm having is that I cannot seem to get this to work properly when using HttpWebRequest. The Create method of IWebRequestCreate expects that you will return a WebRequest object. The downside of the web examples is that they're not using HttpWebRequest. I cannot derive a class from HttpWebRequest, which is really the crux of my problem.</p>

<p>I do not have access to fakes, but can use Moq. My goal is to not modify the library code if it can be avoided.</p>
",https://stackoverflow.com/questions/41600164/unit-testing-webrequest-createhttp-within-a-library,"['c#', 'httpwebrequest']",222,FALSE,1,2
Java Unit Testing Help for loop,"<pre><code>public void login(String username, String password) {

    for(int i = 0; i &lt; Users.size(); i++) {
        user users = (user) Users.get(i);
        if(users.getUsername().contains(username)
               &amp;&amp; users.getPassword().contains(password)) {
            userName = users.getUsername();
            userLevel = users.getUserLevel();
            isSuccess = true;
        }
    }    
}
</code></pre>

<p>Hello everyone. I'm trying to do a java unit testing for this method using Java Junit. But i don't know how to do that? Because there's a for loop. </p>

<p>Let me explain the method.</p>

<pre><code>for(int i=0;i&lt;Users.size();i++){
</code></pre>

<p>This ""Users"" is a vector. This loop runs unit this vector ends.</p>

<pre><code>user users = (user) Users.get(i);
</code></pre>

<p>Then im calling user class for user instance.</p>

<pre><code> if((users.getUsername().contains(username)) &amp;&amp;
    (users.getPassword().contains(password))) {
</code></pre>

<p>Then if any of the users that matches with the values in the vectors, this gives the output.</p>

<p>Can anyone tell me how to write a unit test for this?</p>
",https://stackoverflow.com/questions/45524768/java-unit-testing-help-for-loop,"['java', 'unit-testing', 'junit']",20724,TRUE,1,1
Unit testing for either/or conditions,"<p>The module I'm working on holds a list of items and has a method to locate and return an item from that list based on certain criteria. the specification states that ""...if several matching values are found, any one may be returned""</p>

<p>I'm trying to write some tests with Nunit, and I can't find anything that allows me to express this condition very well (i.e. the returned object must be either A or B but I don't mind which)</p>

<p>Of course I could quite easily write code that sets a boolean to whether the result is as expected and then just do a simple assert on that boolean, but this whole question is making me wonder whether this is a ""red flag"" for unit testing and whether there's a better solution.</p>

<p>How do experienced unit testers generally handle the case where there are a range of acceptable outputs and you don't want to tie the test down to one specific implementation?</p>
",https://stackoverflow.com/questions/42480578/unit-testing-for-either-or-conditions,"['unit-testing', 'nunit']",1459,TRUE,1,2
Unit testing with stubs and mocks,"<p>I'm trying to write tests for some classes. The classes I want to test use different repositories to to get and save things from my database.</p>

<p>A simplified example</p>

<pre><code>public class MyClass
{
    private readonly IGroupRepository _groupRepo;

  public MyClass(IGroupRepository groupRepo){ 
    _groupRepo = groupRepo; 
  }

  public void Execute(PersonInfo personInfo, string id){
  var group = _groupRepo.GetById(id);

  var person = group.Persons.First(p=&gt; p.Id == personInfo.Id);

  person.FirstName = personInfo.FirstName;
  person.LastName = personInfo.LastName;

  _groupRepo.Save(group);      
  }
}
</code></pre>

<p>What I want to do is make sure that what is saved into the db is correct.</p>

<p>So I have a unit test like this:</p>

<pre><code>[TestMethod]
public void TestMethod(){
    var groupId = ""ABC"";
    var personId = 1;

    ver personInfo = new PersonInfo()
    {
      Id = personId,
      FirstName = ""Sam"",
      LastName = ""Smith""  
    }

    var groupStub = new Mock&lt;IGroupRepository&gt;;
    groupStub.Setup(x=&gt; x.GetById(groupId)).Returns(new Group(){
            Id = groupId,
            Persons = List&lt;Person&gt;()
            {
                new Person()
                {
                    Id = personId,
                    FirstName = ""George"",
                    LastName = ""Bolton"",
                }
            }
        }
    });

    var myClass = new MyClass();
    myClass.Execute(personInfo, groupId);

    var group = groupStub.GetById(groupId);
    var person = group.Persons.First(p=&gt; p.Id == personId);

    Assert.AreEqual(personInfo.FirstName, person.FirstName);
}
</code></pre>

<p>I thought this was fine, but then I was reading more up on it and I read that you are not supposed to assert on a sub, which I think I'm doing in my assert statement? I'm getting info from the stub, then using Assert on the result?</p>

<p>So I'm not sure if this is the correct way to test. If not, why and what is the correct way? </p>
",https://stackoverflow.com/questions/44449410/unit-testing-with-stubs-and-mocks,"['c#', 'unit-testing']",507,TRUE,1,3
Unit testing mysql rollback on node.js,"<p>I'm using mysql in a node project.</p>

<p>I would like to unit test a javascript function that makes an sql transaction. If the transaction becomes the victim of a lock monitor, the function has code that handles the failure.</p>

<p><em>Or does it?</em></p>

<p>Because I'm unit testing, I'm only making one transaction at a time on a local database, so there's never going to be a deadlock, right? How can I test the deadlock handling if it's never going to happen? Is there a way I can force it to happen?</p>

<p>Example:</p>

<pre><code>thisMustBeDoneBeforeTheQuery();
connection.queryAsync(/*This is an update*/).catch(function(err) {
    undoThatStuffIDidBeforeTheQuery();
    // I hope that function worked, because my unit tests can't
    // make a deadlock happen, so I can't know for sure.
}
</code></pre>
",https://stackoverflow.com/questions/46406315/unit-testing-mysql-rollback-on-node-js,"['mysql', 'node.js', 'unit-testing', 'deadlock']",800,FALSE,1,1
Unit testing - Unknown provider: translateFilterProvider &lt;- translateFilter,"<p>I have this unit testing that executes an error </p>

<blockquote>
  <p>Unknown provider: translateFilterProvider &lt;- translateFilter</p>
</blockquote>

<p>How can I inject the $translate service?</p>

<pre><code>import angular from 'angular'
import 'angular-mocks'

let $scope
let $compile
let htmlElement

describe('ProjectGeneralSituationForm', () =&gt; {
  beforeEach(angular.mock.module('ProjectGeneralSituationModule'))

  beforeEach(() =&gt; {
    inject((_$rootScope_, _$compile_) =&gt; {
      $scope = _$rootScope_.$new()
      $compile = _$compile_
    })
  })

  beforeEach(() =&gt; {
    $scope.project = {}
    $scope.projectTypes = {}
    $scope.projectReferences = {}
    htmlElement = $compile(`&lt;project-general-situation-form project=""project"" project-types=""projectTypes"" project-references=""projectReferences""&gt;&lt;/project-general-situation-form&gt;`)($scope)
    $scope.$digest()
  })

  it('should be defined', () =&gt; {
    expect(htmlElement).toBeDefined()
  })
})
</code></pre>
",https://stackoverflow.com/questions/45151693/unit-testing-unknown-provider-translatefilterprovider-translatefilter,"['javascript', 'angularjs', 'unit-testing', 'jasmine', 'karma-jasmine']",99,FALSE,1,0
Unit Testing of new Thread(...).start(),"<p>I am trying to write test case for Threads, which is written by someone else. </p>

<p>I don't have liberty of changing the existing code.I have gone through various threads in this forum but nothing seems to be working for this scenario. Please suggest.</p>

<p>My code is like below:</p>

<pre><code>Class X implements Runnable{
   Y y;
   public X(){}

    public X(Y y){
      this.y = y;
    } 

    public void run(){
    Y.staticVoidMethod(A a, B b, boolean c);
    }
}
</code></pre>

<p>Then in another class <code>class Main</code> below line is written:</p>

<pre><code>class Main{
    public static void main1(){     
    Y y=new Y();
    new Thread(new X(y)).start();
    }
}
</code></pre>

<p>My Test class is like below:</p>

<pre><code>class Test {    
  Thread thread;
  X x;
  Y y = spy(new Y());

  @BeforeMethod(alwaysRun = true)
  public void setup() throws Exception {
                    MockitoAnnotations.initMocks(this);
                    PowerMockito.mockStatic(Y.class);

        x= spy(new X(y));
        thread = spy(new Thread(x));

whenNew(X.class).withAnyArguments().thenReturn(x);
                    whenNew(Thread.class).withArguments(x).thenReturn(thread);      // I have also tried ......withArguments(X.class).thenReturn(thread)

        }

        @Test
        public void test1(){
                Main.main1();
           //none of the below is working
           verify(thread).start();
           verify(x).run();
           assertTrue(thread.isAlive());
      } 
}
</code></pre>
",https://stackoverflow.com/questions/44627911/unit-testing-of-new-thread-start,"['java', 'multithreading', 'unit-testing']",4543,TRUE,1,2
Unit testing a service in Angular4,"<p>I'm fairly new to the world of Angular4 and using Jasmine/Karama for testing.  I've created a small app that wraps two web api services and I need to write tests for these.</p>

<p>Using online examples, and my basic understanding of mocking in Angular4, I've managed to hack together a test for my first service and its running fine.  The constructor of this first service has only one dependency (http module, which happened to coincide with the example I was using!).</p>

<p><strong>Service example 1</strong> :</p>

<pre><code>// Lookups api wrapper class.
@Injectable()
export class LookupsService {

    private servicegApiUrl = '';

    public constructor( private http : Http ) {  
        // Build the service api url, uring the environment lookups api url, plus controller name to reference.
        this.servicegApiUrl = environment.apiUrl + 'Lookups/';
    }

    // Get the hubs from the web api.
    public getHubs() : Observable&lt;KeyValuePair&lt;number&gt;[]&gt; {
        // Carry out http get and map the result to the KeyValuePair number object.
        return this.http.get(this.servicegApiUrl + 'Hubs').map(res =&gt; { 
            if (res){ return res.json() as KeyValuePair&lt;number&gt;[]; }
        });
    }
}
</code></pre>

<p><em>Tests example 1 - Tests working:</em></p>

<pre><code>describe('Service: LookupService', () =&gt; {

  let service: LookupsService;
  let backend: MockBackend;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [HttpModule],
      providers: [
        LookupsService,
        MockBackend,
        BaseRequestOptions,
        {
          provide: Http,
          useFactory: (backend, options) =&gt; new Http(backend, options),
          deps: [MockBackend, BaseRequestOptions]
        }
      ]
    });

    // Get the MockBackend
    backend = TestBed.get(MockBackend);

    // Returns a service with the MockBackend so we can test with dummy responses
    service = TestBed.get(LookupsService);

  });

  it('getHubs() should return populated KeyValuePair&lt;number&gt;[]', async(() =&gt; {
    let response = 
        [{
            ""Key"": ""Hub 1 example"",
            ""Value"": 1
        },{
            ""Key"": ""Hub 2 example"",
            ""Value"": 2
        }]
    ;

    // When the request subscribes for results on a connection, return a fake response
    backend.connections.subscribe(connection =&gt; {
      connection.mockRespond(new Response(&lt;ResponseOptions&gt;{
        body: JSON.stringify(response)
      }));
    });

    // Perform a request and make sure we get the response we expect
    var hubsRes : KeyValuePair&lt;number&gt;[];
    service.getHubs().subscribe(hubs =&gt; { 
        hubsRes = hubs;
        console.log(hubs);
    });

    // Test hubs is populated.
    expect(hubsRes.length).toBeGreaterThan(0);

  }));

});
</code></pre>

<p>All good so far, I now need to write tests for a second service.  In this service I had injected a custom service I created for logging (it doesn't have any dependencies injected in, and simply wraps console.log).</p>

<p><strong>Service example 2</strong></p>

<pre><code>// Routing Rules api wrapper class.
@Injectable()
export class RoutingRulesService {

    private servicegApiUrl = '';

    public constructor( private loggerService : LoggerService, private http : Http ) {  
        // Build the service api url, uring the environment routing api url, plus controller name to reference.
        this.servicegApiUrl = environment.routingApiUrl + 'routingRules/';
    }

    // Perform search using passed in filter.  Returns SearchResult object.
    public getSearchFiltered(options): Observable&lt;SearchResult&gt; {
        // Api url is the service url, plus Filtered and search query string.
        var apiUrl = this.servicegApiUrl + 'Filtered' + options;
        this.loggerService.logInfo(""Route search query url: "" + apiUrl);

        // Carry out http get and map the result to the SearchResult object.
        return this.http.get(apiUrl).map(res =&gt; { 
            if (res){ return res.json() as SearchResult; }
        });
    }
}
</code></pre>

<p><em>Tests example 2 - Tests <strong>not working</strong>:</em></p>

<pre><code>describe('Service: RoutingRulesService', () =&gt; {

  let service: RoutingRulesService;
  let logger : LoggerService;
  let backend: MockBackend;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [HttpModule, LoggerService],
      providers: [
        RoutingRulesService,
        MockBackend,
        BaseRequestOptions,
        {
          provide: Http,
          useFactory: (backend, options) =&gt; new Http(backend, options),
          deps: [MockBackend, BaseRequestOptions]
        },
        logger
      ]
    });

    // Get the MockBackend
    backend = TestBed.get(MockBackend);

    // Returns a service with the MockBackend so we can test with dummy responses
    service = TestBed.get(RoutingRulesService);

  });

  it('getSearchFiltered(), with no search parameter, should return populated SearchResult', async(() =&gt; {
    let response = 
    {
      ""Pagination"": {
        ""RecordCount"": 2,
        ""PageRecordsFrom"": 1,
        ""PageRecordsTo"": 1,
        ""TotalPages"": 1,
        ""PageSize"": 2,
        ""PageNumber"": 1,
        ""SortBy"": ""RoutingRuleId"",
        ""Ascending"": true
      },
      ""Results"": [
        {
          ""RoutingRuleId"": 1,
          ""BrandId"": 21,
          ""CashOnDelivery"": false,
          ""CreationTime"": ""2017-09-11T15:14:41.207"",
          ""CurrencyCode"": 2,
          ""CurrencyDescription"": ""USD""
        },
        {
          ""RoutingRuleId"": 2,
          ""BrandId"": 21,
          ""CashOnDelivery"": false,
          ""CreationTime"": ""2017-09-11T15:14:41.207"",
          ""CurrencyCode"": 2,
          ""CurrencyDescription"": ""USD""
        }]
      }    
    ;

    // When the request subscribes for results on a connection, return a fake response
    backend.connections.subscribe(connection =&gt; {
      connection.mockRespond(new Response(&lt;ResponseOptions&gt;{
        body: JSON.stringify(response)
      }));
    });

    // Perform a request and make sure we get the response we expect
    var searchRes : SearchResult;
    service.getSearchFiltered(null).subscribe(results =&gt; { 
        searchRes = results;
        console.log(results);
    });

    // Test populated.
    expect(searchRes.Pagination.RecordCount).toBeGreaterThan(0);
    expect(searchRes.Results[0].RoutingRuleId).toEqual(1);

  }));
});
</code></pre>

<p>I get this error when compiling my tests:</p>

<p><em>Service: RoutingRulesService getSearchFiltered(), with no search parameter, should return populated SearchResult FAILED
        Error: Unexpected value 'LoggerService' imported by the module 'DynamicTestModule'. Please add a @NgModule annotation.</em></p>

<p>How do I successfully inject a new instance of my logger service into this second service?</p>

<p>Thanks for all pointers in advance!</p>
",https://stackoverflow.com/questions/46767870/unit-testing-a-service-in-angular4,"['angular', 'unit-testing', 'dependency-injection', 'protractor', 'karma-jasmine']",757,FALSE,1,0
Unit Testing with Mocha Jade/Javascript,"<p>I have a jade file and corresponding javascript file. the Div elements are defined in jade file and i am using getElementById to access those element in javascript file dynamically. How should i write test cases ? In Mocha I am getting error like "" Uncaught TypeError: Cannot set property 'innerHTML' of null""</p>
",https://stackoverflow.com/questions/45395663/unit-testing-with-mocha-jade-javascript,"['javascript', 'unit-testing', 'testing', 'mocha.js', 'pug']",532,FALSE,1,0
Kotlin coroutines unit testing using mockito,"<p>i am getting the below when i try to mock and verify on an activity that's calling a suspend function</p>

<p><strong>Error:</strong></p>

<p>Argument(s) are different! Wanted:
userManager.getAccountInfo(
(onCreate_callsGetAccountInformation$1) kotlinx.coroutines.experimental.CoroutineScope.() -> kotlin.Unit
);
-> at com.pharmacy.AccountActivityTests$onCreate_callsGetAccountInformation$1.doResume(AccountActivityTests.kt:117)
Actual invocation has different arguments:
userManager.getAccountInfo(
() kotlinx.coroutines.experimental.CoroutineScope.() -> kotlin.Unit
)
-> at com.pharmacy.AccountActivity$loadAccountInfoAsync$1$1.doResume(AccountActivity.kt:199)</p>

<p><strong>Code:</strong></p>

<p>I have my unit test case decorated with runBlocking like this:</p>

<pre><code>    @Test 
    fun onCreate_callsGetAccountInformation() = runBlocking&lt;Unit&gt; 
    { whenever(userManager.getAccountInfo()).thenReturn(AccountInformation()) 
      subject = Robolectric.setupActivity(AccountActivity::class.java) 
      verify(userManager).getAccountInfo() 
    }
</code></pre>

<p>here -> usermanager.getAccountInfo() is a suspend function.</p>
",https://stackoverflow.com/questions/47560808/kotlin-coroutines-unit-testing-using-mockito,"['android', 'unit-testing', 'kotlin', 'mockito', 'kotlinx.coroutines']",1084,TRUE,1,1
React js unit testing with enzyme,"<p>Hi guys i am new to react can anyone help me to write unit test for the below code .. i want to test if link is redirecting properly..</p>

<p>Here is my code ..</p>

<pre><code>import React { Component } from 'react';
import {Link} from 'react-router';
import './App.css';

class Home extends Component {
  render() {
    return (
      &lt;Link to='/college/masters/cs' className=""student""&gt;  
        &lt;div className=""centered""&gt;
          &lt;h2 className=""Branch""&gt;Branch&lt;/h2&gt;
        &lt;/div&gt;
      &lt;/Link&gt;
    );
  }
}
</code></pre>

<p>My test</p>

<pre><code>import React from 'react';
import { mount, shallow } from 'enzyme';
import {expect} from 'chai';
import 'ignore-styles';
import Home from '../src/Home';

describe('&lt;Home/&gt;', function () {
  it('should have a Link', function () {
    const wrapper = shallow(&lt;Home/&gt;);

    expect(wrapper.find('Link')).to.have.length(1);
  });
});
</code></pre>

<p>Please help me to write test if link is redirecting properly..</p>

<p>Thank you</p>
",https://stackoverflow.com/questions/46190966/react-js-unit-testing-with-enzyme,['reactjs'],50,FALSE,1,1
Unit testing angular service with dependencies,"<p>I have the following Jasmine unit test:</p>

<pre><code>describe('myService', function () {
    var myService, $q;

    // Instantiate the app
    beforeEach(module('myApp'));

    beforeEach(inject(function (_myService_, fileSystemService, $q) {
        myService = _myService_;
        spyOn(fileSystemService, 'listFiles').and.callFake(function () {
            var deferred = $q.defer();
            deferred.resolve('mockresult');
            return deferred.promise;
        });
    }));

    it('checks the number of outbound files', inject(function ($rootScope) {
        var result;
        myService.sendOutboundFiles2().then(function (res) {
            result = res;
        });
        $rootScope.$digest();
        expect(result).toBe('mockresult');
    }));
});
</code></pre>

<p>Which tests this very simple service function:</p>

<pre><code>sendOutboundFiles2() {
     return fileSystemService.listFiles('Cached/Outbound').then(function(outfiles) {
         return outfiles;
     })
}
</code></pre>

<p>However when the test runs, it fails with a spurious <code>Error: Unexpected request: GET blah\blah\blah.html No more request expected at $httpBackend</code> error but i have no idea why as neither this test nor the service dependencies do anything with $httpBackend.</p>

<p><strong>MORE INFO</strong></p>

<p>If i comment out my existing controller tests, I get this error: 
<a href=""https://i.stack.imgur.com/qNpAO.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/qNpAO.jpg"" alt=""service test only""></a></p>

<p>If i add my controller tests back in, I get this error:
<a href=""https://i.stack.imgur.com/p0FC7.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/p0FC7.jpg"" alt=""enter image description here""></a></p>

<p>So depending on which tests i add or remove, the HTML file in the <code>GET</code> error changes. But all the controller tests run fine. WTF?!?!?!!??!?!!?</p>
",https://stackoverflow.com/questions/41559172/unit-testing-angular-service-with-dependencies,"['javascript', 'angularjs', 'unit-testing']",99,FALSE,1,1
d3js unit testing removal of elements,"<p>I am using <code>jasmine</code> to unit test some interactions in a <code>d3.js</code> chart.  I have been using <code>d3.timerFlush()</code> to complete the executions of animations.  This works great for when entering new elements or updating attribute, and I am able to accurately test the new values.  However, I am having a hard time getting it to remove elements.</p>

<p>I have a method like this:</p>

<pre><code>exit() {
    let arcs = svg.selectAll(""path.arc"");

    arcs.transition().duration(1000)
        .attrTween(""d"", function(d, i) { return vm._arcTween(this, d) })
        .remove();
}
</code></pre>

<p>And my test looks something like this:</p>

<pre><code>it('it will remove all of the pie related elements from the DOM', () =&gt; {
        chartSvc.exit();
        d3.timerFlush();
        let elements = svg.querySelectorAll(/* selects my elements */);
        expect(elements.length).toEqual(0);
});
</code></pre>

<p>which fails.  If I debug the tests, I can see that the elements are not being removed.  However if I change the expect:</p>

<pre><code>expect(pieChartSvc._arcTween).toHaveBeenCalled();
</code></pre>

<p>that passes, so I know that the method is being executed correctly and the timer flushed, but the elements aren't removed.</p>

<p>What am I doing wrong?</p>

<p>This issue: <a href=""https://stackoverflow.com/questions/14443724/disabling-all-d3-animations-for-testing"">Disabling all D3 animations (for testing)</a>
does not answer my question.  The <em>transition</em> is being executed and the elements have been changed to the state they are in before they are removed from the DOM, however they still appear on the DOM</p>
",https://stackoverflow.com/questions/42538240/d3js-unit-testing-removal-of-elements,"['d3.js', 'jasmine']",894,TRUE,1,1
Django Unit Testing: cannot mock django.core.urlresolvers.resolve,"<p>I'm trying to mock the <em>django.core.urlresolvers.resolve</em> function, but it doesn't seem to be work. I've tested with custom functions and it works like a charm, but mock ignores <em>resolve</em> completely.</p>

<p>Code:</p>

<p><strong>test_something.py:</strong></p>

<pre><code>class SomethingTestCase(TestCase)
    def setUp(self):
        self.middleware = SomeMiddleware()
        self.request = Mock()
        self.request.session = {}

    @patch('django.core.urlresolvers.resolve', side_effect=lambda: None)
    def test_something(self):
        self.assertEqual(self.middleware.process_request(self.request), None)
</code></pre>

<p><strong>middleware.py</strong></p>

<pre><code>class SomeMiddleware(object):
    def process_request(self, request):
        app = resolve(request.path).app_name
        print('App name: {}'.format(app))
</code></pre>

<p>This results in the following error:</p>

<pre><code>======================================================================
ERROR: test_process_request_unauthenticated (something.tests.unit.test_middleware.SomethingTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File ""/home/user/virtualenv/something/local/lib/python2.7/site-packages/mock/mock.py"", line 1305, in patched
    return func(*args, **keywargs)
  File ""/home/user/projects/something/working/something/tests/unit/test_middleware.py"", line 23, in test_process_request_unauthenticated
    self.assertEqual(self.middleware.process_request(self.request), None)
  File ""/home/user/projects/something/working/something/middleware.py"", line 14, in process_request
    app = resolve(request.path).app_name
  File ""/home/user/virtualenv/something/local/lib/python2.7/site-packages/django/core/urlresolvers.py"", line 534, in resolve
    return get_resolver(urlconf).resolve(path)
  File ""/home/user/virtualenv/something/local/lib/python2.7/site-packages/django/core/urlresolvers.py"", line 405, in resolve
    raise Resolver404({'path': path})
Resolver404: {u'path': u""&lt;Mock name='mock.path' id='140678271233168'&gt;""}
</code></pre>

<p>My goal here is to make the <em>resolve</em> function returns something where I can get the app name.</p>

<p>Why is mock.patch unable to override the resolve function?</p>
",https://stackoverflow.com/questions/46607387/django-unit-testing-cannot-mock-django-core-urlresolvers-resolve,"['python', 'django', 'unit-testing']",205,TRUE,1,1
error while unit testing angular controller,"<p>Can someone help me solve this. Tried to create a single page app using angular in front end and node in the back end.
Tried to install karma and jasmine and wrote a simple test spec to check the title of the controller. The app works fine and is routing fine. But when I try to do unit testing using jasmine. It throws the following error and the test suite fails. Please help me find out what went wrong.</p>

<p>karma start karma.conf.js
30 10 2017 11:36:16.490:WARN [karma]: No captured browser, open <a href=""http://localhost:9876/"" rel=""nofollow noreferrer"">http://localhost:9876/</a>
30 10 2017 11:36:16.507:INFO [karma]: Karma v1.7.1 server started at <a href=""http://0.0.0.0:9876/"" rel=""nofollow noreferrer"">http://0.0.0.0:9876/</a>
30 10 2017 11:36:16.508:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
30 10 2017 11:36:16.542:INFO [launcher]: Starting browser PhantomJS
30 10 2017 11:36:19.563:INFO [PhantomJS 2.1.1 (Windows 8 0.0.0)]: Connected on socket ZViNyPVeq1YwHHl-AAAA with id 30996953
PhantomJS 2.1.1 (Windows 8 0.0.0) testing AngularJS testing controllers should initialize title FAILED
        C:/Users/Public/projects/hospital_angularjs/public/bower_components/angular/angular.js:4958:53
        forEach@C:/Users/Public/projects/hospital_angularjs/public/bower_components/angular/angular.js:410:24
        loadModules@C:/Users/Public/projects/hospital_angularjs/public/bower_components/angular/angular.js:4917:12
        createInjector@C:/Users/Public/projects/hospital_angularjs/public/bower_components/angular/angular.js:4839:30
        WorkFn@C:/Users/Public/projects/hospital_angularjs/public/bower_components/angular-mocks/angular-mocks.js:3172:60
        inject@C:/Users/Public/projects/hospital_angularjs/public/bower_components/angular-mocks/angular-mocks.js:3152:46
        unit/testingunitspec.js:9:19
        loaded@<a href=""http://localhost:9876/context.js:162:17"" rel=""nofollow noreferrer"">http://localhost:9876/context.js:162:17</a>
PhantomJS 2.1.1 (Windows 8 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0 secs / 0.015 secs)</p>

<p>The main.js file is </p>

<pre><code>var app = angular.module('myApp',[""ngRoute""]);

app.controller('myCtrl', function($rootScope,$scope){
    $scope.title = ""Welcome!"";
});
</code></pre>

<p>My testSpec.js file is</p>

<pre><code>describe('testing AngularJS', function(){
beforeEach(module('myApp'));

describe('testing controllers', function() {

    it('should initialize title', function() {
        var scope = {};
        var ctrl;
        inject(function($controller) {
            ctrl = $controller('myCtrl', {$scope:scope});
        });
        expect(scope.title).toBeDefined();
        expect(scope.title).toBe('Welcome!');
    });
});
</code></pre>

<p>});</p>

<p>Please help me solve this. Thanks in advance. </p>
",https://stackoverflow.com/questions/47022210/error-while-unit-testing-angular-controller,"['javascript', 'angularjs', 'unit-testing', 'karma-jasmine', 'angular-controller']",117,FALSE,1,0
Unit testing code dependent on DateTime.Now,"<p>The Codewars.com description below.</p>

<blockquote>
  <p>Create a function which passes in a birthday and returns how old a person is in years.</p>
</blockquote>

<p>The Test Cases have already been developed for you. When the test case was created the programmer assumed there would be a shared interface between a <code>SystemClock</code> class and <code>StaticClock</code> class.</p>

<pre><code>public class SystemClock : IClock { ... }

public class StaticClock : IClock { ... }
</code></pre>

<p>The <code>SystemClock</code> class needs to implement a <code>DateTime</code> method that returns <code>DateTime.Now</code></p>

<p>The <code>StaticClock</code> method needs to implement a <code>DateTime</code> method that returns a <code>DateTime</code> value that was passed to its constructor.</p>

<p>The <code>StaticClock</code> implementation of <code>IClock</code> is used in our UnitTest to provide a constant time value for our unittest. Considering that time is always in motion...if we were to simply create unit test based on <code>DateTime.Now</code> then our unit test will fail over time.</p>

<p>With the <code>StaticClock</code> we can inject what value our <code>IClock.Now</code> method should return so our unit test will continue to pass even as time moves on.</p>

<p>My code below.</p>

<pre><code>using System;

namespace AgeFromDOB
{
    public class Program
    {

        public class Kata 
        {
            private DateTime staticClock;

            public Kata(StaticClock staticClock)
            {
                this.staticClock = staticClock.Now;
            }

            public int GetAgeFromDOB(DateTime birthday)
            {
                return staticClock.Year - birthday.Year;
            }
        }

        public interface IClock
        {
            DateTime Now { get; }
        }

        public class SystemClock : IClock
        {
            public DateTime Now { get; }

            public  DateTime Method(DateTime Now)
            {
                return Now;
            }
        }

        public class StaticClock : SystemClock, IClock
        {
            public StaticClock(DateTime Now)
            {
                 Method(Now);
            }
        }

        static void Main(string[] args)
        {
            Kata kata;
            kata = new Kata(new StaticClock(new DateTime(2008,09,3)));
            kata.GetAgeFromDOB(new DateTime(1984,04,23));
            Console.ReadKey();
        }
    }
}
</code></pre>

<p>when I try to pass in <code>new Kata(new StaticClock(new DateTime(2008,09,3)));</code></p>

<p>the object is not being passed correctly and I keep getting the wrong outcome.</p>

<p>I would like to know where to research or what pattern I should look at to solve this problem ? </p>
",https://stackoverflow.com/questions/42056401/unit-testing-code-dependent-on-datetime-now,"['c#', 'unit-testing']",1194,TRUE,1,1
Unit testing test for Ok Result,"<p>I have the following (simplified) controller:</p>

<pre><code>public async Task&lt;IHttpActionResult&gt; Profile(UpdateProfileModelAllowNulls modelNullable)
{         
    ServiceResult&lt;ProfileModelDto&gt; result = await _profileService.UpdateProfile(1);

    return Ok(result);         
}
</code></pre>

<p>And:</p>

<pre><code>public async Task&lt;ServiceResult&lt;ProfileModelDto&gt;&gt; UpdateProfile(ApplicationUserDto user, UpdateProfileModel profile)
{
     //Do something...
}
</code></pre>

<p>and the following NUnit test:</p>

<pre><code>[Test]
        public async Task Post_Profile()
        {
            var result = _controller.Profile(new UpdateProfileModelAllowNulls() { Email = ""testEmail@tt.co.uk"", DisplayName = ""TestDisplay""}) as OkNegotiatedContentResult&lt;Task&lt;&lt;ProfileModelDto&gt;&gt;;
            Assert.IsNotNull(result);            
        }
</code></pre>

<p>In my NUnit test, I am trying to check for an Ok result using this tutorial <a href=""https://www.asp.net/web-api/overview/testing-and-debugging/unit-testing-with-aspnet-web-api"" rel=""nofollow noreferrer"">https://www.asp.net/web-api/overview/testing-and-debugging/unit-testing-with-aspnet-web-api</a>.</p>

<p>My problem is that I cannot convert to an <code>OkNegotiatedContentResult</code>, i assume because I am not passing in the correct object, but I cannot see what object I should be passing in. As far as I can see, I am passing in the correct object eg: <code>OkNegotiatedContentResult&lt;Task&lt;&lt;ProfileModelDto&gt;&gt;;</code></p>

<p>but this does not work.</p>

<p>I have also tried:</p>

<pre><code>var result = _controller.Profile(new UpdateProfileModelAllowNulls() { Email = ""testEmail@tt.co.uk"", DisplayName = ""TestDisplay""}) as OkNegotiatedContentResult&lt;Task&lt;IHttpActionResult&gt;&gt;;
</code></pre>

<p>But this does not work either.</p>

<p>Can anyone help?</p>
",https://stackoverflow.com/questions/41718653/unit-testing-test-for-ok-result,"['c#', 'unit-testing', 'httpresponse']",1663,TRUE,1,2
Ruby on Rails: unit testing helpers,"<p>I have a simple helper method, which determines, whether a user should see the full price of a product or 0, based on his bonus points:</p>

<pre><code>def show_user_price(product, user = current_user)
  return user.bonus_points == 100 ? 0 : product.full_price
end
</code></pre>

<p>Now I would like to unit test the method. I have created a new test in test/helpers/user_price_helper_test, which inherits from ActiveSupport::TestCase. I have included the UserProductHelper. The test case runs smoothly, all the assertions are passed, but in the end I get </p>

<pre><code>Minitest::Assertion: Expected response to be &lt;success&gt;, but was &lt;500&gt;. 
</code></pre>

<p>It seems the test runner evaluates the test as if it should return a template, or at least an HTTP response. How do I properly unit test helper methods like this one?</p>

<p><strong>Edit: my unit test method</strong></p>

<pre><code>test 'user sees 0 price' do
  user = User.new(name: 'Sample user', bonus_points: 100)
  product = Product.new(name: 'Sample product', full_price: 200)
  result = show_user_price(product, user)
  assert result == 0
end
</code></pre>
",https://stackoverflow.com/questions/42440950/ruby-on-rails-unit-testing-helpers,"['ruby-on-rails', 'unit-testing']",171,FALSE,1,0
Unit testing using Junit without arguments,"<p>I have a very big method that requires unit testing, so I had to refactor the code to make it as simple and as readable as possible, I did that however, the last step should be to perform unit testing on different methods, so my question is how to perform unit testing for a method that doesn't have arguments, I have updated my question to include arguments and that is the unit test I performed but it's not correct at all, Your assistance is appreciated.</p>

<p>Customer.java</p>

<pre><code>public class Customer {
private String customerName;
private Vector&lt;Rental&gt; customerRentals = new Vector&lt;Rental&gt;();
double thisAmount;
Rental eachRental;
int rewardPoints;

public Customer(String customerName) {
    this.customerName = customerName;
}

public void addRental(Rental rental) {
    customerRentals.addElement(rental);
}

public String getCustomerName() {
    return customerName;
}

public String statement() {
    double totalAmount = 0;
    rewardPoints = 0;
    Enumeration&lt;Rental&gt; rentals = customerRentals.elements();
    String result = ""Rental Record for:"" + getCustomerName() + ""\n"";
    while (rentals.hasMoreElements()) {
        thisAmount = 0;
        eachRental = (Rental) rentals.nextElement();

        thisAmount=50.0;

        switch (eachRental.getVehicle().getRateCode()) {

            case Vehicle.SEDAN:
                thisAmount += 100*eachRental.getDaysRented();
                if (eachRental.getMileage() &gt; eachRental.getDaysRented()*50)
                {
                    thisAmount += (eachRental.getMileage() - 
                    eachRental.getDaysRented()*50) * 2;
                }
                break;

            case Vehicle.FOURxFOUR:
                thisAmount += 200*eachRental.getDaysRented();
                break;

            case Vehicle.SUV:
                thisAmount += 150*eachRental.getDaysRented();
                if (eachRental.getMileage() &gt; eachRental.getDaysRented()*70)
                    thisAmount += (eachRental.getMileage() - 
                    eachRental.getDaysRented()*70) * 2;
                break;
            default:
                    thisAmount+=0;
        }

        getTotalMilage(eachRental);

        isLate();

        result += ""\t\"""" + eachRental.getVehicle().getMakeAndModel() + 
                  ""\""\tLE "" +
                String.valueOf(thisAmount) + ""\n"";

        totalAmount+=thisAmount;

    }

    result += ""Amount owed is LE "" + String.valueOf(totalAmount) + ""\n"";

    result += ""You earned: "" + String.valueOf(rewardPoints) +
            "" new Reward Points\n\n"";
    return result;
}
public double getTotalMilage(Rental rentalMilage)
{
 if (rentalMilage.getMileage() &gt; 200)
    {
        if (rentalMilage.getDaysRented() &gt; 10 &amp;&amp; 
            rentalMilage.getVehicle().getRateCode()== Vehicle.FOURxFOUR)
        {
            return thisAmount-=thisAmount*0.05;
        }
        else if (rentalMilage.getVehicle().getRateCode() == Vehicle.SUV)
        {
            System.out.println(eachRental);
            return thisAmount-=thisAmount*0.05;
        }
    }

 return thisAmount;
}

public boolean isLate(){
 if (!eachRental.isLate()) 
 {
        rewardPoints++;

        if ((eachRental.getVehicle().getRateCode() == Vehicle.FOURxFOUR)) {
            rewardPoints *= 2;
        }
 }

        if ((eachRental.getVehicle().getRateCode() == Vehicle.SUV) &amp;&amp; 
             eachRental.getDaysRented() &gt; 5) {
            rewardPoints += (eachRental.getDaysRented() - 5);
        }

 else
    {
        thisAmount+=thisAmount*0.03;
    }
        return true;
    }
}
</code></pre>

<p>CustomerTest.java</p>

<pre><code>public class BillingTests {
Vehicle vehicle = new Vehicle(""Renault"", Vehicle.SEDAN);
Rental rental = new Rental(vehicle, 100, 100, false);
@Test
public void StatementCheck() {
    Customer customerBilling = new Customer(""Virgin Gates"");
    rental = new Rental(vehicle,rental.getMileage(), rental.getDaysRented(), 
                        rental.isLate());
    double expected = customerBilling.getTotalMilage(rental);
    assertEquals(102.1, expected, 10.0);
}
</code></pre>

<p>}</p>
",https://stackoverflow.com/questions/47908411/unit-testing-using-junit-without-arguments,"['java', 'unit-testing', 'junit']",292,TRUE,1,1
Unit testing in syntax not working,"<p>I have been trying to learn cmocka to perform unitest. After looking at various examples on internet, I am confused as to how I should do unit testing, specifically I am unable to understand following syntax:</p>

<pre><code>static int functionname(void **state) {
 // What should I write here??
 return 0;
}
</code></pre>

<p>I am unable to understand Why void ** state is being used and what does it signifies. I am doing unittesting on circular buffer to check whether it is full, how should I do it? Till now I have written the uni test for c mocka as follows:</p>

<pre><code>static int CBfull(void **state) {
    if(bufffull=1)
    failcount++;
    else passcount++;
}
</code></pre>
",https://stackoverflow.com/questions/46958207/unit-testing-in-syntax-not-working,"['c', 'cmocka']",34,FALSE,1,0
Directory not found while unit testing,"<p>When I execute my test case, it fails for path within my machine which doesn't exist and I am getting below error:</p>

<blockquote>
  <p>System.IO.DirectoryNotFoundException: Could not find a part of the
  path 'C:\Data1'.</p>
</blockquote>

<p>Do I need some kind of fake/mock here to pass the test case or do we have other way to do this?</p>

<p><strong>Class</strong></p>

<pre><code>public class DemoCls
{
    public void Execute()
    {
        string dataFolder = @""C:\\Data1"";
        foreach (string X in Directory.EnumerateFiles(dataFolder, ""test"" + ""*.xml""))
        {
        }
    }
}
</code></pre>

<p><strong>Test Case</strong></p>

<pre><code>[TestClass()]
public class DemoClsTests
{
    [TestMethod()]
    public void ExecuteTest()
    {
        var X = new DemoCls();
        X.Execute();
    }
}
</code></pre>
",https://stackoverflow.com/questions/44300478/directory-not-found-while-unit-testing,"['c#', 'unit-testing', 'directory']",3000,TRUE,1,2
unit testing django ModelFormset clean methods,"<p>What is the best way to unit test the validation/clean part of a Django ModelFormset? My formset has a clean method that does some validation based on the values of its forms and I want to have a unit test for it. Generified code look like this:</p>

<pre><code>class AForm(ModelForm):
    a = ChoiceField(choices=CHOICES)
    b = FloatField()

    def __init__(self, *args, **kwargs):
       super(AForm, self).__init__(*args, **kwargs)

    class Meta:
       model = AModel
       fields =['a', 'b']


class AFormset(BaseInlineFormSet):

    def clean(self):
       # Some logic to validate relationships between the forms       
</code></pre>

<p>But while testing the form is trivial: <code>form = AForm(formdata)</code> and then verifying its validity or errors based on the data. I'm having trouble writing tests for the formset.</p>

<p>I've tried: </p>

<pre><code>    formset = AFormset()
</code></pre>

<p>And using <code>modelformset_factory</code></p>

<pre><code>Formset = modelformset_factory(AModel, AForm, formset=AFormset, fields=('a', 'b'))
formset = Formset(formdata)
</code></pre>

<p>with various combinations of arguments and mocks (instance, queryset). But I always get errors related to model foreign or primary keys. One example: </p>

<pre><code>Error Traceback (most recent call last):
 File ""/tests/test_forms.py"", line 62, in test_validation formset = Formset(formdata)
 File ""lib/python2.7/site-packages/django/forms/models.py"", line 853, in __init__
self.instance = self.fk.rel.to()
AttributeError: 'AFormset' object has no attribute 'fk'
</code></pre>

<p>What am I missing? Is there an easier way to instantiate a formset with a dictionary of data and have it run its <code>clean</code> method? Should I just test the view that the form is used in? (In the views I'm using the form and formset with the <a href=""https://github.com/AndrewIngram/django-extra-views"" rel=""nofollow noreferrer"">Django Extra Views</a> package)</p>
",https://stackoverflow.com/questions/42029559/unit-testing-django-modelformset-clean-methods,"['python', 'django', 'forms', 'unit-testing']",678,TRUE,1,1
Effort (EF Unit Testing) giving errors,"<p>I am trying to do unit testing on some classes that reply on an Entity Framework DB Context. For help, I managed to find a library called Effort, which seems to be a little old, and not very well documented, but it seems to work, and seems to be quite popular.</p>

<p>I am trying to use a CSV data loader.</p>

<p>When doing a <code>ToArray()</code> I receive an exceptions saying <code>Sequence contains no matching element</code>.</p>

<p>Any ideas on what I might be doing incorrectly? Or if not a different library I might want to give a chance?</p>

<p>A few snippets:</p>

<pre><code>[Table(""SEC_USER"")]
public class SecUser {
    [Key][Column(""USERID"")]
    public int UserId { get; set; }

    [Column(""USERNAME"")]
    public string UserName { get; set; }
}
</code></pre>

<p>DB Context:</p>

<pre><code>public class MusketeerDbContext : DbContext
{
    public virtual IDbSet&lt;IbsCommunity&gt; Communities { get; set; }
    public virtual IDbSet&lt;IbsFunctionLinkLocation&gt; Functionlinklocations { get; set; }
    public virtual IDbSet&lt;IbsInstance&gt; Instances { get; set; }
    public virtual IDbSet&lt;SecUser&gt; Users { get; set; }
    public virtual IDbSet&lt;IbsFieldType&gt; FieldTypes { get; set; }
    public virtual IDbSet&lt;IbsLink&gt; Links { get; set; }
    public virtual IDbSet&lt;IbsFieldFll&gt; FieldFlls { get; set; }
    public virtual IDbSet&lt;IbsFieldValue&gt; FieldValues { get; set; }

    public MusketeerDbContext() : base(""name=EGS.My.MySettings.Conn"") { }
    public MusketeerDbContext(DbConnection connection) : base(connection, true) { }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema(""SA"");
        modelBuilder.Conventions.Add(new FunctionConvention(typeof(OracleFunctions)));

        modelBuilder.Entity&lt;IbsFieldValue&gt;()
            .HasMany(fv =&gt; fv.InstancesFieldValues)
            .WithMany(i =&gt; i.InstancesFieldValues)
            .Map(mm =&gt;
            {
                mm.MapLeftKey(""FIELDVALUEID"");
                mm.MapRightKey(""INSTANCEID"");
                mm.ToTable(""IBS_INSTANCEFIELDVALUE"");
            });
    }
}

public static class OracleFunctions
{
    [Function(FunctionType.BuiltInFunction, ""TO_CHAR"")]
    public static string ToChar(this int value) =&gt; Function.CallNotSupported&lt;string&gt;();

    [Function(FunctionType.BuiltInFunction, ""TO_NCHAR"")]
    public static string ToChar(this string value) =&gt; Function.CallNotSupported&lt;string&gt;();
}
</code></pre>

<p>The SEC_USER.csv:</p>

<pre><code>USERID,USERNAME
""1"",""Jonathan""
</code></pre>

<p>The Test:</p>

<pre><code>var path = @""C:\...\CSVs"";
var dataLoader = new Effort.DataLoaders.CsvDataLoader(path);
var context = Effort.DbConnectionFactory.CreateTransient(dataLoader);
db = new MusketeerDbContext(context);
var users = db.Users.ToArray();
</code></pre>

<p>System.InvalidOperationException:</p>

<pre><code>Message: ""Sequence contains no matching element""
InnerException: null
StackTrace:
    at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
    at System.Data.Entity.Utilities.DbProviderManifestExtensions.GetStoreTypeFromName(DbProviderManifest providerManifest, String name)
    at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.ConfigureColumn(EdmProperty column, EntityType table, DbProviderManifest providerManifest)
    at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.Configure(EdmProperty column, EntityType table, DbProviderManifest providerManifest, Boolean allowOverride, Boolean fillFromExistingConfiguration)
    at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.&lt;&gt;c__DisplayClass4.&lt;Configure&gt;b__3(Tuple`2 pm)
    at System.Data.Entity.Utilities.IEnumerableExtensions.Each[T](IEnumerable`1 ts, Action`1 action)
    at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.Configure(IEnumerable`1 propertyMappings, DbProviderManifest providerManifest, Boolean allowOverride, Boolean fillFromExistingConfiguration)
    at System.Data.Entity.ModelConfiguration.Configuration.Types.StructuralTypeConfiguration.ConfigurePropertyMappings(IList`1 propertyMappings, DbProviderManifest providerManifest, Boolean allowOverride)
    at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.ConfigurePropertyMappings(DbDatabaseMapping databaseMapping, EntityType entityType, DbProviderManifest providerManifest, Boolean allowOverride)
    at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Configure(EntityType entityType, DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
    at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.ConfigureEntityTypes(DbDatabaseMapping databaseMapping, ICollection`1 entitySets, DbProviderManifest providerManifest)
    at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
    at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
    at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
    at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
    at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
    at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
    at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
    at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
    at System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator()
    at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable&lt;TResult&gt;.GetEnumerator()
    at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
    at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
    at Igs.Musketeer.DbRepository.Tests.SecurityRepositoryTest..ctor() in C:\Users\me\Source\Repos\Musketeer\Igs.Musketeer.DbRepositoryTests\SecurityRepositoryTest.cs:line 21
</code></pre>
",https://stackoverflow.com/questions/43893911/effort-ef-unit-testing-giving-errors,"['c#', 'entity-framework', 'unit-testing', 'effort']",698,TRUE,1,1
Unit testing a REST Get Api,"<p>I am testing a GET rest api that I have written that when called with appropriate parameters returns a response like below :</p>

<pre><code>[
  {
    ""baseline"": ""tableName"",
    ""targetDataSource"": ""tableName"",
    ""status"": ""EQUALS""
  },
  {
    ""baseline"": ""tableName"",
    ""targetDataSource"": ""tableName"",
    ""status"": ""EQUALS""
  }
]
</code></pre>

<p>Here is how I am unit testing it :</p>

<pre><code>   String jsonResponse = ""["" + ""{\""baseline\"" : \""tableName\"",\""targetDataSource\"": \""tableName\"",""
        + ""\""status\"": \""EQUALS\""},{ \""baseline\"": \""tableName\"",\""targetDataSource\"": \""tableName\"",""
        + ""\""status\"": \""EQUALS\""}"" + ""]"";
    List&lt;MatchingResult&gt; obj;
    ObjectMapper MAPPER = new ObjectMapper();
    obj = MAPPER.readValue(jsonResponse, new TypeReference&lt;ArrayList&lt;HashMap&lt;String, String&gt;&gt;&gt;() {
    });

    when(matchingService.searchRowkeyAndMatch(Mockito.anyString())).thenReturn(obj);
    mockMvc.perform(get((MATCHING_GET_ENDPOINT), ""123"", ""2016-08-12 11:33:11"")).andExpect(status().isOk());
</code></pre>

<p>I am however receiving an Assertion Error. Status Expected&lt;200> but was &lt;404>.
I think I am doing it right way. Don't know what's going wrong.</p>

<p><code>MatchingResult</code> is my <code>dto</code> which is as follows :</p>

<pre><code>@Data
public class MatchingResult {
  String baseline;
  String targetDataSource;
  QueryResultStatusEnum status;
}
</code></pre>

<p>Here is my controller code:</p>

<pre><code>  @RequestMapping(method = RequestMethod.GET, value = ""/result/config/{date}"",
      produces = OneplatformMediaType.APPLICATION_JSON_UTF8_VALUE)
  @ApiOperation(value = ""get result from matchingengine"")
  @ApiResponses(value = {@ApiResponse(code = 400, message = ""Invalid input"")})
  public ResponseEntity&lt;List&lt;MatchingResult&gt;&gt; getMatchingStatus(
      @ApiParam(value = ""Name of the configuration"", required = true) 
      @RequestParam(""config"") String configName,
      @ApiParam(value = ""Date of the data"", required = true) @PathVariable(""date"") String date) {
    String rowkey =
        new StringBuilder().append(configName).append(""#"").append(""data"").append(""#"")
            .append(date).toString();
    List&lt;MatchingResult&gt; searchRowkey = matchingService.searchRowkeyAndMatch(rowkey);
    if (searchRowkey.isEmpty()) {
      throw NotFoundException.builder().entityNotFound()
      .details(""Rowkey not found."").build();
    }
    return new ResponseEntity&lt;&gt;(searchRowkey, HttpStatus.OK);

  }
</code></pre>

<p>And <code>MATCHING_GET_ENDPOINT</code> is </p>

<pre><code> MATCHING_GET_ENDPOINT = ""/dataverification/v1/matchingApi/result/config/{date}"";
</code></pre>

<p>Also, how can I verify one of the values of entities <code>baseline, targetDataSource and status</code> ?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/46380681/unit-testing-a-rest-get-api,"['java', 'rest', 'unit-testing', 'junit', 'mockito']",299,FALSE,0,0
AngularJS - Unit Testing Controllers and Services,"<p>I'm quite new to <em>unit testing</em> of AngularJS, and have been pulling my hair figuring things out. I am currently testing a simple controller that produces some outputs, which I need to unit test.</p>

<p><strong>controller</strong>: SummaryController</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>(function(app) {
  'use strict';

  function SummaryController($scope, $stateParams, $state, $interval, $payments, $cashierApp, $window, $banks, $prepaidcards, $flash, $player, $cookies, $rootScope, $filter) {
    // lots of stuff going on here, but I only need this part
    $scope.showQR = $payments.get('paymentoption').content.field_display_qrcode;
    // a basic assignment of a boolean value which I need to check if it is defined
  }
  app.controller('depositStatusCtrl', ['$scope', '$stateParams', '$state', '$interval', '$payments', '$cashierApp', '$window', '$banks', '$prepaidcards', '$flash', '$player', '$cookies', '$rootScope', '$filter', SummaryController]);
})(angular.module('cashierApp'));</code></pre>
</div>
</div>
</p>

<p><strong>spec (unit test)</strong>: controller.spec.js</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>'use strict';

describe('Cashier App: Deposit Status Page', function() {

  var service,
    ctrl,
    scope;

  beforeEach(module('cashierApp'));

  beforeEach(inject(function($rootScope, $controller, SummaryController) {
    scope = $rootScope.$new();
    mockSummaryCtrl = SummaryController;
    spyOn(mockSummaryCtrl, 'save').andCallThrough();
    firstController = $controller('depositStatusCtrl', {
      $scope: scope,
      SummaryController: mockSummaryCtrl
    });
  }));

  it('should check if qrcode display is enabled', function() {
    expect(scope.showQR).toBeDefined();
    // expect(scope.showQR).toBe(true);
    // expect(scope.showQR).toBe(false);
  });
});</code></pre>
</div>
</div>
</p>

<p>I've tried every possible approach I can find on the web, and this one I tried to use was based on an example <a href=""https://www.sitepoint.com/unit-testing-angularjs-services-controllers-providers/"" rel=""nofollow noreferrer"">here</a>.</p>

<p>I cannot get this to work at all. How do you <strong>properly</strong> test controllers and/or providers in AngularJS? When I run <code>karma start</code> (I'm using <strong><em>karma-jasmine</em></strong>, btw), I always get the same error of:</p>

<p><code>Error: [$injector:unpr] Unknown provider: SummaryControllerProvider &lt;- SummaryController</code></p>

<p><strong>EDIT</strong>: Here's my <strong>karma.conf.js</strong> just in case you need to know how I use my dependencies.</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>'use strict';

module.exports = function(config) {

  var configuration = {
    autoWatch: true,

    frameworks: ['jasmine'],

    files: [
      'node_modules/angular/angular.js',
      'node_modules/angular-mocks/angular-mocks.js',
      'node_modules/angular-ui-router/release/angular-ui-router.js',
      'bower_components/angular-carousel/dist/angular-carousel.js',
      'bower_components/angular-cookies/angular-cookies.js',
      'bower_components/angular-messages/angular-messages.js',
      'bower_components/ngclipboard/src/ngclipboard.js',
      'bower_components/angular-qrcode/angular-qrcode.js',
      'bower_components/angular-sanitize/angular-sanitize.min.js',
      'bower_components/ng-file-upload/ng-file-upload-all.min.js',
      'bower_components/ng-device-detector/ng-device-detector.min.js',
      'bower_components/re-tree/re-tree.min.js',
      'bower_components/angular-timer/dist/angular-timer.min.js',
      'bower_components/angular-touch/angular-touch.min.js',
      'bower_components/highlightjs/highlight.pack.min.js',
      'bower_components/moment/moment.js',
      'src/app/app.js',
      'src/app/core/cashier.core.js',
      'src/app/core/directives/modal/modal.js',
      'src/app/pages/deposit/deposit.js',
      'src/app/pages/withdrawal/withdrawal.js',
      'src/app/paymentoptions/alipaywap/alipaywap.js',
      'src/app/paymentoptions/alipaywap/alipaywap.confirm.js',
      'src/app/paymentoptions/astropay/astropay.js',
      'src/app/paymentoptions/atmotc/atmotc.js',
      'src/app/paymentoptions/atmotc/atmotc.confirm.js',
      'src/app/paymentoptions/banktransfer/banktransfer.js',
      'src/app/paymentoptions/banktransfer/banktransfer.confirm.js',
      'src/app/paymentoptions/bitcoin/bitcoin.js',
      'src/app/paymentoptions/bitcoinwithdrawal/bitcoinwithdrawal.js',
      'src/app/paymentoptions/debitcard/debitcard.js',
      'src/app/paymentoptions/lbtwithdrawal/lbtwithdrawal.js',
      'src/app/paymentoptions/prepaidcard/prepaidcard.js',
      'src/app/paymentoptions/qqpay/qqpay.js',
      'src/app/paymentoptions/unionpay/unionpay.js',
      'src/app/paymentoptions/wcnp/wcnp.js',
      'src/app/paymentoptions/wechat/wechat.js',
      'src/app/pages/deposit/deposit.status/deposit.status.controller.js',
      'src/app/pages/deposit/deposit.status/deposit.status.controller.spec.js'
    ],

    reporters: ['progress', 'coverage', 'junit'],

    ngHtml2JsPreprocessor: {
      stripPrefix: 'src/',
      moduleName: 'templates'
    },

    // browsers: ['PhantomJS','Chrome'],
    browsers: ['Chrome'],

    plugins: [
      'karma-chrome-launcher',
      'karma-phantomjs-launcher',
      'karma-angular-filesort',
      'karma-jasmine',
      'karma-ng-html2js-preprocessor',
      'karma-junit-reporter',
      'karma-coverage'
    ],

    junitReporter: {
      outputFile: 'target/unittest-results.xml',
      suite: ''
    },

    preprocessors: {
      'src/**/*.html': ['ng-html2js'],
      'src/**/*.js': ['coverage']
    },

    coverageReporter: {
      reporters: [{
          type: 'cobertura',
          dir: 'target/coverage/'
        },
        {
          type: 'html',
          dir: 'target/coverage/'
        }
      ]
    }
  };

  // This block is needed to execute Chrome on Travis
  // If you ever plan to use Chrome and Travis, you can keep it
  // If not, you can safely remove it
  // https://github.com/karma-runner/karma/issues/1144#issuecomment-53633076
  if (configuration.browsers[0] === 'Chrome' &amp;&amp; process.env.TRAVIS) {
    configuration.customLaunchers = {
      'chrome-travis-ci': {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    };
    configuration.browsers = ['chrome-travis-ci'];
  }

  config.set(configuration);
};</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/46111927/angularjs-unit-testing-controllers-and-services,"['angularjs', 'unit-testing']",221,FALSE,0,1
Error utilizing RealmDB while unit testing,"<p>I am writing a test for a ViewModel. The function in the ViewModel is this:</p>

<pre><code>public void discoverMovies(boolean showLoading) {
   // reset the states to initial states
   moviesLoading.set(showLoading);
   errorViewShowing.set(false);
   emptyViewShowing.set(false);

   mMoviesRepository.getPopularMovies(1)
           .observeOn(AndroidSchedulers.mainThread())
           .subscribeOn(Schedulers.io())
           .subscribeWith(new DisposableObserver&lt;List&lt;Movie&gt;&gt;() {
               @Override
               public void onNext(List&lt;Movie&gt; value) {
                   // show or hide empty view
                   boolean isEmpty = value == null || value.isEmpty();

                   if (!isEmpty) {
                        saveResponse(value);
                       movies.clear();
                       movies.addAll(value);
                   }
                   emptyViewShowing.set(isEmpty);
               }

               @Override
               public void onError(Throwable throwable) {
                   errorViewShowing.set(true);
                   moviesLoading.set(false);
                   emptyViewShowing.set(false);

                   errorString.set(getErrorMessage(throwable));
               }

               @Override
               public void onComplete() {
                   moviesLoading.set(false);
                   errorViewShowing.set(false);
               }
           });
}

private void saveResponse(final MovieResponse mainResponse) {
    Realm.getDefaultInstance().executeTransaction(new Realm.Transaction() {
      @Override public void execute(Realm realm) {
        RealmMovie realmMovie = realm.createObject(RealmMovie.class);
        realmMovie.setId(1);
        realmMovie.setMarvelResponse(new Gson().toJson(mainResponse));
      }
    });
}
</code></pre>

<p>And I test the function above in my test class like this:
Note: Everything works without the Realm aspect. I've confirmed that.</p>

<pre><code>@Test
public void getPopularMoviesWithoutError() {
    // given the following movies
    when(mMoviesRepository.getPopularMovies(PAGE)).thenReturn(Observable.just(MOVIES));

    // discover popular movies
    mMoviesViewModel.discoverMovies(true);

    // verify that the repository is called
    verify(mMoviesRepository).getPopularMovies(PAGE);

    // test that the loading indicator is hidden
    assertFalse(mMoviesViewModel.moviesLoading.get());

    // check that the empty view is hidden
    assertFalse(mMoviesViewModel.emptyViewShowing.get());

    // check that the error view is hidden
    assertFalse(mMoviesViewModel.errorViewShowing.get());

    assertTrue(mMoviesViewModel.movies.size() == MOVIES.size());
}
</code></pre>

<p>And it keeps on giving me <code>java.lang.IllegalStateException: Call</code>Realm.init(Context)<code>before calling this method.</code> How can I initialize Realm
to be available</p>
",https://stackoverflow.com/questions/43292105/error-utilizing-realmdb-while-unit-testing,"['android', 'junit', 'mockito', 'realm']",185,TRUE,-1,1
Unit testing NancyFX API - ConfigurableBootstrapper Exception,"<p>Im trying to get nunit test setup for my Nancy API.  I have a very simpLe end point:</p>

<pre><code>this.Get[""/""] = _ =&gt;
       {
           return Negotiate
               .WithModel("" API is running"")
               .WithStatusCode(HttpStatusCode.OK);
       };
</code></pre>

<p>When I try to test it with this test:</p>

<pre><code>this._browser = new Browser(with =&gt; {
           with.Module(new IndexModule());
       });

       var result = this._browser.Get(""/"", with =&gt; { with.HttpRequest(); });

       Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.OK));
</code></pre>

<p>I get ConfigurableBootstrapper Exception and with message of ""OhNoes"". </p>

<p>If I change the return to:</p>

<pre><code>return ""API is running"";
</code></pre>

<p>It works. I think I might be missing something in the test setup to allow the negotiated return. </p>

<p>Does anyone have an idea of what I'm doing wrong? Thanks.</p>
",https://stackoverflow.com/questions/44833912/unit-testing-nancyfx-api-configurablebootstrapper-exception,"['nunit', 'nancy']",237,TRUE,0,1
Array StringLog unit testing smallest method,"<p>I'm a new programmer and I am trying to pass this code through a unit test using the smallest method.</p>

<pre><code>// returns the first string in a lexicographic ordering of the log
public String smallest(){
    String smallest = log[0];

        for(int i= 0;i &lt;= lastIndex; i++){

            if(log[i].compareTo(smallest)&lt; 0){ //compare to smallest
                                               //known not log[i+1]

                smallest = log[i];

            } else {

                lastIndex++;
        }
        return smallest;
</code></pre>

<p>Here are my unit tests:</p>

<pre><code>public class Test_smallest {

 ArrayStringLog strLog;

@Before
public void setUp() throws Exception {      
    strLog = new ArrayStringLog(""My StringLog"",5);
}
/*
LinkedStringLog strLog;

@Before
public void setUp() throws Exception {      
    strLog = new LinkedStringLog(""My StringLog"");
}
*/
@Test
public void test_1Element() {
    strLog.insert(""string 1"");
    assertEquals(strLog.smallest(), ""string 1"");
}

@Test
public void test_3Elements_smallest_at_beginning() {
    strLog.insert(""string 1""); strLog.insert(""string 2"");
    strLog.insert(""string 3""); 

    assertEquals(strLog.smallest(), ""string 1"");
}

@Test
public void test_3Elements_smallest_in_middle() {
    strLog.insert(""string 2""); strLog.insert(""string 1"");
    strLog.insert(""string 3""); 

    assertEquals(strLog.smallest(), ""string 1"");
}

@Test
public void test_3Elements_smallest_at_end() {
    strLog.insert(""string 3""); strLog.insert(""string 2"");
    strLog.insert(""string 1""); 

    assertEquals(strLog.smallest(), ""string 1"");
}   

@After
public void tearDown() throws Exception {
}
</code></pre>

<p>My problem is this, it passes the 1 element, and elements at beginning tests, but fails the other two and I cannot figure out why. It should be stepping through the array comparing the current index the loop is on with the one next to it.</p>

<p>It throws the error expected:string 2, but was string 1, and the other for expected:string 3 but was string 1. I'm trying to find the smallest string in the array no matter the location. I don't understand why its expected to see string 2 or 3, when the assertEquals is looking for string 1.</p>
",https://stackoverflow.com/questions/42079803/array-stringlog-unit-testing-smallest-method,['java'],108,FALSE,0,1
Unit testing geofencing services in UWP,"<p>I have an app that shows a notification when I arrive somewhere, and I would like to have unit testing for it.  I searched around a bit, and couldn't find anything.  </p>

<ol>
<li>Can I do this?</li>
<li>Are there services out there for this?  </li>
<li>If not, what is the best way to do this?</li>
</ol>
",https://stackoverflow.com/questions/42024185/unit-testing-geofencing-services-in-uwp,"['c#', 'geolocation', 'location', 'uwp']",90,TRUE,0,1
Exclude IStringLocalizer/GetString in Unit testing,"<p>I use IstringLocalizer in controller in asp.net core to read shared resources . 
In a method i have :</p>

<pre><code>          foreach (var category in urlCategories)
        {
            if (category == _localizer.GetString(""CategoryWebshop"")) model.SelectedIndustries.Add(1);
            else if (category == _localizer.GetString(""CategoryStore"")) model.SelectedIndustries.Add(2);
            else if (category == _localizer.GetString(""CategoryWebsite"")) model.SelectedIndustries.Add(3);
            else if (category == _localizer.GetString(""CategoryService"")) model.SelectedIndustries.Add(4);
            else if (category == _localizer.GetString(""CategoryProduction"")) model.SelectedIndustries.Add(5);
            else if (category == _localizer.GetString(""CategoryTrade"")) model.SelectedIndustries.Add(6);
            else if (category == _localizer.GetString(""CategoryRestaurant"")) model.SelectedIndustries.Add(7);
            else if (category == _localizer.GetString(""CategoryRealEstate"")) model.SelectedIndustries.Add(8);
        }
</code></pre>

<p>In unit test GetString of localizer does not let the test to get 100% </p>

<p><a href=""https://i.stack.imgur.com/3OeWn.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/3OeWn.png"" alt=""enter image description here""></a></p>

<p>How can i fix the problem or skip/exclude that part from testing ?
Thanks</p>
",https://stackoverflow.com/questions/45353054/exclude-istringlocalizer-getstring-in-unit-testing,"['asp.net-mvc', 'unit-testing', 'asp.net-core', 'asp.net-core-mvc']",590,FALSE,0,0
Unit testing with header-only dependencies,"<p>Given a module which <code>#include</code>s some bloated headers with in-place definitions (like a header-only library), it's not quite easy to stub/mock/spy the dependencies from them. </p>

<p>I can see only one way: for each such header create its fake counterpart with only the definitions the module actually uses, and run each test with it's own compiler configuration where the include path's point to the fakes.</p>

<p>Am I missing something, is there a better way?</p>
",https://stackoverflow.com/questions/44049996/unit-testing-with-header-only-dependencies,"['c++', 'unit-testing']",443,FALSE,0,0
Unit testing for Combination of inputs,"<p>I am working for an application that has set of filter options to filter the data.</p>

<p>I want to test each combination of input for which my method is going to work. For example do I have to write Unit test for each combination like below:</p>

<pre><code>[TestClass]
public class Data_Should_Filter
{
    [TestMethod]
    public void _For_Category()
    {

    }

    [TestMethod]
    public void _For_Product_And_Category()
    {

    }

    [TestMethod]
    public void _For_Product_CreationDate()
    {

    }
}
</code></pre>

<p>Is there any way to test each combination of data with single test. I review the <a href=""https://www.stevefenton.co.uk/2015/04/combinatorial-and-pairwise-testing-with-nunit/"" rel=""nofollow noreferrer"">blog</a> for NUnit test. What are the possible way to achieve this kind of testing and which are the frameworks that support combination testing.</p>
",https://stackoverflow.com/questions/45187105/unit-testing-for-combination-of-inputs,"['c#', 'unit-testing', 'nunit', 'xunit']",2295,TRUE,0,4
Mysql2::Error: Table during unit testing,"<p>I had done a lynda.com tutorial that created a simlple cms using rails. I wanted to practice and expand my knowledge of rails a bit more by adding the unit testing. But every time I try to run any test I get a mysql error. One example of this is just trying to get the index on the public controller.</p>

<pre><code>#public_controller_test.br
test ""should get index"" do
  get public_index_url
  assert_response :success
end
</code></pre>

<p>It gives me the following error </p>

<pre><code>PublicControllerTest#test_should_get_index:
ActiveRecord::StatementInvalid: Mysql2::Error: Table 'simple_cms_test.users' doesn't exist: DELETE FROM `users`
</code></pre>

<p>If you need to look at more of the code it is available at
<a href=""https://github.com/trmccormick/rails_simple_cms"" rel=""nofollow noreferrer"">https://github.com/trmccormick/rails_simple_cms</a> Thanks for any assistance.</p>
",https://stackoverflow.com/questions/43191165/mysql2error-table-during-unit-testing,['ruby-on-rails'],457,TRUE,0,2
Configure theintern for unit testing only,"<p>I am trying to configure intern (<a href=""https://theintern.github.io"" rel=""nofollow noreferrer"">https://theintern.github.io</a>) for unit testing. </p>

<p>Here is my configuration</p>

<pre><code>define([ 'intern' ], function (intern) {
  // Return configuration for intern tests
  var config =  {
    basePath: '../',
    loaderOptions: {
      packages: [
                { name: 'app', location: 'app' },
                { name: 'jquery', location: 'bower_components/jquery/dist/jquery' },
                { name: 'underscore', location: 'bower_components/underscore/underscore' },
                { name: 'backbone', location: 'bower_components/backbone/backbone' }
      ]
    },
    suites: [
      'tests/mymodule'
    ],
    excludeInstrumentation: /^(?:tests|node_modules|bower_components|test)\//,
    loaders: {
      'host-node': 'requirejs',
      'host-browser': 'bower_components/requirejs/require.js',
    },
    reporters: [
      {id:'Console'}
    ]      

  };
  return config;
});
</code></pre>

<p>And I am receiving following error</p>

<pre><code>&gt; intern-runner config=tests/intern

Transformation error; return original code
TypeError: SourceNode is not a constructor
    at toSourceNodeWhenNeeded (C:\repo\my-app\node_modules\escodegen\escodegen.js:535:20)
    at generateIdentifier (C:\repo\my-app\node_modules\escodegen\escodegen.js:866:16)
    at CodeGenerator.Identifier (C:\repo\my-app\node_modules\escodegen\escodegen.js:2244:20)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
    at CodeGenerator.MemberExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:1910:28)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
    at CodeGenerator.MemberExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:1910:28)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
    at CodeGenerator.UpdateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2009:26)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
Transformation error; return original code
TypeError: SourceNode is not a constructor
    at toSourceNodeWhenNeeded (C:\repo\my-app\node_modules\escodegen\escodegen.js:535:20)
    at generateIdentifier (C:\repo\my-app\node_modules\escodegen\escodegen.js:866:16)
    at CodeGenerator.Identifier (C:\repo\my-app\node_modules\escodegen\escodegen.js:2244:20)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
    at CodeGenerator.MemberExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:1910:28)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
    at CodeGenerator.MemberExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:1910:28)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
    at CodeGenerator.UpdateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2009:26)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
Transformation error; return original code
TypeError: SourceNode is not a constructor
    at toSourceNodeWhenNeeded (C:\repo\my-app\node_modules\escodegen\escodegen.js:535:20)
    at generateIdentifier (C:\repo\my-app\node_modules\escodegen\escodegen.js:866:16)
    at CodeGenerator.Identifier (C:\repo\my-app\node_modules\escodegen\escodegen.js:2244:20)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
    at CodeGenerator.MemberExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:1910:28)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
    at CodeGenerator.MemberExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:1910:28)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
    at CodeGenerator.UpdateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2009:26)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
Transformation error; return original code
TypeError: SourceNode is not a constructor
    at toSourceNodeWhenNeeded (C:\repo\my-app\node_modules\escodegen\escodegen.js:535:20)
    at generateIdentifier (C:\repo\my-app\node_modules\escodegen\escodegen.js:866:16)
    at CodeGenerator.Identifier (C:\repo\my-app\node_modules\escodegen\escodegen.js:2244:20)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
    at CodeGenerator.MemberExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:1910:28)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
    at CodeGenerator.MemberExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:1910:28)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
    at CodeGenerator.UpdateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2009:26)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
Transformation error; return original code
TypeError: SourceNode is not a constructor
    at toSourceNodeWhenNeeded (C:\repo\my-app\node_modules\escodegen\escodegen.js:535:20)
    at generateIdentifier (C:\repo\my-app\node_modules\escodegen\escodegen.js:866:16)
    at CodeGenerator.Identifier (C:\repo\my-app\node_modules\escodegen\escodegen.js:2244:20)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
    at CodeGenerator.MemberExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:1910:28)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
    at CodeGenerator.MemberExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:1910:28)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
    at CodeGenerator.UpdateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2009:26)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
Transformation error; return original code
TypeError: SourceNode is not a constructor
    at toSourceNodeWhenNeeded (C:\repo\my-app\node_modules\escodegen\escodegen.js:535:20)
    at generateIdentifier (C:\repo\my-app\node_modules\escodegen\escodegen.js:866:16)
    at CodeGenerator.Identifier (C:\repo\my-app\node_modules\escodegen\escodegen.js:2244:20)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
    at CodeGenerator.MemberExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:1910:28)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
    at CodeGenerator.MemberExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:1910:28)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
    at CodeGenerator.UpdateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2009:26)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
Transformation error; return original code
TypeError: SourceNode is not a constructor
    at toSourceNodeWhenNeeded (C:\repo\my-app\node_modules\escodegen\escodegen.js:535:20)
    at generateIdentifier (C:\repo\my-app\node_modules\escodegen\escodegen.js:866:16)
    at CodeGenerator.Identifier (C:\repo\my-app\node_modules\escodegen\escodegen.js:2244:20)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
    at CodeGenerator.MemberExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:1910:28)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
    at CodeGenerator.MemberExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:1910:28)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
    at CodeGenerator.UpdateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2009:26)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
Transformation error; return original code
TypeError: SourceNode is not a constructor
    at toSourceNodeWhenNeeded (C:\repo\my-app\node_modules\escodegen\escodegen.js:535:20)
    at generateIdentifier (C:\repo\my-app\node_modules\escodegen\escodegen.js:866:16)
    at CodeGenerator.Identifier (C:\repo\my-app\node_modules\escodegen\escodegen.js:2244:20)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
    at CodeGenerator.MemberExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:1910:28)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
    at CodeGenerator.MemberExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:1910:28)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
    at CodeGenerator.UpdateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2009:26)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
Transformation error; return original code
TypeError: SourceNode is not a constructor
    at toSourceNodeWhenNeeded (C:\repo\my-app\node_modules\escodegen\escodegen.js:535:20)
    at generateIdentifier (C:\repo\my-app\node_modules\escodegen\escodegen.js:866:16)
    at CodeGenerator.Identifier (C:\repo\my-app\node_modules\escodegen\escodegen.js:2244:20)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
    at CodeGenerator.MemberExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:1910:28)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
    at CodeGenerator.MemberExpression (C:\repo\\node_modules\escodegen\escodegen.js:1910:28)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
    at CodeGenerator.UpdateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2009:26)
    at CodeGenerator.generateExpression (C:\repo\my-app\node_modules\escodegen\escodegen.js:2427:28)
ReferenceError: __cov_YGSj0arNmIBnXUo5NAKQbw is not defined
  at Object.&lt;anonymous&gt;  &lt;node_modules\digdug\NullTunnel.js:9:1&gt;
  at Module._compile  &lt;module.js:570:32&gt;
  at Object.Module._extensions.(anonymous function) [as .js]  &lt;node_modules\istanbul\lib\hook.js:107:24&gt;
  at Module.load  &lt;module.js:487:32&gt;
  at tryModuleLoad  &lt;module.js:446:12&gt;
  at Function.Module._load  &lt;module.js:438:3&gt;
  at Module.require  &lt;module.js:497:17&gt;
  at require  &lt;internal\module.js:20:19&gt;
  at Object.load  &lt;node_modules\intern\browser_modules\dojo\node.ts:56:11&gt;
  at Object.&lt;anonymous&gt;  &lt;node_modules\requirejs\bin\r.js:1347:28&gt;
npm ERR! Test failed.  See above for more details.
</code></pre>

<p>How can I configure theintern only for unit testing?</p>
",https://stackoverflow.com/questions/45665945/configure-theintern-for-unit-testing-only,"['javascript', 'unit-testing', 'intern']",48,FALSE,0,1
Wicket unit testing Translations.utils not found,"<p>I started recently developing in wicket and wondered how to set the wicket application in the unit test itself. I am currently using the wicket 6.8 Core.
4.1.2 for the unit test.</p>

<p>I am wondering how to set the Locale on the application.
Also actually creating the test application in a good way. 
What i'm trying to achieve is a test to see if a set of strings can be returned which are loaded from a translation file.</p>

<pre><code> //from the Class.
 public Class Information(){

     public Information(){}

     public String getInfo(){
       return TranslationUtil.getTranslation(""RandomFieldNameTobeTranslated"");
     }
 }
</code></pre>

<p>Unit Test:</p>

<pre><code>import org.junit.Before;
import org.junit.Test;

public class InformationTest(){
    @Before
    public void setup() throws Exception(){
      //needs to be setup in someway it can be used by the test.
        tester = new WicketTester();
        WebApplication web = tester.getApplication();
        web.usesDeploymentConfig();
        web.configure();
        web.initApplication();
        Session.get().setLocale(new Locale(""en_us""));
    }

    @Test
    public test(){
       Information information = new Information();
       assertEquals(""Foo is Foo"", ""Foo"", information.getInfo() );
    }
}
</code></pre>

<p>The unit test will run the code and get a unable to find property.
This is just a basic test, describing the issue.</p>

<pre><code>java.util.MissingResourceException: 
Unable to find property: 'RandomFieldNameTobeTranslated'. Locale: null, style: null
</code></pre>

<p>Tried some variations with the initialization and config. But i'm too inexperienced to know how to initialize wicket on the right way for the development unit testing.</p>

<p><strong>Questions:</strong></p>

<ol>
<li><p>how can I initialize wicket so it can find the locale in the session?</p></li>
<li><p>how to redirect wicket to the correct translation file?</p></li>
</ol>

<p>The production version works, but I want to build a unit test and it seemed to require the 'application'. It can be mocked but as a last resort as this is used in allot of locations , I rather want to test 'value equals value'.</p>
",https://stackoverflow.com/questions/42003271/wicket-unit-testing-translations-utils-not-found,"['java', 'unit-testing', 'junit', 'wicket', 'wicket-6']",125,TRUE,0,1
JavaScript unit testing with external module,"<p>I am working on an existing node project where the code structure for most of the js files looks something like following. </p>

<pre><code>    var mod1 = require(""mod1"");
    var mod2 = require(""mod2"");
    var modn = require(""moden"");


    function func1(data, callback) {
        // Do some validation with data etc.. 
        // Use one or more imported modules here 

    }

    function func2(data, callback) {
        // Do some validation with data etc.. 
        // Use one or more imported modules here 

    }


    exports.func1 = func1
    exports.func2 = func2 
</code></pre>

<p>How can unit test func1, while not being dependent on the imported modules? How can I mock/stub them? 
I come from the Java world so I am familiar with the mocking concepts, but here I am not sure how can I mock the globally declared module imports using require. </p>

<p>Currently we are using nodeunit for the unit testing purpose, but it tests very small part of the code. </p>

<p>I am reading about simon.js and testdouble but not sure how to use them to mock the global variables. </p>

<p>Any help/direction is appreciated. </p>
",https://stackoverflow.com/questions/44933762/javascript-unit-testing-with-external-module,"['javascript', 'node.js', 'unit-testing', 'nodeunit']",356,FALSE,0,1
generalise unit testing for private method,"<p>I have a private method where I do all my validation and this method takes a generic object as input parameter. This private method is called by 10 public methods passing the specific object which is the subclass of the generic object mentioned the parameter list of the private method.</p>

<p>How do I write a generic test suite for testing the private method and then invoke this method by all the 10 different public methods so that I do not duplicate the validation in each of the public test methods.</p>

<p>I am using testng and mockito for testing.</p>
",https://stackoverflow.com/questions/45011823/generalise-unit-testing-for-private-method,"['java', 'unit-testing', 'mockito', 'testng']",108,TRUE,-1,2
Angular Unit testing with Jasmine / Karma,"<p>I'm trying to write a unit test script for custom directive with jasmine  and karma.</p>

<p>Current application is Angular 1.28; Issue is above code not running properly. Can anyone help/guide me that where i'm making mistake; or how to write unit test case for custom directives. Any suggestions or help will be greatly appreciated, thanks.</p>

<p><em>Directive as below</em>:</p>

<pre><code>angular.module('phone.filter', [])
    .directive('phoneField', ['$filter', function ($filter) {
      var phoneFilter = $filter('phoneFilter'),
        reversePhone = $filter('reversePhone');
      return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {
          var formatter = value =&gt; phoneFilter(value),
            parser = function (value) {
              var formatted = reversePhone(value);
              element.val(phoneFilter(formatted));
              //prevents a phone number from being all zeros
              ngModel.$setValidity('phone', /^(?!0{10})(\d{10})?$/.test(value.replace(/\D/g, '')))
              return formatted;
            }
          ngModel.$formatters.push(formatter);
          return ngModel.$parsers.unshift(parser);
        }
      };
    }]).filter('phoneFilter', function () {
      return function (value) {
        var len, val;
        if (value) {
          val = value.toString().replace(/\D/g, '');
          len = val.length;
          if (len &lt; 4) {
            return val;
          } else if ((3 &lt; len &amp;&amp; len &lt; 7)) {
            return (val.substr(0, 3)) + '-' + (val.substr(3));
          } else if (len &gt;= 7) {
            return (val.substr(0, 3)) + '-' + (val.substr(3, 3)) + '-' + (val.substr(6));
          }
        }
        return value;
      };
    }).filter('reversePhone', function () {
      return (value = '') =&gt; value.replace(/\D/g, '').substr(0)
    })
</code></pre>

<p><strong><em>Test scripts as below:</em></strong></p>

<pre><code>import chai, { expect } from 'chai'
// import { createElement } from '../helpers/directive-testing-helper'
/* import { stub } from 'sinon'

chai.use(require('sinon-chai'))
*/
const module = angular.mock.module
describe('Phone Field validation directive (phoneField)', () =&gt; {
    let $rootScope,
        $compile;

    beforeEach(() =&gt; module('pru.com.components.phone.filter'))

    beforeEach(inject((_$rootScope_, _$compile_) =&gt; {
        $rootScope = _$rootScope_;
        $compile = _$compile_;
    }))

    it('should not have all zeros', () =&gt; {
        $rootScope.phone = ""0002345678""
        let element = $compile('&lt;input type=""text"" name=""phoneNumber"" phone-field="""" value=""0002345678"" ng-model=""""&gt;')($rootScope);
        $rootScope.$digest();
        chai.expect(new RegExp(/phone-field/)).match(element.html()).to.be.true;
    });
})
</code></pre>
",https://stackoverflow.com/questions/45798732/angular-unit-testing-with-jasmine-karma,"['javascript', 'angularjs', 'unit-testing', 'jasmine', 'karma-coverage']",233,FALSE,0,0
Unit testing of thread synchronization (lock),"<p>I'm working on multithread app and there is part of code which sholud be run only by one thread same time. Nothing complicated. I use lock to synchronize it. It's working in life system but I would like to write unit test to check if only one thread is in the critical section. I wrote one, it was working but it stops :)
I can't figure out how to write a test it in proper way. I use NSubstitute to create mocks.</p>

<p>Class to test:</p>

<pre><code>public interface IMultiThreadClass
{
    void Go();
}
public class Lock02 : IMultiThreadClass
{
    private readonly IProcessor _processor;
    private readonly string _threadName;

    private static readonly object Locker = new Object();

    public Lock02(IProcessor processor, string threadName)
    {
        _processor = processor;
        _threadName = threadName;
    }

    public void Go()
    {
        //critical section
        lock (Locker)
        {
            _processor.Process(_threadName);
        }
    }
}
</code></pre>

<p>Test:</p>

<pre><code>[TestMethod()]
public void Run_Test()
{
    //Only one thread should run Processor.Process, but we allow max 2 threads to catch locking erorrs
    SemaphoreSlim semaphore = new SemaphoreSlim(1, 2);

    //Semaphore to synchronize asserts
    SemaphoreSlim synchroSemaphore = new SemaphoreSlim(0, 1);

    IProcessor procesor = Substitute.For&lt;IProcessor&gt;();
    procesor.When(x =&gt; x.Process(Arg.Any&lt;string&gt;())).Do(y =&gt;
    {
        //increment counter to check if method was called
        Interlocked.Increment(ref _counter);

        //release synchro semaphore
        synchroSemaphore.Release();

        //stop thread and wait for release
        semaphore.Wait();
    });

    Lock02 locker1 = new Lock02(procesor, ""1"");
    Lock02 locker2 = new Lock02(procesor, ""2"");
    Lock02 locker3 = new Lock02(procesor, ""3"");

    Task.Run(() =&gt; locker1.Go());
    Task.Run(() =&gt; locker2.Go());
    Task.Run(() =&gt; locker3.Go());

    //ASSERT
    //Thread.Sleep(1000);
    synchroSemaphore.Wait();
    Assert.AreEqual(1, _counter);

    semaphore.Release(1);
    synchroSemaphore.Wait();
    Assert.AreEqual(2, _counter);

    semaphore.Release(1);
    synchroSemaphore.Wait();
    Assert.AreEqual(3, _counter);

    semaphore.Release(1);
}
</code></pre>
",https://stackoverflow.com/questions/43143275/unit-testing-of-thread-synchronization-lock,"['c#', 'multithreading', 'unit-testing']",2226,TRUE,0,1
Mock boto3 calls for unit testing,"<p>We have a class which looks like this:</p>

<pre><code>import boto3
import json
import time
import sys

def stop_instances_python(instanceId):
    ec2_client = boto3.client('ec2', region_name='us-east-1')
    while True:
        try:
            ec2_client.stop_instances(InstanceIds=[instanceId])
            print ""EC2 instance: "" + instanceId + "" stopped""
            break
        except Exception, e:
            if ('RequestLimitExceeded' in str(e)):
                print ""Request throttled. Sleeping for 15s""
                time.sleep(15)
                res = ec2_client.describe_instances(InstanceIds=[instanceId])
                print ""instance state: "" + res['Reservations'][0]['Instances'][0]['State']['Name']
                try:
                    ec2_client.stop_instances(InstanceIds=[instanceId])
                    print ""EC2 instance: "" + instanceId + "" stopped"" ## Unable to test this
                except Exception, e:
                    if ('RequestLimitExceeded' in str(e)):
                        print ""Request throttled again. Sleeping for 10s""
                        time.sleep(10)
                    else:
                        print str(e)
                        sys.exit(1)
            else:
                print str(e)
                sys.exit(1)
</code></pre>

<p>We want to write unit test cases for this class. We used <code>moto</code> and <code>mock</code> to test most of the lines. We are unable to test the line with comment: <code># Unable to test this</code>. This is because every time stop request is sent, it is getting throttled. Our test case file looks as below:</p>

<pre><code>from moto import mock_ec2
from moto import mock_sts
from mock import patch
import botocore
import boto3
import mock
from botocore.exceptions import ClientError

orig = botocore.client.BaseClient._make_api_call

def mock_throttling(self, operation_name, kwarg):
    if operation_name == 'StopInstances':
        parsed_response = {
            'Error': {'Code': '500', 'Message': 'RequestLimitExceeded'}}
        raise ClientError(parsed_response, operation_name)
    return orig(self, operation_name, kwarg)

def mock_throttling_side_effect(self, operation_name, kwarg):
    mock_api = mock.Mock()
    parsed_response = {'Error': {'Code': '500', 'Message': 'RequestLimitExceeded'}}
    if operation_name == 'StopInstances':
        mock_api.side_effect = [
            ClientError(parsed_response, operation_name),
            orig(self, operation_name, kwarg)
        ]
        mock_api()       
    return orig(self, operation_name, kwarg)

class TestEC2StopInstances:
    @mock_ec2
    @mock_sts
    @patch('time.sleep', return_value=None)
    def test_ec2_lambda_handler(self, patched_time_sleep):
        from StopInstancesPython import stop_instances_python
        client = boto3.client('ec2', region_name='us-east-1')
        response = client.run_instances(ImageId='ami-1234567', MinCount=1, MaxCount=1)
        instanceId = response['Instances'][0]['InstanceId']
        with patch(
                'botocore.client.BaseClient._make_api_call',
                new=mock_throttling_side_effect):
            stop_instances_python(instanceId)
</code></pre>

<p>We tried using both <code>mock_throttling</code> and <code>mock_throttling_side_effect</code>. When we use <code>mock_throttling</code>, the <code>StopInstances</code> API always throws RequestLimitExceeded exception (which is the expected behavior).
When we use <code>mock_throttling_side_effect</code>, the instance gets stopped in the first <code>StopInstances</code> API call and also throws the RequestLimitExceeded exception and continues in the infinite loop.</p>

<p>Could someone guide us on how to test all lines of this code?</p>
",https://stackoverflow.com/questions/47930893/mock-boto3-calls-for-unit-testing,"['python', 'unit-testing', 'amazon-web-services', 'mocking']",4881,FALSE,0,0
Code coverage percentage in unit testing,"<p>I have a class, having 3 methods(in python) .</p>

<pre><code>class MyClass:
    def A(self):
          .......
    def B(self):
         ........
    def C(self):
         ........
</code></pre>

<p>I have written unit test case for only one method A. This unit test covers each line of the method A. That is we don't have any if...else or any branching constructs. </p>

<p>What would  be the code coverage percentage? </p>

<p>Again if I write another unit test case for 2nd method of the class covering all lines.  What would be the code coverage percentage now? </p>
",https://stackoverflow.com/questions/43395968/code-coverage-percentage-in-unit-testing,"['python', 'asp.net', '.net', 'unit-testing']",3298,TRUE,0,1
Inject mock HttpServletResponse during unit testing,"<p>Question first: How can I inject a mock (or real?) HttpServletResponse during my unit tests for CXF JAX-RS service endpoints?</p>

<p>Example of how our services are setup (note I have no control/authority to alter non-test structures):</p>

<pre><code>package services.example;

import org.springframework.http.MediaType;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;

@RestController
@Path(""/base"")
@Produces(MediaType.APPLICATION_JSON_VALUE);
public class ExampleService {

  @Autowired
  SomeInjectedService injectedService;

  @POST
  @Path(""/endpoint"")
  public Object testEndpoint(Object exampleInput, @Context HttpServletResponse response) {
    if (exampleInput.someMethod != null) {
      // Exception thrown here during tests, response is null!!!
      response.setStatus(301);
      return exampleInput;
    }

    return new injectedService.returnOutputFromInput(exampleInput);
  }
}
</code></pre>

<p>Test class:</p>

<pre><code>package test.services.example

// A gazillion imports.  Mockito, JUnit, Hamcrest, Javax.ws.rs, org.apache.cxf, Jackson providers.

public class testExampleService {

  @Mock
  private HttpServletResponse mockResponse; // Should I do this?

  @Mock
  SomeInjectedService mockInjectionService;

  @InjectMocks
  ExampleService service = new ExampleService();

  @Before
  public void setUpStuff() {
    MockitoAnnotations.initMocks(this);

    JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
    sf.setResourceClasses(ExampleService.class);

    List&lt;Object&gt; providers = new ArrayList&lt;Object&gt;;
    JacksonJsonProvider provider = new JacksonJsonProvider();
    providers.add(provider);

    sf.setProviders(providers);

    sf.setResourceProvider(ExampleService.class, new SingletonResourceProvider(service, true));
    sf.setAddress(""local://someuri"");

    // This is where I'm trying to set up my injected Response context.  Help?
    sf.setInvoker(new Invoker() {
      Invoker jarsInvoker = new JAXRSInvoker();

      @Override
      public Object invoke(Exchange exchange, Object o) {
        // What goes in here?  I've seen an example for setting a mock
        // Request context, but no for a Response.  Here's my current 
        // (broken) attempt to do this...
        exchange.getInMessage().put(AbstractHTTPDestination.HTTP_RESPONSE, mockResponse);
        return jarsInvoker.invoke(exchange, o);
      }
    });
  }

  @Test
  public void testEndpointShouldReturn301() {
    List&lt;Object&gt; providers = new ArrayList&lt;Object&gt;();
    JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider();
    providers.add(provider);

    WebClient client = WebClient.create(""local://someuri"", providers);
    WebClient.getConfig(client)
             .getRequestContext()
             .put(LocalConduit.DIRECT_DISPATCH, Boolean.TRUE);

    // Exception thrown here, Response context doesn't get injected!
    client.path(""/base/endpoint"");
    SomeTestObject obj = new SomeTestObject();
    Response response = client.type(MediaType.APPLICATION_JSON).post(obj);

    // Never gets run because an exception was thrown :(
    assertThat(response.getStatus(), is(301));
  }

}
</code></pre>

<p>It's possible that I'm doing a couple things wrong here, but I'm hoping that I just need the right ""magic"" going in inside my custom Invoker in order to properly inject an HttpServletResponse to my endpoint.  I'll note that on my endpoints that do not have an injected Context, tests work correctly (when I remove my custom invoker bit).</p>
",https://stackoverflow.com/questions/43282577/inject-mock-httpservletresponse-during-unit-testing,"['java', 'jax-rs', 'mockito', 'cxf', 'junit4']",2745,TRUE,0,1
Does SystemC unit testing need forking?,"<p>I am starting with using SystemC, and studying example mentioned in 
<a href=""https://stackoverflow.com/questions/4923292/using-existing-unit-test-frameworks-with-systemc"">Using existing unit test frameworks with SystemC</a></p>

<p>I do not really understand why forking is required, especially when one fork only waits the other. Is there something in the kernel that needs such multi-threading (especially the event handling)? (in other words: do I need this type of handling ONLY when I need concurrent testing, or also in the more simple cases)</p>

<p>Another question that in the linked answer I see the logo at the beginning</p>

<pre><code> SystemC 2.2.0 --- Feb 24 2011 15:01:50
        Copyright (c) 1996-2006 by all Contributors
                    ALL RIGHTS RESERVED
Running main() from gtest_main.cc
</code></pre>

<p>while in my case the logo is at the end of the output</p>

<pre><code>Running main() from gtest_main.cc
[==========] Running 0 tests from 0 test cases.
[==========] 0 tests from 0 test cases ran. (0 ms total)
[  PASSED  ] 0 tests.
Hello World.

        SystemC 2.3.1-Accellera --- Mar 28 2017 21:08:36
        Copyright (c) 1996-2014 by all Contributors,
        ALL RIGHTS RESERVED
</code></pre>

<p>It is just because of the different versions, or it is an expected timely behavior?</p>
",https://stackoverflow.com/questions/43145530/does-systemc-unit-testing-need-forking,['systemc'],239,TRUE,0,2
Populate HTTPContext.Item in MVC unit testing,"<p>We have the following lines in one of the functions in the MVC controller.</p>

<pre><code>public ActionResult EditEmp(int eId = 0)
{
    EPermission ePermission =  (EPermission)HttpContext.Items[""empPermission""];
}
</code></pre>

<p>In my unit test, I am calling this controller to test.</p>

<pre><code>public void TestMethod1()
{
   var result = eController.EditEmp(10) as ViewResult;
}
</code></pre>

<p>My test case fails because there is no value in the <code>HttpContext</code> for <code>empPermission</code> during the runtime.</p>

<p>We are wondering how can we populate the <code>HttpContext.Items</code> with a value so it can pick up during the runtime.  We have look for some examples in mock, but not any luck so far.</p>
",https://stackoverflow.com/questions/43690199/populate-httpcontext-item-in-mvc-unit-testing,"['asp.net-mvc', 'mocking', 'httpcontext']",409,FALSE,0,1
react unit testing with jest debug,"<p>I am writing some unit tests for react using jest and it fails at one point.  I want to debug the unit tests and I try the following</p>

<p><a href=""https://facebook.github.io/jest/docs/troubleshooting.html"" rel=""nofollow noreferrer"">https://facebook.github.io/jest/docs/troubleshooting.html</a></p>

<p>However on the first run itself </p>

<pre><code>node --debug-brk ./node_modules/.bin/jest --runInBand
</code></pre>

<p>I get the following error</p>

<pre><code>node_modules\.bin\jest:2
basedir=$(dirname ""$(echo ""$0"" | sed -e 's,\\,/,g')"")
          ^^^^^^^
SyntaxError: missing ) after argument list
</code></pre>

<p>Any ideas anyone?</p>
",https://stackoverflow.com/questions/45498536/react-unit-testing-with-jest-debug,"['reactjs', 'debugging', 'jestjs']",1050,TRUE,0,2
Unit Testing a GPS detecting method,"<p>I really need help with unit testing a method. I simply don't really understand how to go about it. This method is called when pressing a navigation button that centers on your location on my android app. Let's call it buttnav.</p>

<pre><code>public void GPSDetector() { 
    AlertDialog.Builder build = new AlertDialog.Builder(
            mapFragment.getActivity());
    build
            .setTitle(""GPS Detection Services"")
            .setMessage(""GPS is disabled in your device. Enable it?"")
            .setCancelable(false)
            .setPositiveButton(""Enable GPS"",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(i);
                        }
                    });
    build.setNegativeButton(""Cancel"",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            });
    AlertDialog alert = build.create();
    alert.show();
}
</code></pre>

<p>Map fragment being an entity instantiated as a SupportMapFragment on onActivityCreated inside of a fragment as such:</p>

<pre><code>mapFragment = (SupportMapFragment) getChildFragmentManager()
            .findFragmentById(R.id.map);
</code></pre>

<p>I'm pretty lost and couldn't find much documentation referring to unit testing within Android core functionality. I'm trying to use Junit. I tried espresso but it doesn't encompass Android core functionality views.</p>
",https://stackoverflow.com/questions/42787006/unit-testing-a-gps-detecting-method,"['java', 'unit-testing', 'android-studio', 'junit', 'junit4']",191,FALSE,-1,1
Perl Unit Testing -- is the subroutine testable?,"<p>I have been reading up and exploring on the concept of unit testing and test driven development in Perl. I'm looking into how I can incorporate the testing concepts into my development. Say I have a Perl subroutine here:</p>

<pre><code>sub perforce_filelist {

    my ($date) = @_;

    my $path = ""//depot/project/design/...module.sv"";
    my $p4cmd = ""p4 files -e $path\@$date,\@now"";

    my @filelist = `$p4cmd`; 

    if (@filelist) {
        chomp @filelist;
        return @filelist;
    }
    else {
        print ""No new files!""
        exit 1;
    }
}
</code></pre>

<p>The subroutine executes a Perforce command and stores the output of that command (which is a list of files) in to the <code>@filelist</code> array. Is this subroutine testable? Would testing if the returned <code>@filelist</code> is empty useful? I am trying to teach myself how to think like a unit test developer.</p>
",https://stackoverflow.com/questions/44198069/perl-unit-testing-is-the-subroutine-testable,"['perl', 'unit-testing', 'tdd', 'subroutine']",1155,TRUE,7,3
Unit Testing Angular Js with Jasmine,"<p>I have a piece of angular code that does a post request to the cloudant, returns a response, builds a URL with it and does a get request with the same. The get request returns an array buffer through which i build a PDF file to be rendered in the front end.</p>

<p>Could someone please let advice me on how to unit test this as unit testing along with rest API is a new territory for me . PFB my code</p>

<pre><code>$scope.viewfile = function(name) {
                $http({
                method : 'POST',
                url : '/search/searchFiles',    
                data : {'currentdropdownvalue' : name} ,
            }).
            success(function(data){ 
                if (!angular.isUndefined(data.docs[0])){
                $scope.file = data.docs[0]._id;
                var fileUrl = $scope.cloudantUrl + $scope.file +""/""+ $scope.file;       
                $http.get(fileUrl {responseType:'arraybuffer'})
                .success(function (response) {
                     var file = new Blob([response], {type: 'application/pdf'});
                     var fileURL = URL.createObjectURL(file);
                     $scope.content = $sce.trustAsResourceUrl(fileURL);
                     $scope.contentType = ""application/pdf"";
                     $scope.contentWords = null;
                }).error(function(data){
                    console.log(""Printing Error inside Post of view "" , data);
                }); 
                }
                     else{
                        $scope.content = null;
                        $scope.contentWords = ""File is not available for the selected Name"";
                     }



            }).
            error(function(data){ 
                console.log(""Printing Error inside view  "" , data);
            });
        };
    }
</code></pre>
",https://stackoverflow.com/questions/46366678/unit-testing-angular-js-with-jasmine,"['javascript', 'angularjs', 'rest', 'unit-testing', 'jasmine']",102,FALSE,0,1
React.js unit testing with d3-npm,"<p>I am creating a forced graph in react using d3 for npm.
The graph is created using the follows:</p>

<p><a href=""https://medium.com/walmartlabs/d3v4-forcesimulation-with-react-8b1d84364721"" rel=""nofollow noreferrer"">https://medium.com/walmartlabs/d3v4-forcesimulation-with-react-8b1d84364721</a></p>

<p>I am trying to set up the testing environment as follows:
<a href=""https://ericnish.io/blog/how-to-unit-test-react-components-with-enzyme/"" rel=""nofollow noreferrer"">https://ericnish.io/blog/how-to-unit-test-react-components-with-enzyme/</a></p>

<p>the problem is when I run the test I keep on getting </p>

<pre><code> Cannot read property 'matches' of undefined
at C:\workspace\project\node_modules\d3-selection\build\d3-selection.js:83:15
</code></pre>

<p>I have imported d3 in my graph component as follows:</p>

<pre><code>import * as d3 from 'd3';
</code></pre>

<p>It seems like when I import my react component in my test file, it freaks out. This is my test file:</p>

<pre><code>import React from 'react'
import {shallow, mount, render} from 'enzyme'
import {expect} from 'chai'
import * as d3 from 'd3';
import graph from '.../components/graph ';
describe('graph ', () =&gt; {
  it('should have the main svg', (done) =&gt; {
    const wrapper = shallow(&lt;graph /&gt;);
    expect(wrapper.find('svg')).to.have.length(1);
    done()
  })
})
</code></pre>

<p>How can I get rid of this error?</p>
",https://stackoverflow.com/questions/46917042/react-js-unit-testing-with-d3-npm,"['node.js', 'reactjs', 'unit-testing', 'd3.js', 'd3-force-directed']",302,FALSE,0,1
Unit testing strongly named class library,"<p>I am writing some unit tests for a class library which is typically published as a nuget package internally. I have added a class library to the solution (which only has the one other class library project until now) and added references to NUnit and the project to be tested.</p>

<p>I added a very simple test which creates an instance of one of the classes and it fails immediately with this error:</p>

<pre><code>Strong name signature could not be verified.  The assembly may have been
tampered with, or it was delay signed but not fully signed with the correct
private key.
</code></pre>

<p>The class library which provides the body of the nuget package code has a <code>key.snk</code> file and a <code>CompanyNamePublic.snk</code> file.</p>

<p>What do I need to do to be able to add unit tests to this solution?</p>
",https://stackoverflow.com/questions/43896519/unit-testing-strongly-named-class-library,"['c#', 'nunit', 'strong-named-key']",242,FALSE,0,0
EventKit Unit testing - stall on main thread,"<p>I need to create multiple calendar events for Unit Test in Xcode. The call needs to be async, because of the access rights request:</p>

<pre><code> eventStore.requestAccess(to: EKEntityType.event, completion: {
            granted, error in
             //create events
     })
</code></pre>

<p>This is done in <code>setUp()</code> in a loop to create multiple events. The problem is that not all the completion blocks are done when the test starts running. I have implemented the <code>waitForExpectations()</code> method, to make it wait till the counter meets the requirements. But I get the following error message: </p>

<pre><code>Stall on main thread
</code></pre>

<p>Here is the relevant code - setUp:</p>

<pre><code>override func setUp()
{

    super.setUp()

    if let filepath = Bundle.main.path(forResource: ""MasterCalendar"", ofType: ""csv"") {
        do {

            let expectationCreation = expectation(description: ""create events expectation"")
            let contents = try String(contentsOfFile: filepath)
            //print(contents)

            let testDataArray = importTestDataArrayFrom(file: contents)



            createTestEvents(testDataArray: testDataArray)
                { (eventsArray) in
                    self.testEvents = eventsArray
                    print(""finished creating events"")
                    expectationCreation.fulfill()
            }

            waitForExpectations(timeout: 10.0) { (error) in
                if error != nil {
                    XCTFail((error?.localizedDescription)!)
                }
            }


        } catch {
            print(""contents could not be loaded"")
        }
    } else {
        print(""example.txt not found!"")
    }
}
</code></pre>

<p>Create events:</p>

<pre><code>func createTestEvents(testDataArray: [TestData], completion: @escaping (_ eventArray: [EKEvent]) -&gt; Void) -&gt; Void
{
    let eventStore = EKEventStore()
    var testEvents = [EKEvent]()
    var index = 0

    for testDataEvent in testDataArray
    {
        eventStore.requestAccess(to: EKEntityType.event, completion: {
            granted, error in

            if (granted) &amp;&amp; (error == nil) {
                print(""===GRATNED, CREATING EVENT-"", index)
                index += 1
                let event = EKEvent.init(eventStore: eventStore)
                event.title = testDataEvent.combinedFields
                event.startDate = Date()
                event.endDate = Date()
                event.isAllDay = false


                var attendees = [EKParticipant]()
                for i in 0 ..&lt; 5 {
                    if let attendee = self.createParticipant(email: ""test\(i)@email.com"") {
                        attendees.append(attendee)
                    }
                }
                event.setValue(attendees, forKey: ""attendees"")

                try! eventStore.save(event, span: .thisEvent)
                let meetingObj = Parser.parse(calendarEvent: event)
                testDataEvent.meeting = meetingObj

                testEvents.append(event)

                if(testEvents.count == testDataArray.count){

                    completion (testEvents)
                }
            }
        })
    }
}
</code></pre>
",https://stackoverflow.com/questions/45479026/eventkit-unit-testing-stall-on-main-thread,"['swift', 'xcode', 'unit-testing', 'eventkit', 'ekeventkit']",600,FALSE,7,0
Unit Testing Azure Functions and .csx Files,"<p>Azure Functions abstract plenty of dependencies like queue libraries and Azure Tables. So from a Unit Test dependencies mocking perspective, there is less coding effort (and accordingly less maintenance).</p>

<p>Assuming we are developing locally using Visual Studio 2015</p>

<ul>
<li>How can I unit test (not interested in integration test) a single Azure Function? Preferably in xUnit, however, any framework would do.</li>
<li>How can I unit test a function in a .csx file in general?</li>
</ul>
",https://stackoverflow.com/questions/42513577/unit-testing-azure-functions-and-csx-files,"['unit-testing', 'azure', 'visual-studio-2015', 'xunit', 'azure-functions']",2169,TRUE,7,1
Angular 4 HTTP Jasmine Unit Testing,"<p>I'm a noob at unit testing, I've been trying to create a mock unit test for a HTTP call to an end point.</p>

<p>My Service:</p>

<pre><code>this.http.get('endPoint',options).subscribe((res: Response) =&gt; { 
  let result = res.json();
  let obj = new ForgotPasswordResponse(res..........);
  return obj;
})
</code></pre>

<p>My Unit Test</p>

<pre><code> it('should get response from server', (done) =&gt; {
    let responseObj:ForgotPasswordResponse = {
        messageEN: 'dsadsada',
        messageFR: 'dsada',
        headerEN: 'dsada',
        headerFR: 'dsada',
        pageTarget: 'dsada',
        args: 'dsa',
        systemLogs: 'dsada',
        msgCode: 'dsa',
        type: 'dsa'
    }

    let signinid = '1234';
    let lang = 'EN';

    backend.connections.subscribe((connection: MockConnection) =&gt; {
        let options = new ResponseOptions({ body: responseObj });
        connection.mockRespond(new Response(options));

        expect(connection.request.url).toEqual('./api/v1/forgot/1234/EN');
        expect(connection.request.method).toEqual(RequestMethod.Get);
    });

    subject.initPwdResetFlow(signinid, lang).subscribe((response) =&gt; {
        expect(response).toEqual(responseObj);
        done();
    });
});
</code></pre>

<p>My response object is of type <code>ForgotPasswordResponse</code>, with the appropriate props. However, when I run the test, I get a failure -- it only says Type Error thrown.</p>
",https://stackoverflow.com/questions/44578173/angular-4-http-jasmine-unit-testing,"['javascript', 'angular', 'unit-testing', 'jasmine', 'karma-runner']",1166,FALSE,-1,1
Unit testing conditional in ref (ReactJS),"<p>I've run into a problem where I need to set indeterminate on a <code>input[type=""checkbox""]</code>, as <code>indeterminate</code> isn't a html property I need to do this in the <code>DOM</code>, reading other answers I've decided to go with  <code>ref</code></p>

<p>Code looks like:</p>

<pre><code>&lt;input
  id={props.id}
  checked={props.checked}
  type=""checkbox""
  ref={(input) =&gt; {
    if (input) {
      input.indeterminate = props.indeterminate
    }
  }}
/&gt;
</code></pre>

<p>Works fine, the problem is I can't think of a way to unit test the <code>if (input)</code> conditional</p>

<p>I am using Jest / Enzyme as my test frameworks</p>

<p>Any ideas?</p>
",https://stackoverflow.com/questions/45338936/unit-testing-conditional-in-ref-reactjs,"['javascript', 'unit-testing', 'reactjs', 'jestjs', 'enzyme']",150,FALSE,0,0
Unit testing ngComponentRouter - Angular 1.5.x,"<p>I am trying to build basic unit tests for an Angular 1.5 with the purpose of A) practicing unit testing, and B) familiarizing myself with component-based development in Angular 1.5.x. I'm trying to unit test a simple component, but I keep getting the following message:</p>

<blockquote>
  <p>Error: [$injector:modulerr] Failed to instantiate module app due to:</p>
  
  <p>Error: [$injector:modulerr] Failed to instantiate module
  ngComponentRouter due to: </p>
  
  <p>Error: [$injector:nomod] Module
  'ngComponentRouter' is not available! You either misspelled the module
  name or forgot to load it. If registering a module ensure that you
  specify the dependencies as the second argument.</p>
</blockquote>

<p>I'd like a little guidance on how to inject this specific dependency/module into a unit test. This is the code I have:</p>

<p><strong>app.js</strong></p>

<pre><code>(function(){
    ""use strict"";

    const app = angular.module(""app"", [""ngComponentRouter""])

    app.value(""$routerRootComponent"", ""componentApp"");
})();
</code></pre>

<p><strong>component-app.component.js</strong></p>

<pre><code>(function(){
    ""use strict"";

    angular.module(""app"").component(""componentApp"", {
        templateUrl: ""/javascripts/component-app.component.html"",
        controller: [""$router"", function($router){
            $router.config([
                { path: ""/users"", component: ""usersComponent"", name: ""Users"" },
                { path: ""/**"", redirectTo: [""Users""]}
            ]);
        }]

    });
})();
</code></pre>

<p><strong>component-app.component.spec.js</strong></p>

<pre><code>describe(""componentApp component"", function(){
    beforeEach(module(""app""));

    var $componentController, componentApp;

    beforeEach(inject(function($injector){
        $componentController = $injector.get(""$componentController"");
        componentApp = $componentController(""componentApp"", { $scope: {}});
    }));

    it(""componentApp component is defined"", function(){
        expect(componentApp).toBeDefined();
    }); 
});
</code></pre>
",https://stackoverflow.com/questions/43054910/unit-testing-ngcomponentrouter-angular-1-5-x,"['javascript', 'angularjs', 'unit-testing', 'angularjs-1.6', 'ngcomponentrouter']",104,TRUE,0,1
Unit Testing with Realm: Undeclared Type,"<pre><code>import RealmSwift

// MARK: Class

/// The DataPoint object representation
public class DataPoint: Object {

  // MARK: - Variables

  /// The latitude of the point
  dynamic var lat: Double = 0
  /// The longitude of the point
  dynamic var lng: Double = 0
  /// The accuracy of the point
  dynamic var accuracy: Double = 0

  /// The added point date of the point
  dynamic var dateAdded: Date = Date()
  /// The last sync date of the point
  dynamic var lastSynced: Date?
}
</code></pre>

<p>So I have the above simple Realm Object Class. I want to unit test something, irrelevant to Realm at the moment. Originally I have set the target membership of this class to every target (App, UnitTests, UITests) but after I got the duplicate class error I found out that realm requires only the main app target. So I did and I did make the class Public as it was suggested. But now the unit test target does not even build with the error: </p>

<pre><code>Undeclared Type 'DataPoint'
</code></pre>

<p>Any ideas how can I actually solve this error without adding the class to all the target memberships of course. </p>
",https://stackoverflow.com/questions/46152449/unit-testing-with-realm-undeclared-type,"['swift', 'unit-testing', 'realm']",463,TRUE,0,1
Should beginner programmers use unit testing?,"<p>I have been learning PHP for several months now. It is not my first language, but it is the first language I have tried to use for real-life projects. Currently I am writing a web application that can be easy for experienced programmers but is rather hard for me. And the more I write it, the more I realise that I spend more time pressing buttons and entering inputs to test my code than actually writing code. I have heard about unit testing (and other kind of testing) and it got me wondering: does my simple web application need any automated testing or is it a complete overkill? Is unit testing something a beginner can learn or is it only something experienced programmers use correctly? And since I am writing a web application, can all its code be tested or only the small logic parts?</p>

<p>Thank you.</p>
",https://stackoverflow.com/questions/45987614/should-beginner-programmers-use-unit-testing,"['unit-testing', 'testing', 'phpunit', 'tdd', 'codeception']",188,TRUE,0,1
Unit testing issue c# object getProperties,"<p>I have a c# class that gets object property names.</p>

<pre><code>public class MyClass
{
    public int Id { get; set; }
    public int Name { get; set; }
}

public class Parser&lt;T&gt;
{
    public IEnumerable&lt;string&gt; Parse(T item)
    {
        const BindingFlags flag = BindingFlags.Instance | BindingFlags.Public;

        return item.GetType().GetProperties(flag).Select(p =&gt; p.Name);
    }
}
</code></pre>

<p>I want to test this methot.</p>

<pre><code>    [Test]
    public void TestMethod()
    {
        var parser = new Parser&lt;MyClass&gt;();
        var names = parser.Parse(new MyClass()).ToArray();

        Assert.IsTrue(names[1] == ""Name"");
    }
</code></pre>

<p>But this throws an exception <strong>System.NullReferenceException</strong>. But I put breakpoint and see <code>names</code> array have two items.</p>

<p><code>Assert.IsTrue(names[1] == ""Name"");</code> row throws exception. But is has 2 items.</p>

<blockquote>
  <p>Test 'M:ParsProejct.TestsClass.TestMethod.' failed: Object reference
  not set to an instance of an object.</p>
</blockquote>
",https://stackoverflow.com/questions/45049584/unit-testing-issue-c-object-getproperties,"['c#', 'unit-testing', 'nunit']",16,FALSE,0,0
Unit testing threads with dependency injection,"<p>I have a c# program that uses Castle Windsor for dependency injection. The program listens to a RabbitMQ queue.  In the thread that is created I call a class named FileProcessor which in turn calls another class named FileFixer.</p>

<p>I do not pass the container from Castle Windsor to the rest of the program.</p>

<p>How can I tell the program which implementation I am using in the bootstrapper so that I can create a new instance of a class that implements IFileProcessor and IFileFixer in the thread?</p>

<p>I was thinking of using a factory, but am not sure how to put it together.</p>
",https://stackoverflow.com/questions/47417605/unit-testing-threads-with-dependency-injection,"['c#', 'multithreading', 'unit-testing', 'dependency-injection', 'factory']",51,FALSE,0,0
Unit testing RxJava composition and functionality,"<p>In my architecture I use a class called a UseCase to compose an observable and subscribe to it. The UseCase takes in one or more Repositories in the constructor and has an ""execute"" method that is responsible for creating the observable and subscribing to it.</p>

<p>Here's a simple example;</p>

<pre><code>public class MyUseCase {
    IRepoA mRepoA;
    IRepoB mRepoB;
    Scheduler mScheduleOn;
    Scheduler mObserveOn;
    CompositeSubscription mCompositeSubscription;

    public MyUseCase(IRepoA repoA, IRepoB repoB, Scheduler subscribeOn, Scheduler observeOn, CompositeSubscription compositeSubscription) {
    mRepoA = repoA;
    mRepoB = repoB;
    mSubscribeOn = subscribeOn;
    mObserveOn = observeOn;
    mCompositeSubscription = compositeSubscription;
}

public Observable execute(Observable observable, Subscriber subscriber) {
    if (observable == null) {
                     observable = mRepoA
                    .fetchLoginPreference()
                    .map(new Func1&lt;LoginPreference, String&gt;() {
                        @Override
                        public String call(LoginPreference loginPreference) {
                            return loginPreference.getActivationCode();
                        }
                    })
                    .flatMap(new Func1&lt;String, Observable&lt;List&lt;RegistrationField&gt;&gt;&gt;() {
                        @Override
                        public Observable&lt;List&lt;RegistrationField&gt;&gt; call(String s) {
                            return mRepoB.fetchRegistrationFields(s);
                        }
                    })
    }
    mCompositeSubscription.add(observable.subscribeOn(mSubscribeOn).observeOn(mObserveOn).subscribe(observable));
    return observable;
}
}
</code></pre>

<p>It seems to me that there are a couple of things to test here and I'm wondering what the best way to go about it is.</p>

<p>1) I want to test that the observables are composed correctly. That is, I want to make sure that .map(), .flatMap(), and .cache() were called. The way I've done this before is to use mocks and verify that those methods were called on the mocks. So for instance, repoA.fetchLoginPreference() would return a mock observable and then I can verify that the mock has .map() called on it and so forth.</p>

<p>2) I want to test that the observable actually behaves correctly when I subscribe to it. To test this what I've done is to use real Observables instead of mocks. So when repoA.fetchLoginPreference() gets called I'd have it return Observable.just(mockLoginPreference). Then I use a TestSubscriber to subscribe to the resulting observable and verify that mocks are called correctly from within the Func1 callbacks.</p>

<p>Does this seem like a sane way of doing things? I end up being able to test both that the composition is correct and verify that when the observable is subscribed to it actually does what it's supposed to but I'm curious if there's a better way.</p>
",https://stackoverflow.com/questions/42728859/unit-testing-rxjava-composition-and-functionality,"['unit-testing', 'rx-java']",489,TRUE,0,1
Unit Testing email Sign Up Firebase,"<p>I'm just getting stuck into a Firebase project and brushing up on my unit testing skills.</p>

<p>I use a unit test to check that the correct outcome occurs when entering an invalid email/password in sign up. This is fine.</p>

<p>I also want to check that the correct thing happens when I enter valid details. However I do not wish for a new account to be created everytime I run this test, it would just litter up my Firebase database.</p>

<p>Any ideas for a solution? Perhaps, calling a delete user method straight after? This seems a bit OTT though.</p>
",https://stackoverflow.com/questions/46885340/unit-testing-email-sign-up-firebase,"['ios', 'swift', 'unit-testing', 'firebase', 'firebase-authentication']",589,TRUE,0,2
Unit testing bluebird promise bind function,"<p>I have the following function that uses <code>bind</code> to bind a context to the <code>then</code> chains. When i try and test it, it throws </p>

<pre><code>  TypeError: redisClient.hgetallAsync(...).bind is not a function


myFunc() {
    let self = this;

    return redisClient.hgetallAsync('abcde')
      .bind({ api: self })
      .then(doStuff)
      .catch(err =&gt; {
        // error
      });
  }
</code></pre>

<p>Test</p>

<pre><code>let redisClient = { hgetallAsync: sinon.stub() };

describe('myFunc', () =&gt; {
    beforeEach(() =&gt; {
      redisCLient.hgetallAsync.resolves('content!');
    });

    it('should do stuff', () =&gt; {
      return myFunc()
        .should.eventually.be.rejectedWith('Internal Server Error')
        .and.be.an.instanceOf(Error)
        .and.have.property('statusCode', 500);
    });
  });
</code></pre>
",https://stackoverflow.com/questions/45617898/unit-testing-bluebird-promise-bind-function,"['unit-testing', 'bluebird', 'sinon', 'sinon-chai']",185,FALSE,0,1
Randomly generate trees for unit testing,"<p>I want to randomly generate trees (not BST) for unit testing of my code. I have tried it in a number of ways but somehow after generation of 3 -4 trees there is an exception or code goes into infinite loop. I am using random numbers for edges and node values.<br>
I have also tried queue approach where I fill up the queue with random numbers and then dequeue nodes and randomly select the old node from the existing items in the queue and then connect this new node.</p>

<p>Does anybody know how to do this in C# in more better and succinct way?</p>

<p>EDIT </p>

<pre><code>public class Tree
{
    public Node Root { get; private set; }
    public readonly Dictionary&lt;long, Node&gt; Nodes = new Dictionary&lt;long, Node&gt;();
    public readonly Dictionary&lt;string, long&gt; SumDictionary = new Dictionary&lt;string, long&gt;();

    public readonly Dictionary&lt;long, long&gt; FDictionary = new Dictionary&lt;long, long&gt;
    {
        {0, 1},
        {1, 1}
    };


    public long Query(long n)
    {
        long s = 0;
        Dfs();

        for (int i = 1; i &lt;= n; i++)
        {
            for (int j = i; j &lt;= n; j++)
            {
                var lvalue = GetLValue(i, j);

                if (i != j)
                {
                    lvalue *= 2;
                }

                s += lvalue;

                if (s &gt;= Mod)
                {
                    s %= Mod;
                }

            }
        }

        return s;
    }

    private long GetLValue(int a, int b)
    {
        var key = string.Format(""{0}-{1}"", a, b);

        if (SumDictionary.ContainsKey(key))
        {
            return Fvalue(SumDictionary[key]);
        }

        var aKey = string.Format(""{0}-{1}"", 1, a);
        var bKey = string.Format(""{0}-{1}"", 1, b);

        var sumA = SumDictionary[aKey];
        var sumB = SumDictionary[bKey];

        var lca = Lca(a, b);

        if (lca != a &amp;&amp; lca != b)
        {
            return Fvalue(sumA + sumB - SumDictionary[string.Format(""{0}-{1}"", lca, lca)]);
        }


        long bigSum, smallSum;

        if (sumA &gt; sumB)
        {
            bigSum = sumA;
            smallSum = sumB;
        }
        else
        {
            bigSum = sumB;
            smallSum = sumA;
        }

        var sumAtoB = bigSum - (smallSum - Nodes[smallSum].Value);

        return Fvalue(sumAtoB);
    }

    public void AddNode(long a, long b)
    {
        Node nodea, nodeb;
        if (Nodes.ContainsKey(a))
        {
            nodea = Nodes[a];
        }
        else
        {
            nodea = new Node { Value = a };
            Nodes.Add(a, nodea);
        }

        if (Nodes.ContainsKey(b))
        {
            nodeb = Nodes[b];
        }
        else
        {
            nodeb = new Node { Value = b };
            Nodes.Add(b, nodeb);
        }

        nodea.ReachableNodes.Add(b, nodeb);
        nodeb.ReachableNodes.Add(a, nodea);

        if (Root == null)
        {
            Root = nodea;
        }
    }

    public long? Lca(int a, int b)
    {
        bool found = false;
        return TraverseForLca(Root, null, a, b, ref found);
    }

    private long? TraverseForLca(Node node, Node prev, long a, long b, ref bool found)
    {
        if (node == null)
        {
            return null;
        }

        if (node.Value == a)
        {
            return a;
        }

        if (node.Value == b)
        {
            return b;
        }


        long? f = null;

        foreach (KeyValuePair&lt;long, Node&gt; reachableNode in node.ReachableNodes)
        {
            var n = reachableNode.Value;

            if (prev != null &amp;&amp; n.Value == prev.Value)
            {
                continue;
            }

            long? lca = TraverseForLca(n, node, a, b, ref found);

            if (found)
            {
                return lca;
            }

            if (lca != null &amp;&amp; f == null)
            {
                f = lca;
            }
            else if (lca != null)
            {
                found = true;
                return node.Value;
            }
        }

        return f;
    }

    public void Dfs()
    {
        TravelForDfs(Root, null, 0);
    }

    private void TravelForDfs(Node node, Node prev, long recSum)
    {
        if (node == null)
        {
            return;
        }

        var key = string.Format(""{0}-{1}"", prev != null ? prev.Value : node.Value, node.Value);
        var iKey = string.Format(""{0}-{1}"", node.Value, node.Value);
        var weight = node.Weight;

        if (weight &gt;= Mod)
        {
            weight %= Mod;
        }


        if (!SumDictionary.ContainsKey(iKey))
        {
            SumDictionary.Add(iKey, weight);
        }

        weight = recSum + node.Weight;

        if (weight &gt;= Mod)
        {
            weight %= Mod;
        }

        foreach (KeyValuePair&lt;long, Node&gt; reachableNode in node.ReachableNodes)
        {
            var n = reachableNode.Value;

            if (prev != null &amp;&amp; n.Value == prev.Value)
            {
                if (!SumDictionary.ContainsKey(key))
                {
                    SumDictionary.Add(key, weight);
                }

                continue;
            }

            if (!SumDictionary.ContainsKey(key))
            {
                SumDictionary.Add(key, weight);
            }

            TravelForDfs(n, node, weight);
        }
    }

    public long Fvalue(long n)
    {
        if (n == 1 || n == 0)
        {
            return 1;
        }

        long a, b;

        if (FDictionary.ContainsKey(n - 1))
        {
            a = FDictionary[n - 1];
        }
        else
        {
            a = Fvalue(n - 1);

            if (!FDictionary.ContainsKey(n - 1))
            {
                FDictionary.Add(n - 1, a);
            }

        }

        if (FDictionary.ContainsKey(n - 2))
        {
            b = FDictionary[n - 2];
        }
        else
        {
            b = Fvalue(n - 2);

            if (!FDictionary.ContainsKey(n - 2))
            {
                FDictionary.Add(n - 2, b);
            }

        }


        if (!FDictionary.ContainsKey(n))
        {
            FDictionary.Add(n, a + b);
        }


        var s = a + b;
        if (s &gt;= Mod)
        {
            s %= Mod;
        }

        return s;

    }

}
</code></pre>
",https://stackoverflow.com/questions/45257909/randomly-generate-trees-for-unit-testing,['c#'],967,TRUE,0,1
Unit testing Flask app running under uwsgi,"<p>I’m relatively new to python and am looking for a pythonic way to handle this practice. </p>

<p>I’ve inherited a fairly trivial Python 2.7 Flask app that runs under uwsgi that I want to add some unit tests to. It does some initialization at indentation level 0 that is required when it’s running in uwsgi but needs to be skipped when under test.</p>

<p>I’m given to understand that often python apps use the </p>

<pre><code>if __name__ == '__main__':
</code></pre>

<p>pattern to isolate code that should run when the script is run on its own and should not run when it’s imported. In this case, however, both when the script is run under uwsgi and when the script is imported into the unit tests, <code>__name__</code> is the same; the name of the script, so I can’t use that to differentiate between uwsgi and unit-testing environments.</p>

<p>This sample code illustrates what I'm working with.</p>

<p>In the Flask application (flask_app.py):</p>

<pre><code>import logging
import bcrypt
from flask import Flask, jsonify, abort, make_response, request
from ConfigParser import SafeConfigParser

#  some initialization that only makes sense when running from the uwsgi context on the server
PARSER = SafeConfigParser()
PARSER.read('config.ini')
LOG_FILE = PARSER.get('General', 'logfile')

APP = Flask(__name__)

@APP.route('/', methods=['GET'])
def index
    ...

@APP.route('/&lt;p1&gt;/&lt;p2&gt;', methods=['PUT'])
def put(p1, p2):
    ...

if __name__ == '__main__':
    APP.run(debug = True, host='0.0.0.0')
</code></pre>

<p>In the unit tests (tests.py):</p>

<pre><code>import os
import unittest
from flask import json

from flask_app import APP

class FlaskAppTestCase(unittest.TestCase):

    def setUp(self):
        self.APP = APP.test_client()

    def test_GET(self):
        resp = self.APP.get('/')
        assert 'Some Html' in resp.data

    def test_PUT(self):
        resp = self.APP.put('/1/2')
        assert 'Got 1, 2' in resp.data

if __name__ == '__main__':
    unittest.main()
</code></pre>

<p>What I was thinking of doing was to move the initialization so that it only runs when flask_app is being executed by uwsgi and not when it's running via tests.py, perhaps by checking <strong>name</strong> and determining which path to execute based on that, but when I examine the output of print(<strong>name</strong>) either when running flask_app under uwsgi or by executing tests.py the output is ""flask_app"", so I can't seem to use that as a discriminator.</p>

<p>Is there an idiomatic way in python to handle this?</p>
",https://stackoverflow.com/questions/47945449/unit-testing-flask-app-running-under-uwsgi,"['python', 'unit-testing', 'flask']",1713,TRUE,6,1
Using assert raises unit testing in python,"<p>Currently I'm writing a unittest for my class function.</p>

<pre><code>def test_getitem(self):
    test1 = List(3)
    for i in range(3):
        test1.append(i)
    self.assertEqual(test1[2], 2)

    test1 = List(3)
    for i in range(3):
        test1.append(i)
    self.assertRaises(IndexError, test1[4])
</code></pre>

<p>the problem I'm having now is at the <code>self.assertRaises</code> part of my code. I'm not sure if that is how it's done but when I run the <code>unittest</code>, it produces an error <code>Index out of range</code>. By right, it should be ""OK"". </p>

<p><code>List</code> is my class and <code>List(3)</code> creates an array based list. so when i <code>test1.append(i)</code>, it is now <code>[0,1,2]</code>.</p>

<p><code>test1[2]</code> is a method of calling the <code>getitem</code> function in my class similar to <code>self[index]</code>. </p>

<p>I'm wondering if I'm assert raising correctly? <code>self.assertEqual</code> is fine.</p>
",https://stackoverflow.com/questions/46198244/using-assert-raises-unit-testing-in-python,"['python', 'unit-testing', 'exception']",3326,TRUE,6,2
What are Html fixtures for jasmine unit testing jquery/javascript code and unit testing for jsp pages?,"<p>Can anyone explain me what are html fixtures in simple language.I am starting and trying to jasmine unit test a jquery/javascript file which is implementing logic for the Jsp file on the front end.The whole project is java as back-end and javascript/jsp as front end.And also if anyone could explain if there is any way we can also unit test jsp code?</p>
",https://stackoverflow.com/questions/47823485/what-are-html-fixtures-for-jasmine-unit-testing-jquery-javascript-code-and-unit,"['javascript', 'jquery', 'maven', 'jsp', 'jasmine']",420,FALSE,1,0
unit testing a method that uses Assembly,"<p>I need to <code>xUnit</code> test a method that uses <code>Assembly</code>, specifically called with parameter <code>Assembly.GetEntryAssembly()</code>.</p>

<p>But unfortunately in unit test project, the entry assembly appears to be <code>testhost</code> not my test project. That way I'll not be able to search my test project. Does that mean I won't be able to test this method? or is the another way to go?</p>
",https://stackoverflow.com/questions/43242731/unit-testing-a-method-that-uses-assembly,"['c#', 'unit-testing', '.net-core']",2371,TRUE,6,1
Unit testing with private service injected using jasmine angular2,"<p>I have a problem trying to unit test an angular service. I want to verify that this service is properly calling another service that is injected into it.</p>

<p>Lets say I have this ServiceToTest that injects ServiceInjected:</p>

<p>ServiceToTest .service.ts</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>@Injectable()
export class ServiceToTest  {
    constructor(private _si: ServiceInjected) {}
    public init() {
      this._si.configure();
    }

}</code></pre>
</div>
</div>
</p>

<p>ServiceInjected.service.ts
<div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>@Injectable()
export class ServiceInjected {
    constructor() {}
    public configure() {
    /*Some actions*/
    }

}</code></pre>
</div>
</div>
</p>

<p>With these services, now I write my unit test: </p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>const serviceInjectedStub = {
  configure(): void {}
}


describe('ServiceToTest service Test', () =&gt; {
  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      providers: [ServiceToTest ,
        { provide: ServiceInjected, useValue: serviceInjectedStub }]
    });
  });
  
  it('should be initialize the service injected', inject([ServiceToTest],
    (tService: ServiceToTest) =&gt; {
      spyOn(serviceInjectedStub, 'configure');
      tService.init();
      expect(serviceInjectedStub.configure).toHaveBeenCalled();
    }));</code></pre>
</div>
</div>
</p>

<p>I expected my test to be positive, however I receive the following error:</p>

<p>Expected spy configure to have been called.</p>

<p>On the other hand, it works OK if I set the injected service public in this way:</p>

<pre><code>private _si: ServiceInjected by public si: ServiceInjected
</code></pre>
",https://stackoverflow.com/questions/47938424/unit-testing-with-private-service-injected-using-jasmine-angular2,"['angular', 'karma-jasmine', 'angular-services', 'injectable', 'spyon']",24245,TRUE,19,4
Real Unit Testing of SQLAlchemy in Flask,"<p>I'm searching web and SO for keys like ""Unit Test sqlalchemy"" but all answers involves creating real database (sqlite, postgres) to test it. It's not Unit Test when you create real things.</p>

<p>Creating sqlite DB is no different from creating file on disk but surprisingly people wish to mock only the latter. I've tried mocking db import using setUp and sys.modules and it works but it mocks too much and using models as testing objects is no trivial (mocks does not support all needed things like <strong>next</strong>)</p>

<p>Is there any technique to mock database behaviour (creating db, commits, queries) but still have access to models to do basic checks on them ? Maybe there is some library to mock only connection ?</p>
",https://stackoverflow.com/questions/44539816/real-unit-testing-of-sqlalchemy-in-flask,"['python', 'unit-testing', 'sqlalchemy']",4849,TRUE,5,1
Unit testing ES7 React components with Jest,"<p>How do you make Jest play nicely with ES7 initializers? I've searched far a wide on here and other sources, but didn't find anything conclusive.</p>

<p><code>.babelrc.js</code></p>

<pre><code>{
    ""env"": {
        ""development"": {
            ""presets"": [[""es2015"", { ""modules"": false }], ""react"", ""react-hmre""],
            ""plugins"": [
                ""transform-class-properties"",
                ""react-hot-loader/babel""
            ]
        },
        ""test"": {
            ""presets"": [""env"", ""react""],
            ""plugins"": [""transform-class-properties""]
        },
        ""production"": {
            ""presets"": [[""es2015"", { ""modules"": false }], ""react""],
            ""plugins"": [""transform-class-properties""]
        }
    }
}
</code></pre>

<p><code>package.json</code></p>

<pre><code>    {
    ""name"": ""demo"",
    ""version"": ""1.0.0"",
    ""main"": ""index.js"",
    ""license"": ""MIT"",
    ""private"": true,
    ""dependencies"": {
        ""react"": ""^15.5.4"",
        ""react-dom"": ""^15.5.4"",
    },
    ""devDependencies"": {
        ""babel-cli"": ""^6.24.1"",
        ""babel-core"": ""^6.24.1"",
        ""babel-jest"": ""^20.0.3"",
        ""babel-plugin-transform-class-properties"": ""^6.24.1"",
        ""babel-polyfill"": ""^6.23.0"",
        ""babel-preset-env"": ""^1.5.2"",
        ""babel-preset-es2015"": ""^6.24.1"",
        ""babel-preset-react"": ""^6.24.1"",
        ""babel-preset-react-hmre"": ""^1.1.1"",
        ""enzyme"": ""^2.8.2"",
        ""react-hot-loader"": ""next"",
        ""babel-plugin-import"": ""^1.2.1"",
        ""enzyme"": ""^2.9.1"",
        ""enzyme-to-json"": ""^1.5.1""
    },
    ""scripts"": {
        ""test"": ""export NODE_ENV=test &amp;&amp; ./node_modules/.bin/jest --no-cache""
    },
    ""engines"": {
        ""node"": ""&gt;= 7.8.0""
    },
    ""jest"": {
        ""verbose"": true,
        ""collectCoverage"": true,
        ""coverageDirectory"": ""__coverage__"",
        ""mapCoverage"": true,
        ""setupFiles"": [
            ""./tests/setup.js""
        ],
        ""testPathIgnorePatterns"": [
            ""/node_modules/""
        ],
        ""transform"": {
            ""\\.js$"": ""../node_modules/babel-jest""
        },
        ""testRegex"": "".*\\.test\\.js$"",
        ""snapshotSerializers"": [
            ""enzyme-to-json/serializer""
        ]
    }
}
</code></pre>

<p><code>Demo.jsx</code></p>

<pre><code>import React from 'react';
import PropTypes from 'prop-types';

export class Demo extends React.Component {

    static props = { name: PropTypes.string.isRequired };

    constructor(props) {
        super(props);
    }

    render() {
        return (
            &lt;div className='demo'&gt;{this.props.name}&lt;/div&gt;
        );
    }

}
</code></pre>

<p><code>Demo.test.js</code></p>

<pre><code>import React from 'react';
import { Demo } from '..';
import { render } from 'enzyme';


describe('Demo', () =&gt; {
    it('renders correctly', () =&gt; {
        const wrapper = render(&lt;Demo name=""foo"" /&gt;);
        expect(wrapper).toMatchSnapshot();
    });
});
</code></pre>

<p>After running <code>yarn test</code> or <code>export NODE_ENV=test &amp;&amp; ../node_modules/.bin/jest --no-cache</code>, Jest will complain that it sees an unexpected character </p>

<pre><code> 8 |     props = {
   |           ^
 9 |         name: PropTypes.string.isRequired
</code></pre>

<p>From my understanding, the environment variable set when we run the tests should automatically transform the initializers to something which can be used by Jest, but this doesn't appear to be happening.</p>

<p>I am also using webpack 2.x, but the configuration overhead to get that to work seems daunting. Is there another way?</p>

<h2>Update 1</h2>

<p>I modified my Jest settings as follows:</p>

<pre><code> ""transform"": {
      ""\\.js$"": ""./node_modules/babel-plugin-transform-class-properties""
 }
</code></pre>

<p>This failed immediately with:</p>

<blockquote>
  <p>TypeError: Jest: a transform must export a <code>process</code> function.</p>
</blockquote>

<p>Removing <code>transform</code> altogether yields a slightly different issue:</p>

<blockquote>
  <p>TypeError: Cannot read property 'props' of null</p>
</blockquote>

<p>I also added the <code>constructor</code> to the <code>Demo</code> component.</p>
",https://stackoverflow.com/questions/44794161/unit-testing-es7-react-components-with-jest,"['javascript', 'unit-testing', 'reactjs', 'babeljs', 'jestjs']",2425,TRUE,5,2
Using H2 database only for Unit testing,"<p>I have a spring boot application standing on Postgres database. </p>

<p>Now I want to use h2 database for Unit testing alone. </p>

<p>Is this right to do? or what is the recommendation</p>
",https://stackoverflow.com/questions/45294478/using-h2-database-only-for-unit-testing,"['postgresql', 'unit-testing', 'spring-boot', 'h2']",8578,TRUE,5,2
Unit testing react using Karma and Jasmine,"<p>I am very new to react and I have written a code using React 14 without any transpiler. Now I want to use Karma-Jasmine for unit testing but it seems that my test is failing rendering the app.</p>

<p>I have the following structure:</p>

<pre><code>node_modules
MyApp/
    /js/ *.js
    /test/*.js
Karma.conf.js
package.json
index.html
</code></pre>

<p>My index.html:</p>

<pre><code>&lt;html&gt;
&lt;div id=""content""&gt;&lt;/div&gt;
&lt;script src=""js/react-0.14.7.js""&gt;&lt;/script&gt;
&lt;script src=""js/react-dom-0.14.7.js""&gt;&lt;/script&gt;

&lt;script src=""js/App.js""&gt;&lt;/script&gt;
&lt;script src=""js/main.js""&gt;&lt;/script&gt;
&lt;link rel=""stylesheet"" href=""style.css""&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>My main.js:</p>

<pre><code>ReactDOM.render(React.createElement(App), document.getElementById('content'))
</code></pre>

<p>My App then is like below:</p>

<pre><code>var h = React.createElement;

var Command = React.createClass({
   render: function(){
   return h(....)
  }
})
</code></pre>

<p>my test code is as follows:</p>

<pre><code>describe('App', function() {
beforeEach(function() {
fixture.load('index.htm');
});

beforeEach(function () {
ReactDOM.render(React.createElement(App),  document.getElementById('content'));
});

it('accepts elements', function() {
  document.getElementById('x').value = 1;
  document.getElementById('y').value = 2;
  document.getElementById('setbtn').click();
});

});
</code></pre>

<p>And here is the error: </p>

<pre><code>Uncaught ReferenceError: App is not defined
at main.js:2
(anonymous) @ main.js:2
debug.html:1 (WEB_PAGE context) Lazy require of app.binding did not set the binding field
.
.
.
ReferenceError: fixture is not defined
at UserContext.&lt;anonymous&gt; (main.test.js:6)
</code></pre>

<p>Debugging Karma shows my files have been loaded as I can see the functions in my components. I installed Html2js and added to my Karma.conf.js. I have read most of the documents on the web but they didn't help.</p>

<p>What am I doing wrong? I  </p>
",https://stackoverflow.com/questions/47329520/unit-testing-react-using-karma-and-jasmine,"['javascript', 'reactjs', 'unit-testing', 'jasmine', 'karma-jasmine']",8366,TRUE,5,2
Unit testing a controller in Play 2.6,"<p>I'm getting a null pointer exception when trying to test a controller in Play 2.6 in Scala.
This is a test for an OK response:</p>

<pre><code>class ApplicationControllerSpec extends PlaySpec
with MockitoSugar with ScalaFutures {

  val mockOrchestrator = mock[ApplicationOrchestrator]
  val mockCC = mock[ControllerComponents]
  val controller = new ApplicationController(mockOrchestrator, mockCC)
  val method = controller.home()(FakeRequest())

  assert(status(method) == 200)
}
</code></pre>

<p>This is the Controller I'm testing:</p>

<pre><code>class ApplicationController @Inject()
(orchestrator: ApplicationOrchestrator, cc: ControllerComponents)
extends AbstractController(cc) with I18nSupport {

    def home(): Action[AnyContent] = Action {
      implicit request: RequestHeader =&gt; //line 29
        Ok(views.html.home())
    }
}
</code></pre>

<p>The error looks like it is associated with the implicit request but I cannot find a solution.</p>

<p>The log output is:</p>

<p><code>java.lang.NullPointerException was thrown.
java.lang.NullPointerException
    at controllers.ApplicationController.home(ApplicationController.scala:29)</code></p>
",https://stackoverflow.com/questions/44972670/unit-testing-a-controller-in-play-2-6,"['scala', 'unit-testing', 'playframework', 'playframework-2.6']",3538,TRUE,4,2
HttpRequestMessage Content Disposition null when unit testing,"<p>I am trying to write tests for a custom <code>MultipartMemoryStreamProvider</code> - one that is very similar to this <a href=""https://github.com/QualiSystems/ShellRepo/blob/master/ShellRepo/Engine/MultipartFormDataMemoryStreamProvider.cs"" rel=""nofollow noreferrer"">MultipartFormDataMemoryStreamProvider.cs</a></p>

<p>In particular, I am trying to test my own implementation of the <code>GetStream(HttpContent parent, HttpContentHeaders headers)</code> method. </p>

<p>It requires an HttpContent and HttpContentHeaders. </p>

<p>To achieve this I am trying to create a controller context and controller, then pass through the appropriate properties from that controllers request. </p>

<p>In fact, I have tried to implement the answer on this (duplicate) question: <a href=""https://stackoverflow.com/a/31194413/1678148"">Testing a Web API method that uses HttpContext.Current.Request.Files?</a></p>

<p>Everything I try results in the <code>Content-Disposition</code> on the headers being <code>null</code> As shown in the images below:</p>

<p><a href=""https://i.stack.imgur.com/VbtDh.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/VbtDh.png"" alt=""enter image description here""></a></p>

<p><a href=""https://i.stack.imgur.com/Gbli0.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Gbli0.png"" alt=""enter image description here""></a></p>

<p>Any idea what I am missing?</p>

<p>For code-sake, here is a copy of the code. You will notice it's the same as that in the answer on the other question. I just can't get passed the null content-disposition.</p>

<pre><code>  var content = new ByteArrayContent(new Byte[100]);
        content.Headers.Add(""Content-Disposition"", ""form-data"");
        var controllerContext = new HttpControllerContext
        {
            Request = new HttpRequestMessage
            {
                Content = new MultipartContent { content }
            }
        };
        var controller = new MockController();
        controller.ControllerContext = controllerContext;
</code></pre>

<p>MockController is simply:</p>

<pre><code>public class MockController : ApiController { }
</code></pre>
",https://stackoverflow.com/questions/44073646/httprequestmessage-content-disposition-null-when-unit-testing,"['c#', 'unit-testing']",2595,TRUE,4,2
Unit Testing a Keycloak-enabled Angular app,"<p>I'm trying to write a test suite for an Angular app that uses Keycloak for authentication.</p>

<p>However, as Keycloak requires you to manually bootstrap Angular and set up a few interceptors, I'm unable to fire any test due to the following error:</p>

<pre><code>Error: $injector:unpr
Unknown Provider: AuthProvider &lt;- Auth &lt;- authInterceptor &lt;- $http &lt;- $templateRequest &lt;- $route
</code></pre>

<p>This is the code for the interceptor that raises the error:</p>

<pre><code>angular.module('MPMReportGenerator')
  .factory('authInterceptor', function authInterceptor ($q, Auth, $log) {
    return {
      request: function (config) {
        var deferred = $q.defer()
        Auth.updateToken(5).success(function () {
          config.headers = config.headers || {}
          config.headers.Authorization = 'Bearer ' + Auth.token
          deferred.resolve(config)
        }).error(function () {
          deferred.reject('Failed to refresh token')
        })
        $log.info(deferred.promise)
        return deferred.promise
      }
    }
  })
</code></pre>

<p>My thinking is that I should mock the interceptor and just have it return the request.
However, I fail to see how I could do that, since this interceptor is never injected anywhere as a dependency, it's simply declared with the block above and that's it. My understanding of mocked services is that they need to be injected somewhere to be mocked.</p>

<p>My implementation of Keycloak into Angular comes straight from their examples, if that helps.</p>

<h1>Edit</h1>

<p>I've been trying to inject a mocked Auth module into the service I'm writing a test for, but still no change.<br>
I'm very new to unit testing in general, so I'm a bit lost trying to track this down. I feel like I know where the issue is, but not how to solve it (The Auth service is added during the bootstrap of the app, I need to mock it for things to work, but it seems I don't know how/where to mock it properly)</p>

<p>Here's the whole testing code:</p>

<pre><code>describe('Services', function () {
  'use strict'

  beforeEach(module('MPMReportGenerator'))

  module(function ($provide) {
    $provide.factory('Auth', function () {
      return null
    })
  })

  var sectionService, $httpBackend, mockAuth
  beforeEach(inject(function (_sectionService_, _$httpBackend_, Auth) {
    sectionService = _sectionService_
    $httpBackend = _$httpBackend_
    mockAuth = Auth
  }))

  it('should get sections', function () {
    $httpBackend.expect('GET', '/MPMReportGenerator/api/categories/all').respond(200)

    sectionService.getSections()

    expect($httpBackend.flush).not.toThrow()
  })
})
</code></pre>

<h1>Edit 2</h1>

<p>I've managed to get past my initial error by making a mock version of Auth.<br>
I am now facing issues implementing a mock version of Keycloak's Javascript library.</p>

<p>My current mock code is as follow:</p>

<pre><code>beforeEach(module(function ($provide) {
    $provide.factory('Auth', function ($q) {
      return {
        updateToken: function (minValidity) {
          return {
            success: function (fn) {
              var deferred = $q.defer()
              deferred.resolve('')
              fn(deferred.promise)
            },
            error: function (fn) {
              var deferred = $q.defer()
              deferred.resolve('Error')
              fn(deferred.promise)
            }
          }
        },
        token: 'thisisafaketokenfortesting'
      }
    })
  }))
</code></pre>

<p>And throws this error:</p>

<pre><code>Expected function not to throw, but it threw TypeError: undefined is not an object (near '...}).error(function () {...').
    target/MPMReportGenerator-1.0.0/js/app.service.spec.js:42:43
    loaded@http://localhost:9876/context.js:151:17
</code></pre>

<p>My actual test is this:</p>

<pre><code>  it('should get sections', function () {
    $httpBackend.expect('GET', '/MPMReportGenerator/api/categories/all').respond(200)
    sectionService.getSections()
    expect($httpBackend.flush).not.toThrow()
  })
</code></pre>
",https://stackoverflow.com/questions/42620612/unit-testing-a-keycloak-enabled-angular-app,"['javascript', 'angularjs', 'jasmine', 'keycloak']",4043,TRUE,5,1
How Mock JsonReader unit testing a custom JsonConverter,"<p>Wrote a Custom JsonConverter to handle different Json formats that are returned by different versions of the same api. One app makes a request to several other apps, and we dont know which format will be returned so the JsonConverter handles this and seems to work well. I need to add unit tests to the project, except I have not found helpful resources to help Mock out some of the Newtonsoft.Json objects, mainly JsonReader.</p>

<pre><code>    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject jsonValue = JObject.Load(reader);
        if(jsonValue == null)
        {
            return null;
        }

        var responseData = ReadJsonObject(jsonValue);
        return responseData;
    }

    [TestMethod]
    public void ReadJsonReturnNullForNullJson()
    {
        var converter = new DataConverter();

        _mockJsonReader.Setup(x =&gt; x.Value).Returns(null);

        var responseData = converter.ReadJson(_mockJsonReader.Object, typeof(ProbeResponseData), null, _mockJsonSerializer.Object);

        Assert.IsNull(responseData);
    }
</code></pre>

<p>Some code has been taken out of the ReadJson method. I am trying Setup the JsonReader to return the value of the actual json, in this case a null value but in other unit tests I would want an actual Json(JObject). When running the unit test I receive a ""Newtonsoft.JsonReaderException: Error reading JObject from JsonReader. Path ''.""</p>
",https://stackoverflow.com/questions/46835362/how-mock-jsonreader-unit-testing-a-custom-jsonconverter,"['c#', '.net', 'json', 'unit-testing', 'json.net']",11557,TRUE,11,5
Mock AngularFireAuth When Unit Testing an Angular Service,"<p>I have an <code>authService</code> which when instantiated subscribes to <code>AngularFireAuth</code>'s Observable <code>authState</code> and sets the services' internal (private) property <code>authState</code>.</p>

<p>So I can unit test <code>authService</code> I highjack the services' internal <code>authState</code> with <code>Reflect.get/set</code> in my test specs so I can control its value.</p>

<p><strong>The problem is of course <code>authService</code> is still subscribing to <code>AngularFireAuth</code>'s Observable <code>authState</code> during its instantiation</strong> and I don't want, nor need it to.</p>

<p>I <em>presume</em> I need to mock out AngularFireAuth which fakes a subscription and doesn't actually communicate to Firebase? New to unit tests I am at a loss as to how I should do this.</p>

<h2>auth.service.ts</h2>

<pre><code>import { Injectable } from '@angular/core';

import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class AuthService {
  private authState: firebase.User;

  constructor(private afAuth: AngularFireAuth) { this.init(); }

  private init(): void {
    this.afAuth.authState.subscribe((authState) =&gt; {
      if (authState === null) {
        this.afAuth.auth.signInAnonymously()
          .then((authState) =&gt; {
            this.authState = authState;
          })
          .catch((error) =&gt; {
            throw new Error(error.message);
          });
      } else {
        this.authState = authState;
      }

      console.log(authState);
    }, (error) =&gt; {
      throw new Error(error.message);
    });
  }

  public get currentUid(): string {
    return this.authState ? this.authState.uid : undefined;
  }

  public get currentUser(): firebase.User {
    return this.authState ? this.authState : undefined;
  }

  public get currentUserObservable(): Observable&lt;firebase.User&gt; {
    return this.afAuth.authState;
  }

  public get isAnonymous(): boolean {
    return this.authState ? this.authState.isAnonymous : false;
  }

  public get isAuthenticated(): boolean {
    return !!this.authState;
  }

  public logout(): void {
    this.afAuth.auth.signOut();
  }
}
</code></pre>

<h2>auth.service.spec.ts</h2>

<pre><code>import { async, fakeAsync, inject, TestBed, tick } from '@angular/core/testing';

import { AngularFireModule } from 'angularfire2';
import { AngularFireAuth, AngularFireAuthModule } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import 'rxjs/add/observable/of';
// import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Rx';

import { AuthService } from './auth.service';
import { environment } from '../../environments/environment';

const authState = {
  isAnonymous: true,
  uid: '17WvU2Vj58SnTz8v7EqyYYb0WRc2'
} as firebase.User;

describe('AuthService', () =&gt; {
  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [AngularFireModule.initializeApp(environment.firebaseAppConfig)],
      providers: [
        AngularFireAuth,
        AuthService
      ]
    });
  });

  it('should be defined', inject([ AuthService ], (service: AuthService) =&gt; {
    expect(service).toBeDefined();
  }));

  it('.currentUser should be anonymous', inject([ AuthService ], (service: AuthService) =&gt; {
    Reflect.set(service, 'authState', authState);

    expect(service.currentUser).toBe(authState);
  }));

  it('.currentUser should be undefined', inject([ AuthService ], (service: AuthService) =&gt; {
    expect(service.currentUser).toBe(undefined);
  }));

  it('.currentUserObservable should be anonymous', inject([ AuthService ], (service: AuthService) =&gt; {
    Reflect.set(service, 'authState', authState);

    service.currentUserObservable.subscribe((value) =&gt; {
      expect(value).toBe(authState);
    });
  }));

  it('.currentUserObservable should be undefined', inject([ AuthService ], (service: AuthService) =&gt; {
    service.currentUserObservable.subscribe((value) =&gt; {
      expect(value).toBe(undefined);
    });
  }));

  it('.currentUid should be of type String', inject([ AuthService ], (service: AuthService) =&gt; {
    Reflect.set(service, 'authState', authState);

    expect(service.currentUid).toBe(authState.uid);
  }));

  it('.currentUid should be undefined', inject([ AuthService ], (service: AuthService) =&gt; {
    expect(service.currentUid).toBe(undefined);
  }));

  it('.isAnonymous should be false', inject([ AuthService ], (service: AuthService) =&gt; {
    expect(service.isAnonymous).toBe(false);
  }));

  it('.isAnonymous should be true', inject([ AuthService ], (service: AuthService) =&gt; {
    Reflect.set(service, 'authState', authState);

    expect(service.isAnonymous).toBe(true);
  }));
});
</code></pre>

<p>For bonus points the two excluded tests (<code>.currentUserObservable should be anonymous</code> and <code>.currentUserObservable should be undefined</code>) throw the error <code>Error: 'expect' was used when there was no current spec, this could be because an asynchronous test timed out</code> but only when I log to the console during <code>authService</code>'s instantiation. I'm wondering why this would be?</p>
",https://stackoverflow.com/questions/45121529/mock-angularfireauth-when-unit-testing-an-angular-service,"['angular', 'unit-testing', 'firebase', 'jasmine', 'angularfire2']",3623,TRUE,11,1
PHP Unit testing a class w/ traits,"<p>I've just started using PHP and am writing some test for some legacy code.  I have a class here that has a trait.  How can I test that class's method that utilizes a trait's method within a function?</p>

<pre><code>trait Cooltrait
{
  public function extractMethod($z){
     return $z[0];
  }
}

class Awesome
{
  using Cooltrait

  public function handlesomething($x, $y){
    $var1 = $this-&gt;extractMethod($x)

    if(!is_null($var1)){
      return true;
    }

    return false;
  }
}
</code></pre>

<p>I need to test if $var1 is null or not in the class but I'm using this trait's method.  Anyone encountered how to best mock / stub a trait in a class for testing the <em>hadlesomething</em> function in the <em>Awesome</em> class? (edited to clarify question).</p>
",https://stackoverflow.com/questions/44533659/php-unit-testing-a-class-w-traits,"['php', 'unit-testing', 'mocking', 'phpunit', 'traits']",2706,TRUE,4,1
Unit Testing Native C++ In Visual Studio Code,"<p>I've been using Visual Studio Code to develop a low-level C++ library on a Mac. It seems to integrate with the compiler toolchain quite gracefully. But as to Unit Testing, I'm totally lost. There are a <a href=""https://stackoverflow.com/questions/242926/comparison-of-c-unit-test-frameworks"">myriad of frameworks</a> out there, none of them having been established as a standard, the way JUnit has. Moreover, the Visual Studio Code Unit Test Explorer has been very <a href=""https://github.com/formulahendry/vscode-dotnet-test-explorer"" rel=""noreferrer"">scantily documented</a>.</p>

<p>Which unit testing frameworks integrate well with the Code frontend? How should one set up a unit testing project? I'm using SCons but I can switch to another build system if necessary.</p>
",https://stackoverflow.com/questions/47035706/unit-testing-native-c-in-visual-studio-code,"['c++', 'unit-testing', 'visual-studio-code']",15761,TRUE,11,1
Angular Unit testing : Error: Cannot match any routes. URL Segment: &#39;home/advisor&#39;,"<p>Am working on unit testing under my angular 4.0.0 app , some method in my  real  component is calling manual routing via : </p>

<pre><code>method(){
....
    this.navigateTo('/home/advisor');
....
}
</code></pre>

<p>with <strong>navigateTo</strong> is a custom routing method calling this :</p>

<pre><code>  public navigateTo(url: string) {
    this.oldUrl = this.router.url;
    this.router.navigate([url], { skipLocationChange: true });
  }
</code></pre>

<p>i have this routing file :</p>

<pre><code>import ...     // Components and dependencies

const homeRoutes: Routes = [
  {
    path: 'home', component: HomeComponent,
    children: [
      {
        path: 'registration',
        component: RegistrationComponent,
        children: [
          {
            path: 'synthese',
            component: SyntheseComponent
          },
          {
            path: 'queue',
            component: QueueComponent,
            children: [
              {
                path: 'queue-modal',
                component: QueueModalComponent
              },
              {
                path: 'confirm',
                component: ConfirmComponent
              }
            ]
          }
        ]
      },
      {
        path: 'toolbox',
        component: ToolboxComponent
      },
      {
        path: 'appointment',
        component: AppointmentRegistrationComponent
      },
      {
        path: 'appointment-validation',
        component: AppointmentValidationComponent
      },
      {
        path: 'datepicker',
        component: DatePickerComponent
      },
      {
        path: 'validation/:defaultNumber',
        component: ValidationComponent,
        children: [
                   {
                     path: 'synthese',
                     component: SyntheseComponent
                   }
                   ]
      },
      {
        path: 'modalField',
        component: ModalFieldComponent
      },
      {
        path: 'search',
        component: SearchComponent
      },
      {
        path: 'advanced-search',
        component: AdvancedSearchComponent
      },
      {
        path: 'tools',
        component: ToolsComponent
      },
      {
        path: 'advisor',
        component: AdvisorComponent
      },
      {
        path: 'pilote',
        component: PilotComponent
      },
      {
          path: 'blank',
          component: BlankComponent
        },
      {
        path: 'view-360/:id',
        component: View360Component,
        children: [
          {
            path: 'client',
            component: ClientComponent
          },
          {
            path: 'tools',
            component: ToolsAdvisorComponent
          },
          {
            path: 'valid-close',
            component: ValidCloseComponent
          },
          {
            path: 'application',
            component: ApplicationView360Component
          }
        ],
        canActivate: [AuthGuardAdviser]
      },
      {
        path: 'view-360',
        component: View360Component,
        children: [
          {
            path: 'client',
            component: ClientComponent
          }
        ],
        canActivate: [AuthGuardAdviser]
      },
      {
        path: 'contract',
        component: ContractComponent
      },
      {
        path: 'queue-again',
        component: QueueAgainComponent
      },
      {
        path: 'stock',
        component: StockComponent,
        children: [
          {
            path: 'mobile',
            component: MobileComponent
          },
          {
            path: 'stock-level',
            component: StockLevelComponent
          }
        ]
      },
      {
        path: 'usefull-number',
        component: UsefullNumberComponent
      },
      {
        path: 'admin',
        loadChildren: 'app/home/admin/admin.module#AdminModule',
        //           component: AdminComponent,
        canActivate: [AuthGuardAdmin]
      },
      {
        path: 'rb',
        loadChildren: 'app/home/rb/rb.module#RbModule',
        //        component: RbComponent
        //        canActivate: [AuthGuardAdmin]
      },
      {
        path: 'tools-advisor',
        component: ToolsAdvisorComponent
      },
      {
        path: 'catalog/:haveClient',
        component: CatalogComponent
      },
      {
        path: 'application',
        component: ApplicationComponent
      },
    ]
  },

   ];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(homeRoutes)
  ],
  exports: [
    RouterModule
  ],
  declarations: []
})
export class HomeRoutingModule { }
</code></pre>

<p>Strangely , even my application goes fonctionnally well ,but the test throws this error :</p>

<blockquote>
  <p>Failed: Uncaught (in promise): Error: Cannot match any routes. URL
  Segment: 'home/advisor' Error: Cannot match any routes. URL Segment:
  'home/advisor'</p>
</blockquote>

<p>it seems like i have some missing configuration .</p>

<p><strong>Any ideas ??</strong></p>
",https://stackoverflow.com/questions/47201037/angular-unit-testing-error-cannot-match-any-routes-url-segment-home-adviso,"['javascript', 'angular', 'typescript', 'jasmine']",44539,TRUE,37,4
Unit Testing - Tests Cases vs. Multiple Methods,"<p>When writing unit tests for the below example, would it be best practice to use TestCases (such as in NUnit), or to write multiple tests for verify the functionality? </p>

<p>Say that you want to test the RetrieveContact method below - it simply finds the corresponding Contact within an array and returns the result if found, otherwise will return null.</p>

<pre><code>public class Contact
{
    public string Name { get; set; }
}

private static Contact[] Contacts =
{
    new Contact() { Name = ""Jim"" },
    new Contact() { Name = ""Bob"" },
    new Contact() { Name = ""Tom"" }
};

public static Contact RetrieveContact(string name)
{
    return Contacts.FirstOrDefault(c =&gt; c.Name == name);
}
</code></pre>

<p>Would you test this with one method, using TestCases, like below?</p>

<pre><code>[TestCase(""Bob"", ""Bob"")]
[TestCase(null, ""ZZZ"")]
public void Test_RetrievesFromContacts(string expectedName, string name)
{
    var ret = RetrieveContact(name);
    Assert.AreEqual(expectedName, ret?.Name);
}
</code></pre>

<p>Or would you write two separate tests - one for valid contacts, or one for invalid contacts returning null?</p>

<pre><code>[Test]
public void Test_RetrieveValidContact()
{
    var ret = RetrieveContact(""Bob"");
    Assert.AreEqual(""Bob"", ret.Name);
}

[Test]
public void Test_RetrieveInvalidContact()
{
    var ret = RetrieveContact(""ZZZ"");
    Assert.AreEqual(null, ret);
}
</code></pre>

<p>Thanks</p>
",https://stackoverflow.com/questions/45814148/unit-testing-tests-cases-vs-multiple-methods,"['unit-testing', 'junit', 'nunit', 'xunit', 'vs-unit-testing-framework']",4618,TRUE,4,2
&quot;XmlPullParserFactory not mocked&quot; issue while unit testing,"<p>I am doing a unit testing which includes parsing of data with XStream parser.I used Mockito for mocking context.But the test case fails with an error log:</p>

<pre><code>java.lang.RuntimeException: Method newInstance in org.xmlpull.v1.XmlPullParserFactory not mocked. See http://g.co/androidstudio/not-mocked for details.

at org.xmlpull.v1.XmlPullParserFactory.newInstance(XmlPullParserFactory.java)
at com.thoughtworks.xstream.io.xml.XppDriver.createParser(XppDriver.java:57)
at com.thoughtworks.xstream.io.xml.AbstractXppDriver.createReader(AbstractXppDriver.java:54)
at com.thoughtworks.xstream.io.xml.AbstractXppDriver.createReader(AbstractXppDriver.java:65)
at com.thoughtworks.xstream.XStream.fromXML(XStream.java:1049)
at com.att.apis.metadata.MetadataHandler.execute(MetadataHandler.java:38)
at com.att.apis.services.ServerOperations.executePostOperation(ServerOperations.java:20)
at com.att.framework.helper.request.MetadataAPIHandler.executeAPIRequest(MetadataAPIHandler.java:58)
at com.att.framework.helper.request.MetadataAPIHandlerMokitoTest.executeAPIRequest(MetadataAPIHandlerMokitoTest.java:57)
</code></pre>

<p>The error is happening at the line "" response =  (MetadataResponse)xs.fromXML(iStream); "" in the below code block</p>

<pre><code>InputStream iStream = responseData.getInputStream();
        XStream xs = new XStream();
        xs.autodetectAnnotations(true);
        xs.alias(""helloa"", A.class);
        xs.alias(""hellob"", B.class);
        xs.alias(""helloc"",C.class);
        response =  (MetadataResponse)xs.fromXML(iStream);
</code></pre>

<p>As per the answer from <a href=""https://stackoverflow.com/questions/35626721/android-xmlpullparserfactory-newinstance-creating-a-null-factory][1]"">Android: XmlPullParserFactory.newInstance() creating a null factory</a>,  I added</p>

<pre><code>testOptions {
    unitTests.returnDefaultValues = true
}
</code></pre>

<p>in build.gradle.</p>

<p>After the update when NullPointer Exception with below log occurred.</p>

<pre><code>java.lang.NullPointerException
at com.thoughtworks.xstream.io.xml.XppDriver.createParser(XppDriver.java:59)
at com.thoughtworks.xstream.io.xml.AbstractXppDriver.createReader(AbstractXppDriver.java:54)
at com.thoughtworks.xstream.io.xml.AbstractXppDriver.createReader(AbstractXppDriver.java:65)
at com.thoughtworks.xstream.XStream.fromXML(XStream.java:1049)
at com.att.apis.metadata.MetadataHandler.execute(MetadataHandler.java:38)
at com.att.apis.services.ServerOperations.executePostOperation(ServerOperations.java:20)
at com.att.framework.helper.request.MetadataAPIHandler.executeAPIRequest(MetadataAPIHandler.java:58)
at com.att.framework.helper.request.MetadataAPIHandlerMokitoTest.executeAPIRequest(MetadataAPIHandlerMokitoTest.java:57)
</code></pre>

<p>Can anyone help me to sort out the issue</p>
",https://stackoverflow.com/questions/43256958/xmlpullparserfactory-not-mocked-issue-while-unit-testing,"['java', 'android', 'unit-testing', 'mockito', 'xstream']",1863,TRUE,4,3
Django/Python Unit Testing: Let exceptions rise,"<p>I'm debugging a unit test failure whereby an exception is raised from the guts of some libraries; many exceptions. I'm using <code>ipdb</code> from the commandline to debug it.</p>

<p>when running <code>./manage.py test path.to.test</code> and the exception happens, the test runner catches the exception, prints a stack trace and marks the test failed or whatever. I get why this is useful, rather than letting the exception rise.</p>

<p>In my case, I want it to rise so <code>ipdb</code> catches it and lands me in a nice position to move up/down frames and debug the issues. I don't want to keep wrapping tests in <code>try</code> or putting <code>ipdb.set_trace()</code> calls where the exceptions are thrown. It is a pain and it is slowing down debugging. Ordinarily this isn't an issue, but today it is.</p>

<p><strong>Q:</strong> Can I stop the test runner catching the exception so <code>ipdb</code> catches it instead without code modifications? </p>

<p>I feel like there should be a way to do this, as it would be very helpful when debugging, but I have missed it somewhere along the line.</p>

<p>(Ps, Python 2.7, Django 1.6 <em>sadface</em>)</p>
",https://stackoverflow.com/questions/45060801/django-python-unit-testing-let-exceptions-rise,"['python', 'django', 'unit-testing', 'debugging']",90,TRUE,3,1
Xamarin Unit Testing from the Command Line,"<p>I'm coming from a native iOS / Android development background and I'm trying to understand the tooling around Xamarin Unit Testing using the Command Line.</p>

<p>From my point of view there are two types of code that you want to Unit Test:</p>

<ul>
<li>Plain Old C# Code - with no dependencies to any iOS / Android framework - so it shouldn't need an iOS / Android emulator to run on</li>
<li>Code that depends on iOS / Android frameworks that needs to run on a device / emulator</li>
</ul>

<p>The official <a href=""https://developer.xamarin.com/guides/ios/deployment,_testing,_and_metrics/touch.unit/"" rel=""nofollow noreferrer"">Xamarin documentation</a> mentions NUnitLite / Touch.Unit but it doesn't mention any support around Command Line. I did found an <a href=""https://forums.xamarin.com/discussion/85443/build-and-execute-xamarin-ios-unit-test-from-command-line"" rel=""nofollow noreferrer"">example</a> though, but it's not clear to me if this is a tool that's officially supported by Xamarin. Also it seems that you can run tests only on the emulator/device using that tool.</p>

<p>Another example I've found around refers to <a href=""https://gregshackles.com/testing-xamarin-apps-getting-started-with-xunit/"" rel=""nofollow noreferrer"">xUnit.net</a> - it seems that you can also run tests without an emulator / device, and that you can also run them on an emulator / device - however in that specific blogpost it's not documented how you do that.</p>

<p>So my question is: How should I approach Xamarin Unit Testing and what tools do you recommend using so I can have Command Line support in my CI.</p>

<p>Thank you</p>
",https://stackoverflow.com/questions/44928271/xamarin-unit-testing-from-the-command-line,"['unit-testing', 'xamarin', 'xamarin.ios', 'xamarin.android', 'continuous-integration']",1406,TRUE,3,2
Unit Testing Point of Sale in Odoo9,"<p>I'm trying to add unit testing into my project, focused on improoving basic Odoo 9 POS module.
My issue is about getting Odoo instanse inside test.
I've created test for testing and getting undefined value for everything, except web.Registry.
Here is my code sample:</p>

<pre><code>    odoo.define_section('Model', ['&lt;my_module&gt;.models', 'web.Registry', '&lt;my_module&gt;.lens_selection_widget', '&lt;my_module&gt;.test_passer', 'point_of_sale.chrome'], function(test, mock) {
    test('Check Orderline', function(assert, Model, Reg, LSW, TP, Main, POSC) {
        assert.ok(mock, 'mock');
        assert.ok(Model, 'Model');
        assert.ok(Reg, 'Reg');
        assert.ok(LSW, 'LSW');
        assert.ok(TP, 'TP');
        assert.ok(POSC, 'POSC');
    })
});
</code></pre>

<p>Even test_passer, with definition like </p>

<pre><code>odoo.define('test_passer', function (require) {
""use strict"";

    return true
});
</code></pre>

<p>returns undefined.</p>

<p>Need some help, ready for any question.</p>
",https://stackoverflow.com/questions/42531864/unit-testing-point-of-sale-in-odoo9,"['unit-testing', 'odoo', 'qunit', 'odoo-9', 'odoo-10']",160,TRUE,3,1
Error while unit testing HttpClientModule (Angular 4.3+),"<p>I'm exploring the new Angular HttpClientModule and running into an inexplicable error. The module is new enough that I can't yet find any useful information about how to unit test, and the official documentation doesn't have any examples. </p>

<p>The app contains a service with one method, which passes a URL to <code>http.get</code>. When I call this method in a browser context (aka <code>ng serve</code>), the http call executes normally. When called in the context of a unit test, I get the following error:</p>

<p><code>TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.</code></p>

<p>This is a minimal app generated with Angular CLI. Here's the pertinent code:</p>

<p><strong>app.module.ts:</strong></p>

<pre><code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, HttpClientModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code></pre>

<p><strong>app.component.ts:</strong></p>

<pre><code>import { Component, OnInit } from '@angular/core';
import { TestService } from './test.service'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [TestService]
})
export class AppComponent {
  title = 'app';

  constructor(private testSvc: TestService) {}

  ngOnInit() {
    this.testSvc.executeGet('http://www.example.com');
  }
}
</code></pre>

<p><strong>test.service.ts:</strong></p>

<pre><code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class TestService {
  constructor(private http:HttpClient) {}

  executeGet(url:string) {
    this.http.get(url)
      .subscribe(
        data =&gt; console.log('success', data),
        error =&gt; console.log('error', error)
    );
  }
}
</code></pre>

<p><strong>test.service.spec.ts:</strong></p>

<pre><code>import { HttpClient, HttpHandler } from '@angular/common/http';
import { TestBed, inject } from '@angular/core/testing';
import { TestService } from './test.service';

describe('TestService', () =&gt; {
  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      providers: [HttpClient, HttpHandler, TestService]
    });
  });

  it('should executeGet', inject([TestService], (svc: TestService) =&gt; {
    expect(svc.executeGet).toBeDefined();
    // this is where the 'undefined' error occurs
    svc.executeGet('http://www.example.com'); 
  }));
});
</code></pre>

<p>Any guidance or pointers greatly appreciated. </p>
",https://stackoverflow.com/questions/45326952/error-while-unit-testing-httpclientmodule-angular-4-3,['angular'],1500,TRUE,3,2
MVC Core 2.0 Unit Testing and Automapper,"<p>I am attempting to Unit Test a method that uses Automapper ProjectTo and I'm not sure how to register the mappings in MVC Core.  I am using the built in unit testing.</p>

<p>The following is my unit test.</p>

<pre><code> [TestClass]
public class BusinessGenderServiceTest
{
    [ClassInitialize]
    public static void Init(TestContext context)
    {

    }
    [TestMethod]
    public void GetTest()
    {
        var options = new DbContextOptionsBuilder&lt;GotNextDbContext&gt;()
            .UseInMemoryDatabase(databaseName: ""GetTest"")
            .Options;

        using (var context = new GotNextDbContext(options))
        {


            context.GenderLanguage.Add(new GenderLanguage { Id = 1, Name = ""Male"", Language = 1 });
            context.GenderLanguage.Add(new GenderLanguage { Id = 2, Name = ""Female"", Language = 1 });
            context.GenderLanguage.Add(new GenderLanguage { Id = 3, Name = ""Hombre"", Language = 2 });
            context.GenderLanguage.Add(new GenderLanguage { Id = 4, Name = ""Hombre"", Language = 2 });
            context.SaveChanges();
        }
            using (var context = new GotNextDbContext(options))
            {
                var service = new GenderService(context);
                var result = service.Get(1);
                Assert.AreEqual(2, result.Count());
            }

    }
}
</code></pre>

<p>I am getting the following error when I run the test:</p>

<blockquote>
  <p>Message: Test method GotNext.Test.BusinessGenderServiceTest.GetTest threw exception:</p>
  
  <p>System.InvalidOperationException: Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance.</p>
</blockquote>
",https://stackoverflow.com/questions/46457946/mvc-core-2-0-unit-testing-and-automapper,"['unit-testing', 'asp.net-core', 'automapper']",3466,TRUE,3,4
Unit Testing with retrofit and Rx android,"<p>I am new in unit testing and I am unit testing retrofit with rx android. I have one observable which is getting access token from the api and I use it using retrofit to send request. I am getting Null Pointer Exception due to it here is my code:</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)
public class AuthenticationTokenGetterTest {
    @Mock
    AuthenticatorInterface authenticatorservice;
    @InjectMocks
    AuthenticationTokenGetter tokengetter;

    @Test
    public void testtokkengetter() {
        when(authenticatorservice.servicecall(anyString(), anyString())).thenReturn(
                Observable.just(""44fffffggggggg""));

        Observable&lt;String&gt; obs = tokengetter.getToken();
        TestSubscriber&lt;String&gt; testsubscriber = new TestSubscriber&lt;&gt;();
        obs.subscribe(testsubscriber);
        testsubscriber.assertNoErrors(); // Here I get exception
        List&lt;String&gt; value = testsubscriber.getOnNextEvents();
    }

}
</code></pre>

<p>But I am getting java.lang.NullPointerException all the time.
and my observable code is which I am testing:</p>

<pre><code>@CheckResult
    public Observable&lt;String&gt; getToken() {
        return service.servicecall(key, code)
                .subscribeOn(Schedulers.newThread())
                .doOnNext(new Action1&lt;String&gt;() {
                    public void call(String token) {
                        savedToken = token;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread());
    }
</code></pre>

<p>My Error is:</p>

<pre><code>java.lang.AssertionError: Unexpected onError events: 1

    at rx.observers.TestSubscriber.assertNoErrors(TestSubscriber.java:308)
    at AuthenticationTokenGetterTest.testtokkengetter(AuthenticationTokenGetterTest.java:47)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
    at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.NullPointerException
    at rx.android.schedulers.LooperScheduler$HandlerWorker.schedule(LooperScheduler.java:77)
    at rx.android.schedulers.LooperScheduler$HandlerWorker.schedule(LooperScheduler.java:91)
    at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.schedule(OperatorObserveOn.java:190)
    at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber$1.request(OperatorObserveOn.java:147)
    at rx.Subscriber.setProducer(Subscriber.java:209)
    at rx.Subscriber.setProducer(Subscriber.java:205)
    at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.init(OperatorObserveOn.java:141)
    at rx.internal.operators.OperatorObserveOn.call(OperatorObserveOn.java:75)
    at rx.internal.operators.OperatorObserveOn.call(OperatorObserveOn.java:40)
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:46)
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
    at rx.Observable.subscribe(Observable.java:8759)
    at rx.Observable.subscribe(Observable.java:8726)
.AuthenticationTokenGetterTest.testtokkengetter(AuthenticationTokenGetterTest.java:45)
</code></pre>
",https://stackoverflow.com/questions/43913214/unit-testing-with-retrofit-and-rx-android,"['android', 'unit-testing', 'retrofit', 'rx-java', 'rx-android']",2155,TRUE,3,2
Unit testing in Typescript with Dependency Injection,"<p>I'm running into problems with typescript during unit testing. I try to unit test an module like the following code example:</p>

<pre><code>import {Express} from 'express'

export interface BootClassInterface {
  setup(): Express
}

export class BootClass implements BootClassInterface {

  constructor(private express: () =&gt; Express ){

  }

  public test(){
      const app = this.express()
      app.get(""/test"", (req, res) =&gt; {
        res.send(""Hello World"")
      })

      return app;
  }
}
</code></pre>

<p>For testing propose I want to know if express().get() was called and if the first parameter was '/test'. Before I switched to typescript I always used the module <a href=""http://sinonjs.org/"" rel=""nofollow noreferrer"">sinonJS</a> to spy or stub the functionality so that I could test of a certain dependency was used correctly. Now with Typescript I run into problems with the strict types that I've set in the module. By example:</p>

<pre><code>import * as chai from 'chai'
import 'mocha'
import * as sinon from 'sinon'
import * as express from 'express'

import * as Boot from '../../src/Core/Boot'

const assert = chai.assert

suite('[CORE] unit test /Core/Boot.ts', () =&gt; {
  let BootClass: Boot.BootClassInterface

  setup(() =&gt; {
    const expressApp = () =&gt; {
      const app = express()
      app.get = sinon.spy()
      return app
    }

    const Services: Boot.BootServicesInterface = { express: expressApp }
    BootClass = new Boot.BootClass(Services)

  })

  test('Do first test', () =&gt; {
    const app = BootClass.setup()
    chai.assert.equal(app.get.called, 1)
  })
})
</code></pre>

<p>The code example above results in the following Typescript compiling error:</p>

<pre><code>error TS2339: Property 'called' does not exist on type 'ApplicationRequestHandler&lt;Express&gt;'.
</code></pre>

<p>I can see why typescript returns this error and somehow it is even obvious. I even know a possible solution where I accept Express as any in the module.</p>

<p>But I'm looking for a more elegant way to be able to spy/stub/mock my dependencies for testing propose, but at the same time have the advantages of strict typing.</p>
",https://stackoverflow.com/questions/43616329/unit-testing-in-typescript-with-dependency-injection,"['node.js', 'unit-testing', 'typescript', 'dependency-injection', 'sinon']",1555,TRUE,3,1
Varying a struct field for unit testing,"<p>I'm trying to unit test a constructor for a struct with many fields. I want to make sure that the constructor performs all the expected validations so I am testing single fields for multiple failure scenarios. </p>

<p>I'm trying to do this programatically so I'm using table tests, however this leads to a lot of repetition and noise in the tests as I end up repeating N param fields just to test for the one field error.</p>

<p>For example:</p>

<pre><code>func NewSomeObject(p *Params) *SomeObject {
  ...
}


type SomeObject struct {
  ..
  Field1 string
  Field2 string
  Field3 string
  ...
  Field10 string
}

func TestNewSomeObject(t *testing.T) {
    tcases := map[string]struct {
        params *Params
        err    error
    }{
        &amp;Params{
          Field1: ""invalid_0"" // &lt;--- making sure that this invalid field is caught
          Field2: ""valid""
          Field3: ""valid""
          ...
          Field10: ""valid""
        },
        &amp;Params{
          Field1: ""invalid_1"" // &lt;--- another invalid case
          Field2: ""valid""
          Field3: ""valid""
          ...
          Field10: ""valid""
        },
        &amp;Params{
          Field1: ""invalid_2""
          Field2: ""valid""
          Field3: ""valid""
          ...
          Field10: ""valid""
        },
        &amp;Params{
          Field1: ""invalid_3""
          Field2: ""valid""
          Field3: ""valid""
          ...
          Field10: ""valid""
        },
        ...
        ...
        ...
    }  

    for name, tc := range tcases {
        t.Logf(""Running test %s"", name)

        s, err := NewSomeObject(tc.params)
        if !reflect.DeepEqual(tc.err, err) {
            t.Fatalf(""Got '%v', Expected: '%v'"", err, tc.err)
        }
    }
}
</code></pre>

<p>Is there a better way to vary a single field in the struct without having to repeat the input so many times?</p>
",https://stackoverflow.com/questions/44118967/varying-a-struct-field-for-unit-testing,['go'],70,TRUE,2,1
spark unit testing using spark-testing-base,"<p>I am exploring on how to write unit tests for my spark scala code. I came across spark-testing-base and upon trying to run a few standard examples i get an error</p>

<pre><code>import org.scalatest.FunSuite
import com.holdenkarau.spark.testing.{SharedSparkContext}

class AppTest extends FunSuite with SharedSparkContext {
  test(""test initializing spark context"") {
    val list = List(1, 2, 3, 4)
    val rdd = sc.parallelize(list)

    assert(rdd.count === list.length)
  }
}
</code></pre>

<p>The error is as follows: </p>

<pre><code>Class 'AppTest' must either be declared abstract or implement abstract member 'withFixture(test:Any):Outcome' in 'org.scalatest.SuiteMixin'
</code></pre>

<p>I am using IntelliJ IDEA for the same and my build.sbt looks as follows</p>

<pre><code>name := """"

version := ""1.0""

scalaVersion := ""2.11.8""

fork in Test := true

libraryDependencies ++= Seq(""org.apache.spark"" %% ""spark-core"" % ""2.0.0"",
  ""org.apache.spark""  %% ""spark-mllib""             % ""2.0.0"",
  ""org.apache.spark""  %% ""spark-sql""             % ""2.0.0"",
  ""org.scalatest"" %% ""scalatest"" % ""1.9.1"" % ""test"",
  ""com.holdenkarau"" %% ""spark-testing-base"" % ""0.7.2"" % ""test""
)

parallelExecution in Test := false
</code></pre>

<p>I have never done unit testing before. I would appreciate any help with this issue</p>
",https://stackoverflow.com/questions/46709468/spark-unit-testing-using-spark-testing-base,"['scala', 'unit-testing', 'apache-spark']",3159,TRUE,2,1
Mock Rest Server Response for Unit Testing,"<p>In integration testing, I use a real remote server to consume REST APIs. 
What's the simplest way to provide those responses within a unit test w/o depending on external entity. </p>

<p>One possible approach is to build </p>

<pre><code>public class TestHttpResponse implements   org.apache.http.client.methods.CloseableHttpResponse

override

 @Override
    public StatusLine getStatusLine() {
      return new StatusLine() {
        @Override
        public ProtocolVersion getProtocolVersion() {
          return null;
        }

        @Override
        public int getStatusCode() {
          return statusCode;
        }

        @Override
        public String getReasonPhrase() {
          return reasonPhrase;
        }
      };
    }
   ...
</code></pre>

<p>Is there a simpler and better way for mocking REST API response payloads?</p>
",https://stackoverflow.com/questions/43350697/mock-rest-server-response-for-unit-testing,"['rest', 'unit-testing', 'mockrestserviceserver']",1430,TRUE,2,1
Unit testing React component that includes MathJax,"<p>I'm looking for a way to unit test a React component that involves MathJax. Currently, my only means of getting MathJax to work in actual code is through the script tag:</p>

<pre><code>&lt;script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_CHTML'&gt;&lt;/script&gt;
</code></pre>

<p>This works fine in the actual code, but the testing environment is different. I've tried adding the above to the initial creation of JSDOM:</p>

<pre><code>const dom = new JSDOM(`
&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;&lt;/head&gt;
  &lt;body&gt;
    &lt;script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_CHTML'&gt;&lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;
`);
</code></pre>

<p>But it produces:</p>

<blockquote>
  <p>ReferenceError: MathJax is not defined.</p>
</blockquote>

<p>I've tried <code>import MathJax from 'mathjax';</code> from the NPM module, but this of course does not work as MathJax was not designed to work from an import.</p>

<p>I've also tried adding the MathJax <a href=""https://github.com/pkra/MathJax-single-file"" rel=""nofollow noreferrer"">single file</a> versions, but my code runs in strict mode, which errors trying to implement them due to their use of <code>arguments.callee</code>, etc.</p>

<p>So I'm at a loss as to how to unit test a component that has MathJax involved.</p>

<p>Here is the test:</p>

<pre><code>describe('test', () =&gt; {
  it('should render', () =&gt; {
    const wrapper = shallow(&lt;TheComponent {...props} /&gt;); // this seems to be where the problem originates
  });
});
</code></pre>

<blockquote>
  <p>ReferenceError: MathJax is not defined.</p>
</blockquote>

<p>And this is the component:</p>

<pre><code>constructor (props) {
  super(props);
  MathJax.Hub.Config(...
}

componentDidMount () {
  MathJax.Hub.Queue(...
}

componentDidUpdate () {
  MathJax.Hub.Queue(...
}
</code></pre>
",https://stackoverflow.com/questions/44600578/unit-testing-react-component-that-includes-mathjax,"['javascript', 'unit-testing', 'reactjs', 'mocha.js', 'mathjax']",414,FALSE,2,1
instrumentation/unit testing for different build variants,"<p>I'm trying to include an instrumentation test directory for each different build variants. </p>

<p>Currently I have 3 different build variants:</p>

<pre><code>alpha {
            java.srcDirs = ['src/main/java', 'src/integration-alpha/java']
            res.srcDirs = ['src/alpha/res', 'src/alphaProd/res']
      }
beta {
        manifest.srcFile 'src/beta/AndroidManifest.xml'
        java.srcDirs = ['src/beta/java', 'src/beta/java']
     }
gamma {
        java.srcDirs = ['src/gamma-integration/java', 'src/gamma/java']
     }
</code></pre>

<p>How can I set my Gradle so that I will have an ""androidTest"" or an instrumentation test for each of these build variants. </p>

<p><em>I'm trying to avoid having <strong>ONE</strong> unit test for all of the build variants because they have some different functionality.</em> </p>
",https://stackoverflow.com/questions/43902563/instrumentation-unit-testing-for-different-build-variants,"['android', 'unit-testing', 'gradle', 'android-instrumentation']",156,FALSE,2,0
Unit testing Alexa skill that uses alexa-sdk,"<p>I'm developing an Alexa skill in node and I'd like to know how I can unit test my code. I'm using the alexa sdk that Amazon released.</p>

<p>I've found many libraries to accomplish this, but they seem to be developed before the alexa sdk was available.</p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/42190976/unit-testing-alexa-skill-that-uses-alexa-sdk,"['alexa-skills-kit', 'alexa-skill']",1580,TRUE,9,5
Unit testing React Saga watchers and workers,"<p>I want to do the unit testing for the following watchers and workers using mocha and chai. Can someone help here?</p>

<p>I did write some unit test case but its not working as expected</p>

<p><strong><em>example</em></strong></p>

<pre><code>import { expect } from ""chai"";
import { take, call } from ""redux-saga/effects"";

import * as actions from ""client/actions"";
import { watchGetFavorites } from ""client/sagas/watchers/favorite-watcher"";
import { fetchFavorites } from ""client/sagas/workers/favorite-worker"";

describe(""favorite-watcher saga"", () =&gt; {
  const generator = watchGetFavorites();
  it(""it should execute watchGetFavorites"", () =&gt; {
    expect(generator.next().value).to.deep.equal(take(actions.GET_FAVORITES));
  });
  it(""it should execute watchGetFavorites api"", () =&gt; {
    const data = {
      ""loadAction"": {
        type: actions.GET_FAVORITES,
        ""payload"": {
          ""userId"": ""id""
        }
      }
    };
    const apiCall = generator.next(data);
    expect(apiCall).to.deep.equal(call(fetchFavorites, data));
  });
});
</code></pre>

<p>The 1st test case is passing but however the second one is failing and I also want to know how can I test the entire watchers so that it will also cover the worker code.</p>

<p><strong>RootSaga</strong></p>

<pre><code>import {fork} from ""redux-saga/effects"";
import * as favoriteWatcher from ""./watchers/favorite-watcher"";

export default function *rootSaga() {
  yield [
    fork(favoriteWatcher.watchGetFavorites)
  ];
}
</code></pre>

<p><strong><em>Watcher</em></strong></p>

<pre><code>import {take, call, takeEvery} from ""redux-saga/effects"";
import * as actions from ""../../actions/index"";
import * as workers from ""../workers/favorite-worker"";

export function* watchGetFavorites() {
  const loadAction = yield take(actions.GET_FAVORITES);
  yield call(workers.fetchFavorites, loadAction.payload);
}

export function* watchDeleteFavorites() {
  yield takeEvery(actions.DELETE_FAVORITE, function*(loadAction) {
    yield call(workers.deleteFavorites, loadAction.payload);
  });
}
</code></pre>

<p><strong><em>Worker</em></strong></p>

<pre><code>export function* fetchFavorites(payload) {// eslint-disable-line
  try {
    const response = yield call(fetchForJson, `${config.API.favoritesListURL}/${payload.userId}`); //api call
    yield put({//dispatch
      type: actions.GET_FAVORITES_SUCCESS,
      result: response.result,
      fetching: false
    });
  } catch (error) {
    yield put({
      type: actions.GET_FAVORITES_ERROR,
      result: error,
      fetching: false
    });
  }
}

export function* deleteFavorites(payload) {
  try {
    const response = yield call(deleteJson, `${config.API.deleteFavoriteURL}/${payload.userId}`, payload); //api call
    yield put({//dispatch
      type: actions.DELETE_FAVORITE_SUCCESS,
      result: response.result,
      fetching: false
    });
  } catch (error) {
    yield put({
      type: actions.DELETE_FAVORITE_ERROR,
      result: error,
      fetching: false
    });
  }
}
</code></pre>

<p>Any help really appriciated.</p>
",https://stackoverflow.com/questions/46092286/unit-testing-react-saga-watchers-and-workers,"['reactjs', 'unit-testing', 'mocha.js', 'react-redux', 'redux-saga']",432,FALSE,2,0
Automated unit testing for database dependent application,"<p>I am working on C++ application which has huge dependency on database. If I need to implement automated unit testing what is the best option?</p>

<ol>
<li>Insert dummy data in DB which your test function requires and the call test function.</li>
<li>Modular DB operation code and processing code but may not be feasible in legacy code.</li>
<li>Override DB Operation so that specific data can be return instead of actual DB hit; looks complex.</li>
</ol>
",https://stackoverflow.com/questions/45237383/automated-unit-testing-for-database-dependent-application,"['database', 'unit-testing', 'tdd']",64,TRUE,2,1
Unit testing HttpResponseMessage with Autofac and Moq,"<p>I'm going round in circles. So my WebApi returns the output it needs to the browser when i am running in debug. Firefox and IE display the List i need. However when i am trying to unit test the response using Mock and Autofac the <code>HttpResponseMessage</code> I am getting back has no Contents. I get the feeling it is returning on a different context or something like that. I am not totally sure, hence asking the question. I have stringed the below unit test together via googling and the Autofac documentation. </p>

<p>WebApiMethod (contained within <code>InScrapController</code>, <code>_WebScrapSprocService</code> is injected by Autofac in the constructor)</p>

<pre><code>public HttpResponseMessage GetFormItemsByFormNumber(int FormNumber)
{
    HttpResponseMessage response;
    try
    {
        //response = Request.CreateResponse(HttpStatusCode.OK, _WebScrapSprocService.GetFormItemsByFormNumber(FormNumber),new MediaTypeHeaderValue(""application/json""));
        response = Request.CreateResponse(HttpStatusCode.OK, new MediaTypeHeaderValue(""application/json""));
        response.Content = new StringContent(JsonConvert.SerializeObject(_WebScrapSprocService.GetFormItemsByFormNumber(FormNumber)),Encoding.UTF8, ""application/json"");
    } catch (Exception e)
    {
        response = Request.CreateResponse(HttpStatusCode.InternalServerError, new StringContent(e.Message), new MediaTypeHeaderValue(""application/json""));
    }
    //Checking if bob knows anything about this...
    string bob = response.Content.ReadAsStringAsync().Result;
    return response;
}
</code></pre>

<p>Unit Test</p>

<pre><code>public void GetFormItemsByFormNumber()
{
    using (var mock = AutoMock.GetLoose())
    {

        var Service = mock.Mock&lt;IWebScrapSprocService&gt;().Setup(x =&gt; x.GetFormItemsByFormNumber(3392));
        var service = mock.Create&lt;InScrapController&gt;();
        service.Request = new HttpRequestMessage();
        service.Request.SetConfiguration(new HttpConfiguration());
        var HttpResponse = service.Request.CreateResponse(HttpStatusCode.OK, Service, new MediaTypeHeaderValue(""application/json""));
        var response = service.GetFormItemsByFormNumber(3392);
        mock.Mock&lt;IWebScrapSprocService&gt;().Verify(x =&gt; x.GetFormItemsByFormNumber(3392));
        Assert.AreEqual(HttpResponse, response);
    }
}
</code></pre>
",https://stackoverflow.com/questions/44391969/unit-testing-httpresponsemessage-with-autofac-and-moq,"['c#', 'unit-testing', 'asp.net-web-api', 'moq', 'autofac']",1165,TRUE,2,1
Unit testing Vue with Karma and Typescript,"<p>I've just started using Vuejs and I'm having a real issue trying to get some tests involved. Here is how my code looks:</p>

<pre><code>//myapp.specs.ts    
import Vue from ""vue"";
import { mount } from 'avoriaz';
import Component from ""./component.vue""

describe(""My App"", () =&gt; {
    it(""works"", () =&gt; {      
        const wrapper = mount(Component);

        expect(wrapper.html()).toContain(""Hello, World"");
    });
});

//myapp.vue
&lt;script lang=""ts"" src=""./component.ts""&gt;&lt;/script&gt;
&lt;template src=""./template.html""&gt;&lt;/template&gt;
&lt;style src=""./styles/styles.css""&gt;&lt;/style&gt;

//component.ts    
import { Foo } from ""./foo""

export default {
    data() {
        return {
            isLoading: true,
            data: new Foo()
        }
    },
    created() {
        this.populate();
    },
    methods: {
        populate() {
            new FooRepository().get().then((fooData: Foo) =&gt; {
                this.isLoading = false;
                this.data = fooData;
            });
        }
    }
}

   //template.html
   &lt;div v-if=""!isLoading"" &gt;
       &lt;h2&gt;Heading&lt;/h2&gt;
       &lt;textarea name=""myText"" v-model=""data.Text""&gt;&lt;/textarea&gt;
   &lt;/div&gt;
</code></pre>

<p>The error i get is: <code>TypeError: Cannot convert undefined or null to object</code>
which i think is happening on <code>mount</code>. I previously tried this without <code>avoriaz</code> and logged the <code>Component</code> i imported, which seemed to come through as undefined. So i think the issue may be on <code>import Component from ""./component.vue""</code> not working as desired.</p>

<p>And here is my Karma.conf.js:</p>

<pre><code>module.exports = function(config) {
    config.set({
        basePath: './',
        frameworks: ['jasmine', ""karma-typescript""],
        files: [
            { pattern: './**/*.ts' },
            { pattern: './**/*.js' }
        ],
        exclude: [
            './**/*component.ts',
            './**/*build.js', //component files server as an entry point only.
            './**/*config.js'
        ],
        preprocessors: {
            './**/*.ts': ['karma-typescript']
        },
        karmaTypescriptConfig: {
            tsconfig: './tsconfig.json'
        },
        reporters: ['progress'],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: true,
        browsers: ['Chrome'],
        singleRun: false,
        concurrency: Infinity
    });
};
</code></pre>
",https://stackoverflow.com/questions/47410155/unit-testing-vue-with-karma-and-typescript,"['typescript', 'vue.js', 'vuejs2', 'karma-runner']",388,FALSE,2,0
Unit testing and mocking with RedBean ORM?,"<p>How would I go about unit testing when using RedBean ORM? It uses static methods (<code>R::dispense()</code>, <code>R::store()</code>, etc.) so how can I create a mock object? </p>

<p>Or should I just forget about that idea and simply use a test database which gets <code>nuke()</code>'d at the beginning of each test suite? I'm new to both RedBean and unit testing, but something doesn't sound right about that approach... wouldn't it be on the border of integration testing if I'm using a real database?</p>
",https://stackoverflow.com/questions/41826343/unit-testing-and-mocking-with-redbean-orm,"['unit-testing', 'testing', 'phpunit', 'integration-testing', 'redbean']",84,FALSE,2,0
Spring Boot Unit Testing with Spring Security,"<p>I have a simple application that I have setup with spring security using a custom MySql Database. Now I'm writing test cases for it and they seems to fail on login page and anything that works after the login. My question is how do I write test cases for it to check the successful login and the subsequent requests?</p>

<p>My Security Config:</p>

<pre><code>@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private DataSource dataSource;

    @Value(""${spring.queries.users-query}"")
    private String usersQuery;

    @Value(""${spring.queries.roles-query}"")
    private String rolesQuery;

    @Autowired 
    private CustomAuthenticationSuccessHandler successHandler;

    /** Providing the queries and data source for security*/
    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception 
    {
        auth.
            jdbcAuthentication()
                .usersByUsernameQuery(usersQuery)
                .authoritiesByUsernameQuery(rolesQuery)
                .dataSource(dataSource)
                .passwordEncoder(bCryptPasswordEncoder);
    }

    /** Defining fine grained access for ADMIN and CUSTOMER user */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.
            authorizeRequests()
                .antMatchers(""/"").permitAll()
                .antMatchers(""/login"").permitAll()
                .antMatchers(""/registration"").permitAll()
                .antMatchers(""/user/**"").hasAuthority(AppRole.CUSTOMER.toString())
                .antMatchers(""/health/**"").hasAuthority(AppRole.ADMIN.toString())
                .antMatchers(""/admin/**"").hasAuthority(AppRole.ADMIN.toString()).anyRequest()
                .authenticated().and().csrf().disable().formLogin()
                .loginPage(""/login"").failureUrl(""/login?error=true"")
                .successHandler(successHandler)
                .usernameParameter(""username"")
                .passwordParameter(""password"")
                .and().logout()
                .logoutRequestMatcher(new AntPathRequestMatcher(""/logout""))
                .logoutSuccessUrl(""/"").and().exceptionHandling()
                .accessDeniedPage(""/access-denied"");
    }

    /** Defining ant matchers that should ignore the paths and provide no access to any one */
    @Override
    public void configure(WebSecurity web) throws Exception 
    {
        web
           .ignoring()
           .antMatchers(""/resources/**"", ""/static/**"", ""/css/**"", ""/js/**"", ""/images/**"");
    }

}
</code></pre>

<p>My Custom Success Handler:</p>

<pre><code>@Component
@Configuration
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler 
{
    /** Getting reference to UserService */
    @Autowired
    private UserService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
            HttpServletResponse httpServletResponse, Authentication authentication) 
                    throws IOException, ServletException, RuntimeException 
    {
        HttpSession session = httpServletRequest.getSession();
        User authUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        com.crossover.techtrial.java.se.model.User user = userService.findUserByUsername(authUser.getUsername());
        session.setAttribute(""userId"", user.getUserId());
        session.setAttribute(""username"", authUser.getUsername());
        session.setAttribute(""accountId"", user.getAccountId());
        //set our response to OK status
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        Collection&lt;? extends GrantedAuthority&gt; authorities = authentication.getAuthorities();
        authorities.forEach(authority -&gt; 
                                { 
                                    if(authority.getAuthority().equals(AppRole.ADMIN.toString())) 
                                    { 
                                        session.setAttribute(""role"", AppRole.ADMIN);
                                        try
                                        {
                                            //since we have created our custom success handler, its up to us to where
                                            //we will redirect the user after successfully login
                                            httpServletResponse.sendRedirect(""/admin/home"");
                                        } 
                                        catch (IOException e) 
                                        {
                                            throw new RuntimeException(e);
                                        }                                                                           
                                    }
                                    else if (authority.getAuthority().equals(AppRole.CUSTOMER.toString()))
                                    {
                                        session.setAttribute(""role"", AppRole.CUSTOMER);
                                        try
                                        {
                                            //since we have created our custom success handler, its up to us to where
                                            //we will redirect the user after successfully login
                                            httpServletResponse.sendRedirect(""/user/home"");
                                        } 
                                        catch (IOException e) 
                                        {
                                            throw new RuntimeException(e);
                                        }   
                                    }
                                });

    }

}
</code></pre>

<p>After some seraching I tried to write test cases like this but they don't seem to be working:</p>

<pre><code>    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class TrialApplicationTests 
    {
        @Autowired
        private WebApplicationContext webApplicationContext;

        @Autowired
        private FilterChainProxy springSecurityFilterChain;

        @Autowired
        private MockHttpServletRequest request;

        private MockMvc mockMvc;


        @Test
        public void contextLoads() 
        {
        }

        @Before
        public void setup() 
        {
            mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
                    .addFilters(springSecurityFilterChain)
                    .build();
        }
        @Test
        public void verifiesLoginPageLoads() throws Exception 
        {
            mockMvc.perform(MockMvcRequestBuilders.get(""/""))
                   .andExpect(MockMvcResultMatchers.model().hasNoErrors())
                   .andExpect(MockMvcResultMatchers.view().name(""login""))
                   .andExpect(MockMvcResultMatchers.status().isOk());
        }

        @Test
        public void testUserLogin()  throws Exception
        {
            HttpSession session = mockMvc.perform(post(""/login"")
                    .contentType(MediaType.APPLICATION_FORM_URLENCODED) 
                    .param(""username"", ""test"")
                    .param(""password"", ""test123"")
                    )
                    .andExpect(MockMvcResultMatchers.status().isOk())
                    //.andExpect(redirectedUrl(""/user/home""))
                    .andReturn()
                    .getRequest()
                    .getSession();

            request.setSession(session);

            SecurityContext securityContext = (SecurityContext)   session.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);

            SecurityContextHolder.setContext(securityContext);
        }

        @Test
        public void testRetrieveUserBookings() throws Exception
        {
            testUserLogin();

            mockMvc.perform(MockMvcRequestBuilders.get(""user/bookings""))
                .andExpect(MockMvcResultMatchers.model().hasNoErrors())
                .andExpect(MockMvcResultMatchers.model().attributeExists(""bookings""))
                .andExpect(MockMvcResultMatchers.view().name(""user/bookings""))
                .andExpect(content().string(containsString(""Booking"")));
        }

    }

I searched on the net and there are links WithMockUser and UserDetails, but the problem is as you can see I'm setting a my primary key userId in the session in my custom success handler. So I would also need to get the session in my test. Please tell me the simplest way to write tests that will work, possibly with code since I'm new with security and all such. 

UPDATE:

I changed the code as suggested but still getting the 404 error on my testRetrieveUserBookings. Any more ideas?

@RunWith(SpringRunner.class)
@ContextConfiguration
@SpringBootTest
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@TestExecutionListeners(listeners={ServletTestExecutionListener.class,
        DependencyInjectionTestExecutionListener.class,
        DirtiesContextTestExecutionListener.class,
        TransactionalTestExecutionListener.class,
        WithSecurityContextTestExecutionListener.class})
public class TrialApplicationTests 
{
    @Autowired
    private WebApplicationContext webApplicationContext;

    MockMvc mockMvc; 

    @Autowired
    ForestApiClient apiClient;

    @Autowired
    AccountClient accountClient;

    @Autowired
    AirlineClient airlineClient;

    @Autowired
    UserService userService;

    private final String INTEGRATION_ACCOUNT = ""account1"";

    private MockHttpSession mockSession;

    private Authentication authentication;

    @Test
    public void contextLoads() 
    {
    }

    @Before
    public void setup() 
    {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
                //.addFilters(springSecurityFilterChain)
                .build();   

        mockSession = new MockHttpSession(webApplicationContext.getServletContext(), UUID.randomUUID().toString()); 
        mockSession.setAttribute(""userId"", 3);
        mockSession.setAttribute(""accountId"", ""ZWR26539"");
    }

    @Test
    public void testVerifiesLoginPageLoads() throws Exception 
    {
        mockMvc.perform(MockMvcRequestBuilders.get(""/""))
               .andExpect(MockMvcResultMatchers.model().hasNoErrors())
               .andExpect(MockMvcResultMatchers.view().name(""login""))
               .andExpect(MockMvcResultMatchers.status().isOk());
    }

    @Test
    public void testRegistration()  throws Exception
    {
        mockMvc.perform(post(""/registration"")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED) 
                .param(""username"", ""test2"")
                .param(""password"", ""test123"")
                .param(""email"", ""crossovertestuser@gmail.com"")
                .param(""address"", ""Some Address"")
                .param(""accountCurrency"", ""USD"")
                )
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.model().hasNoErrors())
                .andExpect(MockMvcResultMatchers.model().attributeExists(""user""))
                .andExpect(MockMvcResultMatchers.view().name(""registration""))
                .andExpect(content().string(containsString(""User has been registered successfully"")));
    }

    @Test
    @WithMockUser(username=""test"",roles={""USER"",""ADMIN""})
    public void testRetrieveUserBookings() throws Exception
    {

        mockMvc.perform(MockMvcRequestBuilders.get(""user/bookings""))
            .andExpect(MockMvcResultMatchers.model().hasNoErrors())
            .andExpect(MockMvcResultMatchers.model().attributeExists(""bookings""))
            .andExpect(MockMvcResultMatchers.view().name(""user/bookings""))
            .andExpect(content().string(containsString(""Booking"")));
    }
}
</code></pre>
",https://stackoverflow.com/questions/44100684/spring-boot-unit-testing-with-spring-security,"['spring-boot', 'junit', 'spring-security', 'spring-test', 'mockmvc']",3014,FALSE,2,1
Best approach for unit testing with data,"<p>I have a lot of DAO classes I need to test on a Spring project.</p>

<p>I am already using <em>DBUnit</em> to mock my database, however I use the @Before annotation to create objects and compare them after tests on create/update/delete operations.</p>

<pre><code>@DatabaseSetup(value = { ""/db_data/dao/common.xml"", ""/db_data/dao/myDAOCommonTest.xml"" })
@DbUnitConfiguration(dataSetLoader = ReplacementDataSetLoader.class)
public class MyDAOImplTest extends AbstractDaoTU {

  @Autowired
    private MyDAO myDAO;

    private Set&lt;ClassNeeded&gt; objectsNeeded = new HashSet&lt;&gt;();
    private ClassOne classOne;
    private ClassTwo classTwo;

    private ClassThree classThree;

    @Override
    public void setUp() throws Exception {
        super.setUp();
        this.objectsNeeded.add(somethingComingFromTheMotherClass);

        this.classOne = new ClassOne();
        this.classOne.setIdClassOne(1L)
    this.classOne.setObjectsNeeded(this.objectsNeeded);
        // ... Many other sets

        this.classTwo = new ClassTwo();
        this.classTwo.setIdClassTwo(1L);
    this.classTwo.setClassOne(this.classOne);
    // ... Many other sets

    // ... Other sets follow for a lot of other objects
    }

  @Test
  public void testOne {
    // ...
  }

  // ... Other tests follow
}
</code></pre>

<p>I am using an ORM (Hibernate in this case), and most objects are inter-dependent. My dao functions mostly need complete objects to be called, so I must create the objects before testing.</p>

<p>My questions are the following : </p>

<ul>
<li>Is there a better approach to unit test DAOs ?</li>
<li>What tools do you know to make this easier/faster to write ? (I am using maven for packaging)</li>
</ul>

<p>Thanks for your help !</p>
",https://stackoverflow.com/questions/44115844/best-approach-for-unit-testing-with-data,"['java', 'hibernate', 'unit-testing', 'junit']",179,TRUE,2,2
C# unit testing with collections of collections,"<p>To piggyback on <a href=""https://stackoverflow.com/q/11055632/2658159"">this SO question</a>...</p>

<p>How does this test fail?</p>

<pre><code>[TestMethod]
public void DummyTest() {
    var expected = new List&lt;List&lt;string&gt;&gt;() {
        new List&lt;string&gt;(){ ""123456"", ""25.6"", ""15"", ""a"" },
        new List&lt;string&gt;(){ ""123457"", ""3107450.82"", ""1"", ""bcdef"" },
        new List&lt;string&gt;(){ ""123458"", ""0.01"", ""900000"", ""-fgehk"" }
    };

    var actual = new List&lt;List&lt;string&gt;&gt;() {
        new List&lt;string&gt;(){ ""123456"", ""25.6"", ""15"", ""a"" },
        new List&lt;string&gt;(){ ""123457"", ""3107450.82"", ""1"", ""bcdef"" },
        new List&lt;string&gt;(){ ""123458"", ""0.01"", ""900000"", ""-fgehk"" }
    };

    CollectionAssert.AreEqual(expected, actual);
}
</code></pre>

<p>By the way, <code>Assert.IsTrue(expected.SequenceEqual(actual));</code> also fails.</p>

<p>Is there a better way to test collections of collections?</p>

<p>Using .NET 4.6.1.</p>
",https://stackoverflow.com/questions/42984980/c-unit-testing-with-collections-of-collections,"['c#', '.net', 'unit-testing']",1488,TRUE,2,2
"AngularJS Unit Testing, Injection and Jasmine spyOn","<p>I'm a little confused at how spyOn is being used under-the-covers when it comes to Angular unit tests. Given the following code:</p>

<pre><code>beforeEach(inject(function (_$controller_, $q, $rootScope, employeeService, _notifyService_) {
  notifyService = _notifyService_;
  $scope = $rootScope.$new();
  deferred = $q.defer();

  spyOn(notifyService, 'error').and.callFake(function(message) { return message; });
  spyOn(employeeService, 'searchEmployees').and.returnValue(deferred.promise);      

  vm = _$controller_('MainController');
}));
</code></pre>

<p>When the controller service is run, there is some initialization code that happens in MainController. Some of which uses employeeService and notifyService. I was surprised that I didn't need to pass in my mocked implementations of these two services to $controller. Why is that? Is spyOn sneakily replacing the values of these services in the provider?</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/45597692/angularjs-unit-testing-injection-and-jasmine-spyon,"['angularjs', 'unit-testing', 'jasmine']",48,FALSE,2,0
Unit testing Client/Server App in C++,"<p>I am currently developing Client/Server app based on <strong>TCP protocol</strong> in C/C++ and want to perform unit tests of both client and server side. 
I am using unix sockets for development.
Are there any MOCK libs or something similar to be used in testing or do I have to make wrappers in order to perform tests? Do these tests have to be <strong>local</strong> or they can be performed on <strong>network</strong>?</p>
",https://stackoverflow.com/questions/46608407/unit-testing-client-server-app-in-c,"['c++', 'unit-testing', 'tcpclient', 'tcpserver']",2108,TRUE,2,1
Slick unit testing - duplicate statements in logs,"<p>I have a suit of tests for slick in playframework environment, but when they are run, the statements are duplicated in logs, and it seems that they are duplicated as many times as number of tests. So if I have only one test I have one e.g. insert and select statement, but with few I have situation like that:</p>

<pre><code>[info] c.z.h.HikariDataSource - HikariCP pool db is starting.
[info] c.z.h.HikariDataSource - HikariCP pool db is starting.
[info] a.e.s.Slf4jLogger - Slf4jLogger started
[info] c.z.h.HikariDataSource - HikariCP pool db is starting.
[info] c.z.h.HikariDataSource - HikariCP pool db is starting.
[info] a.e.s.Slf4jLogger - Slf4jLogger started
[info] a.e.s.Slf4jLogger - Slf4jLogger started
[debug] s.j.J.statement - Preparing insert statement (returning: ID): insert into `USER` (`EMAIL`,`PASSWORD`,`ACTIVATION_TOKEN`,`ACTIVATED`,`CREATED`)  values (?,?,?,?,?)
[debug] s.j.J.statement - Preparing insert statement (returning: ID): insert into `USER` (`EMAIL`,`PASSWORD`,`ACTIVATION_TOKEN`,`ACTIVATED`,`CREATED`)  values (?,?,?,?,?)
[debug] s.j.J.statement - Preparing statement: select `ACTIVATION_TOKEN`, `PASSWORD`, `ACTIVATED`, `CREATED`, `EMAIL`, `ID` from `USER` where `EMAIL` = 'test@example.com' limit 1
[debug] s.j.J.statement - Preparing statement: select `ACTIVATION_TOKEN`, `PASSWORD`, `ACTIVATED`, `CREATED`, `EMAIL`, `ID` from `USER` where `EMAIL` = 'test@example.com' limit 1
[info] c.z.h.p.HikariPool - HikariCP pool db is shutting down.
[info] c.z.h.p.HikariPool - HikariCP pool db is shutting down.
[info] c.z.h.HikariDataSource - HikariCP pool db is starting.
[info] c.z.h.HikariDataSource - HikariCP pool db is starting.
[info] c.z.h.p.HikariPool - HikariCP pool db is shutting down.
[info] c.z.h.p.HikariPool - HikariCP pool db is shutting down.
</code></pre>

<p>In database state results look correct - there are no redundant statements, only these logs concerns me. ""Slf4jLogger started"" message is 10 times, so it's not because of parallel execution of tests. Number of duplicates is up to number of tests (currently 4), they are placed sequentially so no other statements from other parallel execution between.
Unit code:</p>

<pre><code>class UserSpec extends PlaySpecification {

    val userRepo = Injector.inject[UserRepo]

    import scala.concurrent.ExecutionContext.Implicits.global

    def fakeApp: FakeApplication = {
      FakeApplication(additionalConfiguration =
        Map(
          ""slick.dbs.default.driver"" -&gt; ""slick.driver.H2Driver$"",
          ""slick.dbs.default.db.driver"" -&gt; ""org.h2.Driver"",
          ""slick.dbs.default.db.url"" -&gt; ""jdbc:h2:mem:test;MODE=MySQL;DATABASE_TO_UPPER=FALSE""
        ))}

    ""User"" should {
      ""be created as not activated"" in new WithApplication(fakeApp) {
        val email = ""test@example.com""
        val action = userRepo.create(email, ""Password"")
            .flatMap(_ =&gt; userRepo.findByEmail(email))

        val result = Await.result(action, Duration.Inf)
        result must not(beNone)
        result.map {
          case User(id, email2, _, _, activated, _) =&gt; {
            activated must beFalse
            email2 must beEqualTo(email)
          }
        }
      }

      ""cannot be create if same email"" in new WithApplication(fakeApp) {
        val email = ""test2@example.com""
        val action = userRepo.create(email, ""Password"")
          .flatMap(_ =&gt; userRepo.create(email, ""Password""))

        val result = Await.result(action, Duration.Inf)
        result must beNone
      }
// rest omitted
}
</code></pre>
",https://stackoverflow.com/questions/45999315/slick-unit-testing-duplicate-statements-in-logs,"['unit-testing', 'playframework', 'play-slick']",53,FALSE,1,0
Unit testing elasticsearch.net&#39;s implicit operator using Moq,"<p>I am not sure <a href=""https://www.elastic.co/guide/en/elasticsearch/client/net-api/current/elasticsearch-net.html"" rel=""nofollow noreferrer"">ElasticSearch's .net low level client</a> is commonly used yet, because NEST seems to be the ""go to"" approach to implement an Elasticsearch client in .net. </p>

<p>Anyway, among many other methods, the main <code>IElasticLowLevelClient</code> interface exposes a method to create indices : </p>

<pre><code>ElasticsearchResponse&lt;T&gt; IndicesCreate&lt;T&gt;(
    string index, 
    PostData&lt;object&gt; body, 
    Func&lt;CreateIndexRequestParameters, CreateIndexRequestParameters&gt; requestParameters = null
) where T : class;
</code></pre>

<p>As explained <a href=""https://www.elastic.co/guide/en/elasticsearch/client/net-api/current/post-data.html"" rel=""nofollow noreferrer"">in this doc</a>, you can pass a string instead of an instance of <code>PostData&lt;object&gt;</code> thanks to one of the handy <code>PostData</code>'s implicit operators : </p>

<pre><code>public class PostData&lt;T&gt; : IPostData&lt;T&gt;, IPostData
{ 
     // ... code omitted
     public static implicit operator PostData&lt;T&gt;(string literalString);
}
</code></pre>

<p>I am unit testing a <code>PersonIndexer</code> class whose role is to call <code>IndicesCreate</code> with the correct index name ""people"" and the correct json body - I don't care about the last param. To do that I am mocking <code>IElasticLowLevelClient</code> using the Moq library.</p>

<p>Here is how <code>PersonIndexer</code> calls the low level client to create the index : </p>

<pre><code>var result = _elasticClient.IndicesCreate&lt;object&gt;(""people"", ""{ properties: {etc}}"", null);
</code></pre>

<p>Here is what the <code>PersonIndexerTest</code> class verification would ideally look like (json parsing simplified): </p>

<pre><code>_elasticClientMock.Verify(c =&gt; c.IndicesCreate&lt;object&gt;(
            ""people"",
            It.Is&lt;string&gt;(body =&gt;
                JObject.Parse(body).SelectToken(""$.properties.name.type"").ToString() == ""string""
            ), 
            null
        ));
</code></pre>

<p>The issue is that Moq never sees this call because it is expecting <code>PostData&lt;object&gt;</code> to match the second argument type, not a string.</p>

<p>You would tell me to use the ""real"" underlying type in my clause : <code>It.Is&lt;PostData&lt;object&gt;&gt;(...)</code> but this raises another issue : the <code>PostData</code> class does not publicly expose the string I used as the implicit constructor, thus it prevents me from parsing the body of my index creation request.</p>

<p>Is there any trick I can use to verify the string passed ? Is there any way to setup the mock so that it reproduces the implicit operator's behavior ? Am I going in the wrong direction...?</p>
",https://stackoverflow.com/questions/47726464/unit-testing-elasticsearch-nets-implicit-operator-using-moq,"['c#', 'unit-testing', 'moq', 'elasticsearch-net']",786,TRUE,1,1
Provide a fake CKEDITOR while unit testing,"<p>I have 2 projects ..</p>

<pre><code>.
├── dependency-project
│   └── ckeditor
│       └── ckeditor.js
└── my-project
    ├── app
    │   └── script.js
    ├── karma.conf.js
    └── test
        └── script.test.js
</code></pre>

<p><code>dependency-project</code> contains <code>ckeditor.js</code>, and both applications are served from the same web server.</p>

<p>So <code>my-project</code> can access <code>ckeditor.js</code> via <code>http://localhost:8080/ckeditor/ckeditor.js</code> based on how I have configured the web server.</p>

<p>This setup works fine when using the apps via a browser. But for unit testing, I'm getting an error when my tests try to use <code>CKEDITOR</code>.</p>

<p>Note: I'm not referencing <code>ckeditor.js</code> in my <code>karma.conf.js</code>, I'd like to define a fake if possible.</p>

<p>This is the error, is there a way i can stub/mock <code>CKEDITOR</code> here? ..</p>

<pre><code>      PhantomJS 2.1.1 (Mac OS X 0.0.0)
        ReferenceError: Can't find variable: CKEDITOR
</code></pre>

<p><code>script.js</code> ..</p>

<pre><code>document.getElementById('myElement').addEventListener('click', _editingTextStart);

function _editingTextStart() {
  CKEDITOR.disableAutoInline = true;
}
</code></pre>

<p><code>script.test.js</code> ..</p>

<pre><code>'use strict';
describe('script', function() {

  var sandbox;
  beforeEach(function() {
    sandbox = sinon.sandbox.create();
  });
  afterEach(function() {
    sandbox.restore();
  });

  it('should setup ckeditor', function() {
    var event = new Event('click');
    document.getElementById('myElement').dispatchEvent(event);
  });
});
</code></pre>
",https://stackoverflow.com/questions/47475420/provide-a-fake-ckeditor-while-unit-testing,"['javascript', 'unit-testing']",1241,TRUE,1,1
jasmine unit testing angular directive using $parsers,"<p>I'm having an issue figuring out the unit test for a directive that takes the input and replaces anything that isn't a digit with an empty string.  I'm getting the error <code>undefined is not a constructor (evaluating 'input.val('1').trigger('input')')</code></p>

<p>The issue is on the trigger.  input.val returns an empty string.  If I don't do the trigger my $parser function code isn't called.</p>

<p>It works when testing in my app, just can't get my head around how to test it.</p>

<p>I know it is using the directive as when I take out the <code>ng-model</code> the test fails with <code>number-only requires ngModel</code></p>

<p>I want to have a two tests:</p>

<ul>
<li>enter a number, view value is a number</li>
<li>enter a letter, view value is an empty string.</li>
</ul>

<p>Here is my directive</p>

<pre><code>/**
 * @ngdoc object
 * @name components-helpers-number-only
 * @description
 *
 * Catch the value before it reaches the model in the parsers phase
 * replace any non digit (0-9) and replace with an empty string.  
 * This works for any input method.  Copy and paste / Dragon etc.
 *
 */
angular.module('components-helpers-number-only', [])
    /**
     * @ngdoc directive
     * @name components-helpers-number-only.directive:numberOnly
     * @restrict E
     * @replace true
     * @element ANY
     *
     * @description
     * Directive to display a standard number field,
     * along with binding and validation, link function initialises the controller passing references to all required resources
     *
     */
    .directive('numberOnly', function() {
        return {
            require: 'ngModel',
            link: function (scope, element, attr, ngModel) {
                // The parsers are before assigning a value to a model
                ngModel.$parsers.push(function (inputValue) {
                    // Replace anything apart from a value 0-9 with an empty string
                    var transformedInput = inputValue.toLowerCase().replace(/[^0-9]/g, '');

                    // If the values are the same no need to change the value.
                    if (transformedInput!=inputValue) {
                        ngModel.$setViewValue(transformedInput);
                        ngModel.$render();
                    }

                    return transformedInput;
                });
            }
        };
    });
</code></pre>

<p>Here is my unit test</p>

<pre><code>describe('Directive: numberOnlyDirective', function () {
    'use strict';

    var scope;
    var dummyElement1;
    var input;
    var ngModel;

    beforeEach(module('components-helpers-number-only'));

    beforeEach(inject(function ($compile, $rootScope) {
        scope = $rootScope.$new();

        dummyElement1 = angular.element(
            '&lt;input type=""text"" ng-model=""model"" value=""1"" number-only /&gt;'
        );

        input = $compile(dummyElement1)(scope);

        ngModel = input.controller('ngModel');

    }))


    it('should define an input with number only directive', function () {
        expect(input).toBeDefined()



    });

    it('should set the value to 1 and set the view value to 1', function () {
        input.val('1').trigger('input');
        scope.$apply()
    });

})
</code></pre>
",https://stackoverflow.com/questions/46349552/jasmine-unit-testing-angular-directive-using-parsers,"['javascript', 'angularjs', 'unit-testing', 'jasmine']",268,TRUE,1,1
Unit testing of callback methods in Hibernate,"<p>Can someone explain to me whether it needs to write Unit testing for Hibernate callback methods? I meant methods of Entity with annotation @PrePresist, @PreUpdate and etc. </p>

<p>Here is a slice of my Entity class with needed fields. I meant fields ""startDate"" and ""endDate"". As you can see there are certain logics in methods prePersistStartDate and prePersistEndDate that determine which values will be set on. So my question was about a necessity to created Unit tests for such methods.</p>

<pre><code>@Entity
@Table(name = ""Budget"")
public class Budget implements Serializable, Comparable&lt;Budget&gt; {
  // *** Fields *** //

  @Transient
  private Calendar initCalendar = Calendar.getInstance();

  @Id
  @GeneratedValue
  @Column(name = ""id"", nullable = false)
  private Integer id;

  ...
  ...
  ...

  @Enumerated(EnumType.ORDINAL)
  @Column(name = ""range"", length = 15, nullable = false)
  private Range range;

  @Column(name = ""by_date_range"")
  private Boolean byDateRange;

  @Temporal(TemporalType.DATE)
  @Column(name = ""start_date"", nullable = false)
  private Date startDate;

  /**
   * Set up value for start date.
   */
  @PrePersist
  @PreUpdate
  public void prePersistStartDate() {
    if (!byDateRange) {
      Calendar calendar = Calendar.getInstance();
      calendar.setTimeInMillis(initCalendar.getTimeInMillis());

      switch (range) {
        case CURRENT_WEEK:
          // set Monday as the start day of week (value = 2)
          calendar.add(Calendar.DAY_OF_WEEK, 2 - calendar.get(Calendar.DAY_OF_WEEK));
          break;

        case LAST_WEEK:
          // subtract one week
          calendar.add(Calendar.WEEK_OF_MONTH, -1);
          // set Monday as the start day of week (value = 2)
          calendar.add(Calendar.DAY_OF_WEEK, 2 - calendar.get(Calendar.DAY_OF_WEEK));
          break;

        case CURRENT_MONTH:
          // set first day of the current Month
          calendar.set(Calendar.DAY_OF_MONTH, 1);
          break;

        case LAST_MONTH:
          // subtract one month
          calendar.add(Calendar.MONTH, -1);
          // set first day of the last Month
          calendar.set(Calendar.DAY_OF_MONTH, 1);
          break;

        case CURRENT_YEAR:
          // set first day of the current Year
          calendar.set(Calendar.DAY_OF_YEAR, 1);
          break;

        case LAST_YEAR:
          // subtract one year
          calendar.add(Calendar.YEAR, -1);
          // set first day of the last Year
          calendar.set(Calendar.DAY_OF_YEAR, 1);
          break;

        default:
      }

      startDate = calendar.getTime();
    }
  }

  @Temporal(TemporalType.DATE)
  @Column(name = ""end_date"", nullable = false)
  private Date endDate;

  /**
   * Set up value for end date.
   */
  @PrePersist
  @PreUpdate
  public void prePersistEndDate() {
    if (!byDateRange) {
      Calendar calendar = Calendar.getInstance();
      calendar.setTimeInMillis(initCalendar.getTimeInMillis());

      switch (range) {
        case CURRENT_WEEK:
          // set the last day of the current week
          calendar.add(Calendar.DAY_OF_WEEK, 7 - calendar.get(Calendar.DAY_OF_WEEK));
          break;

        case LAST_WEEK:
          // subtract one week
          calendar.add(Calendar.WEEK_OF_MONTH, -1);
          // set the last day of the current week
          calendar.add(Calendar.DAY_OF_WEEK, 7 - calendar.get(Calendar.DAY_OF_WEEK));
          break;

        case CURRENT_MONTH:
          // set last day of the current Month
          calendar.set(Calendar.MONTH, calendar.getActualMaximum(Calendar.MONTH));
          break;

        case LAST_MONTH:
          // subtract one month
          calendar.add(Calendar.MONTH, -1);
          // set last day of the last Month
          calendar.set(Calendar.MONTH, calendar.getActualMaximum(Calendar.MONTH));
          break;

        case CURRENT_YEAR:
          // set last day of the current Year
          calendar.set(Calendar.DAY_OF_YEAR, calendar.getActualMaximum(Calendar.YEAR));
          break;

        case LAST_YEAR:
          // subtract one year
          calendar.add(Calendar.YEAR, -1);
          // set last day of the last Year
          calendar.set(Calendar.DAY_OF_YEAR, calendar.getActualMaximum(Calendar.YEAR));
          break;

        default:
      }

      endDate = calendar.getTime();
    }
  }

  public enum Range {
    CURRENT_WEEK, LAST_WEEK, CURRENT_MONTH, LAST_MONTH, CURRENT_YEAR, LAST_YEAR
  }
}
</code></pre>
",https://stackoverflow.com/questions/47251201/unit-testing-of-callback-methods-in-hibernate,"['java', 'hibernate', 'unit-testing']",110,FALSE,1,0
Mock Web API HTTPResponseMessage C# Unit Testing,"<p>I want to create a unit test method for the below method which is receiving a file upload ""text file"" data and parsing it, I tried to use Moq and created a method but I am still very confused in the concept, I need a sample code, I've read many stackover flow questions but it is all for Controllers not Web API
the method used</p>

<pre><code>// Enable both Get and Post so that our jquery call can send data, and get a status
        [HttpGet]
        [HttpPost]
        public HttpResponseMessage Upload()
        {
            // Get a reference to the file that our jQuery sent. Even if multiple files, they will
            // all be their own request and be the 0 index

            if (HttpContext.Current.Request.Files.Count&gt;0)
            {
                HttpPostedFile file = HttpContext.Current.Request.Files[0];

                if (file != null &amp;&amp; file.ContentLength &gt; 0)
                {
                    try
                    {

                        var extension = Path.GetExtension(file.FileName);
                        if (!IsFileFormatSupported(extension))
                        {
                            var objectSerialized = SerializeData(GetError( GlobalResources.NotSupportedFileExtension));
                            return BadResponse(objectSerialized);
                        }
                        var path = SaveFileGetPath(file);
                        var result = GetPaySlips(path);
                        var SerializedData = SerializeData(result);
                        return OkResponse(SerializedData);
                    }
                    catch (System.Exception exception)
                    {
                        var SerializedData = SerializeData(GetError( GlobalResources.CouldNotReadFile + "" "" + exception.Message));
                        return BadResponse(SerializedData);
                    }
                }
                else
                {
                    var SerializedData = SerializeData(GetError(file.FileName + "" "" +  GlobalResources.FileisCorrupt));
                    return BadResponse(SerializedData);
                }
            }else
            {
                var SerializedData = SerializeData(GetError( GlobalResources.FileisCorrupt));
                return BadResponse(SerializedData);
            }
        }
</code></pre>

<p><strong>the code I did so far</strong></p>

<pre><code>    var FileUploadCtrl = new UploadController();
    Mock&lt;HttpRequestMessage&gt; cc = new Mock&lt;HttpRequestMessage&gt;();
    UTF8Encoding enc = new UTF8Encoding();

    // Mock&lt;HttpPostedFileBase&gt; file1 = new Mock&lt;HttpPostedFileBase&gt;();
    //file1.Expect(f=&gt;f.InputStream).Returns(file1.Object.InputStream);
    //cc.Expect(ctx =&gt; ctx.Content).Returns(new retur);
   // cc.Expect(ctx =&gt; ctx.Content).Returns();
    var content = new ByteArrayContent( /* bytes in the file */ );
    content.Headers.Add(""Content-Disposition"", ""form-data"");
    var controllerContext = new HttpControllerContext
    {
        Request = new HttpRequestMessage
        {
            Content = new MultipartContent { content }
        }
    };

    //file1.Expect(d =&gt; d.FileName).Returns(""FileTest.csv"");
    //file1.Expect(d =&gt; d.InputStream).Returns(new HttpResponseMessage(HttpStatusCode.OK)));
    var config = new HttpConfiguration();
    //var request = new HttpRequestMessage(HttpMethod.Post, ""http://localhost/api/upload"");
    var route = config.Routes.MapHttpRoute(""DefaultApi"", ""api/{controller}/{id}"");
    var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { ""controller"", ""FileUpload"" } });



    FileUploadCtrl.ControllerContext = new HttpControllerContext(config, routeData, cc.Object);
    var r = FileUploadCtrl.Upload();
    Assert.IsInstanceOfType(r, typeof(HttpResponseMessage));
</code></pre>
",https://stackoverflow.com/questions/43444069/mock-web-api-httpresponsemessage-c-unit-testing,"['c#', 'unit-testing', 'asp.net-web-api', 'tdd', 'moq']",2456,FALSE,1,0
Angular2 unit testing - why nativeElement has empty CSSStyleDeclaration,"<p>I'm trying to test a simple header component that has a button and when being focused - opens a dropdown using just css visibility property.</p>

<p>This is the html:</p>

<pre><code>&lt;nav class=""navigation""&gt;
    &lt;button type=""button""&gt;
        &lt;span&gt;click here&lt;/span&gt;
    &lt;/button&gt;
    &lt;ul&gt;
        &lt;li&gt; Text &lt;/li&gt;
        &lt;li&gt; Text &lt;/li&gt;
        &lt;li&gt; Text &lt;/li&gt;
    &lt;/ul&gt;
&lt;/nav&gt;
</code></pre>

<p>This is the scss style:</p>

<pre><code>button {

    span {
        margin-right: 10px;
    }

    &amp;:focus {

        + ul {
            visibility: visible;
        } 
    }
}

ul {
    position: absolute;
    list-style: none;
    z-index: 1000;
    visibility: hidden;
    transition: visibility 0.1s linear;
    background-color: $color-primary;
}
</code></pre>

<p>And this is the test:</p>

<pre><code>it('should open dropdown on focus', () =&gt; {

    let button = fixture.debugElement.query(By.css('button'));
    button.triggerEventHandler('focus', null);

    fixture.detectChanges();
    let dropdownElement = fixture.debugElement.query(By.css('ul')).nativeElement;

    console.log(dropdownElement);
    console.log(dropdownElement.style);

    expect(dropdownElement.style['visibility']).toBe('visible');

});
</code></pre>

<p>When I run the test I can see that <code>console.log(dropdownElement)</code> exists and that <code>console.log(button.nativeElement)</code> returns the <code>CSSStyleDeclaration</code> object - but ALL the properties have an empty string as a value:</p>

<pre><code>CSSStyleDeclaration {
    alignContent: """"
    alignSelf: """"
    ...
    ...
    ...
    color: """"
    visibility: """"
    ...
    ...
}
</code></pre>

<p>So basically what I need is to trigger the focus event on the button and then see if the value of the dropdown's css/style property ""visibility"" is ""visible"".
I can't figure what's wrong, cause i can see that everything is rendering fine in Karma-Debug but all the style properties are empty... any idea what's the problem?</p>
",https://stackoverflow.com/questions/42349088/angular2-unit-testing-why-nativeelement-has-empty-cssstyledeclaration,"['unit-testing', 'angular', 'karma-jasmine', 'typescript2.0', 'angular2-testing']",2408,TRUE,8,1
Pester unit testing function with Mandatory=True,"<p>I'm learning slowly using the wonderful Pester unit testing for Powershell for a while now. I'm kind of stuck around the usage of checking if my function can run ""if not supplied any mandatory input into a function."" which is giving me a red light here and wanted to achieve a green test result and move on coding.</p>

<p>So I have a function as follows.</p>

<pre><code>function Code()
{     
param(
  [parameter(Mandatory=$true)]
  [string]$SourceLocation)
return ""Hello from $SourceLocation""
}
</code></pre>

<p>my test script is executed with the following checks
...</p>

<pre><code>$moduleName = 'Code';
Describe $moduleName {         
      Context ""$Function - Returns a result "" {
          It ""does something useful with just $Function function name"" {
            $true | Should Be $true
          }
      }

      Context ""$Function - Returns with no input "" {
        It ""with no input returns Mandatory value expected"" {
           Code | Should Throw
        }
      }

      Context ""$Function - Returns some output"" {
          It ""with a name returns the standard phrase with that name"" {
              Code ""Venus"" | Should Be ""Hello from Venus""
          }
          It ""with a name returns something that ends with name"" {
              Code ""Mars"" | Should Match "".*Mars""
          }
      }

  } #End Describe
</code></pre>

<p>my output from AppVeyor shows this outcome which the [+] are green colours and [-] is a red colour which is what I'm avoiding the best I can.</p>

<pre><code> Describing Code
    Context Code - Returns a result 
      [+] does something useful with just Code function name 16ms
    Context Code - Returns with no input 
      [-] with no input returns Mandatory value expected 49ms
        Cannot process command because of one or more missing mandatory parameters: SourceLocation.
        at &lt;ScriptBlock&gt;, C:\projects\code\Code.Tests.ps1: line 117
        117:            Code | Should Throw

    Context Code - Returns some output
      [+] with a name returns the standard phrase with that name 23ms
      [+] with a name returns something that ends with name 11ms
</code></pre>

<p>Any help is appreciated as I would like a green condition there as I'm not sure how to overcome certain types of message responses from Powershell and translate this into unit tests...</p>
",https://stackoverflow.com/questions/44856253/pester-unit-testing-function-with-mandatory-true,"['unit-testing', 'powershell', 'pester']",845,TRUE,1,1
Unit testing anonymous callback routing in silex,"<p>I'm approaching 100% code coverage by phpunit unit tests, but the only thing i'm currently not covering is the routing. And i'm unsure as how to test it. Can anyone be of assistance?</p>

<p>I'm using the Silex framework to do my routing in the following manner:</p>

<pre><code>$api-&gt;put('/update/{websiteName}/{endpointName}', function($websiteName, $endpointName, Request $request) use ($databaseServiceContainer, $sourceRetrievalService) {
    $controller = new RequestController(
        $databaseServiceContainer, 
        $sourceRetrievalService
    );

    return $controller-&gt;update(
        $websiteName, 
        $endpointName, 
        $request
    );
});
</code></pre>

<p>Creating the routing themselves is covered, but not the anonymous callback within. </p>

<p>As you can see within this image:</p>

<p><img src=""https://i.stack.imgur.com/gjtyP.png"" alt=""As you can see within this image.""></p>

<p>The full code is available at <a href=""https://github.com/ri0t1985/api-creator"" rel=""nofollow noreferrer"">https://github.com/ri0t1985/api-creator</a></p>
",https://stackoverflow.com/questions/46047837/unit-testing-anonymous-callback-routing-in-silex,"['php', 'unit-testing', 'phpunit', 'silex']",215,TRUE,1,2
"Unit Testing - Interfaces, Mocking and Dependancy Injection","<p>Im trying to get my head around some aspects of Unit testing, so I've created a simple solution with the following architecture:</p>

<p><a href=""https://i.stack.imgur.com/WjUOa.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/WjUOa.jpg"" alt=""enter image description here""></a></p>

<p>In the Business layer I've created a FizzBuzz class (FizzBuzzService) that implements an IFizzBuzz interface.</p>

<pre><code>namespace SampleApp2017.Business
{
public class FizzBuzzService : IFizzBuzz
{
    public bool IsFizzBuzz(int num)
    {
        if (num % 3 == 0 || num % 6 == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public bool IsFizz(int num)
    {
       return (num % 3 == 0 ? true : false);
    }

    public bool IsBuzz(int num)
    {
        if (num % 6 == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}
}
</code></pre>

<p>(and heres the Interface details for reference)</p>

<pre><code>namespace SampleApp2017.Business
{
public interface IFizzBuzz
{

    bool IsFizzBuzz(int num);

    bool IsFizz(int num);

    bool IsBuzz(int num);
}
}
</code></pre>

<p>In this sample solution, the FizzBuzz service is consumed by both the WebUI and the ConsoleApp using Dependancy Injection, I understand why this is necessary however when it comes to Unit Testing the service i'm getting confused.</p>

<p>Below is a test I have set up for the FizzBuzz method:</p>

<pre><code>  [TestMethod]
    public void fizzbuzz_should_return_true()
    {
        //Arrange
        //Bring in the business rules
        IFizzBuzz _fbservice = new FizzBuzzService();

        //Act
        /// Send 12 to service, should return true
        bool resultof12 = _fbservice.IsFizzBuzz(12);

        //Assert
        Assert.AreEqual(resultof12, true);
    }
</code></pre>

<p>I'm now looking for some guidance on the 'best practice' for running unit tests.</p>

<ol>
<li>Does the above test look OK? (it runs fine)</li>
<li>Is is common to use DI with Unit Testing? Surely I am testing the concrete implentation of a class?</li>
<li><p>In unit testing do I need to programme to an interface? What would be the problem with:</p>

<p>FizzBuzzService _fbservice = new FizzBuzzService();</p></li>
<li><p>And finally, if I wanted to Mock in this example, where does it come in and what are the advantages?</p></li>
</ol>
",https://stackoverflow.com/questions/41461989/unit-testing-interfaces-mocking-and-dependancy-injection,"['c#', 'unit-testing', 'dependency-injection', 'mocking']",3146,TRUE,1,1
Mocking and Unit Testing ASP.Net 1.0 Repository,"<p>I am in need of some help Mocking and testing my class. I have tried various methods and feel this is the closest I have came. //1 and //2 are two separate attempts. 
There is no error on method one but I do not know how to actually test anything with it using the <code>Assert</code> call. 
Attempt 2 has the error message </p>

<blockquote>
  <p>Can not instantiate proxy of class: RentalsRated.Data.RentalsDBContext.</p>
</blockquote>

<p><strong>Test</strong></p>

<pre><code>[Fact]
public void RepoUA_GetAll()
{
    var users = new List&lt;UserAccount&gt; {
        new UserAccount { Id = ""idstring1"", Username = ""username1""},
        new UserAccount { Id = ""idstring2"", Username = ""username2"" },
        new UserAccount { Id = ""idstring3"", Username = ""username3"" },
    }.AsQueryable();

    var mockContext = new Mock&lt;RentalsDBContext&gt;();
    var mockSet = new Mock&lt;DbSet&lt;UserAccount&gt;&gt;();

    mockSet.As&lt;IQueryable&lt;UserAccount&gt;&gt;().Setup(m =&gt; m.Provider).Returns(users.Provider);
    mockSet.As&lt;IQueryable&lt;UserAccount&gt;&gt;().Setup(m =&gt; m.Expression).Returns(users.Expression);
    mockSet.As&lt;IQueryable&lt;UserAccount&gt;&gt;().Setup(m =&gt; m.ElementType).Returns(users.ElementType);
    mockSet.As&lt;IQueryable&lt;UserAccount&gt;&gt;().Setup(m =&gt; m.GetEnumerator()).Returns(users.GetEnumerator());

    mockContext.Setup(m =&gt; m.Set&lt;UserAccount&gt;()).Returns(mockSet.Object).Verifiable();

    //1
    Mock&lt;IRentalsRepository&lt;UserAccount&gt;&gt; MockRepo = new Mock&lt;IRentalsRepository&lt;UserAccount&gt;&gt;();
    MockRepo.Setup(m =&gt; m.GetAll()).Returns(users);

    //2
    var testClass = new RentalsRepository&lt;UserAccount&gt;(mockContext.Object);
    var result = testClass.Get(""idstring2"");

    Assert.Equal(""idstring2"", result.Id);
}
</code></pre>

<p><strong>Repo</strong></p>

<pre><code>public class RentalsRepository&lt;T&gt; : IRentalsRepository&lt;T&gt; where T : BaseClass
{
    private readonly RentalsDBContext _Context;
    private DbSet&lt;T&gt; entities;
    string errorMessage = string.Empty;

    public RentalsRepository(RentalsDBContext _Context)
    {
        this._Context = _Context;
        entities = _Context.Set&lt;T&gt;();
    }

    public IEnumerable&lt;T&gt; GetAll()
    {
        return entities.AsEnumerable();
    }
}
</code></pre>

<p><strong>Context</strong></p>

<pre><code>public class RentalsDBContext : DbContext
{

    public RentalsDBContext(DbContextOptions&lt;RentalsDBContext&gt; options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

    }

    public virtual DbSet&lt;UserAccount&gt; UserAccounts { get; set; }
    public virtual DbSet&lt;Rating&gt; Ratings { get; set; }
    public virtual DbSet&lt;PropertyAddress&gt; PropertyAddresses { get; set; }
    public virtual DbSet&lt;Town&gt; Towns { get; set; }
    public virtual DbSet&lt;County&gt; Countys { get; set; }
    public virtual DbSet&lt;RatingImage&gt; RatingImages { get; set; }
}
</code></pre>
",https://stackoverflow.com/questions/43559325/mocking-and-unit-testing-asp-net-1-0-repository,"['c#', 'asp.net', '.net', 'unit-testing', 'mocking']",147,TRUE,1,1
Android - Local Unit testing for file exists,"<p>What would be the recomended approach(if any) to test the following code under a Local Unit test class in a Android project?</p>

<pre><code>public static boolean internalAppFolderExists() {
    File file = new File(getDefaultStoragePath() + ""/env/app"");
    return file.exists();
}
</code></pre>

<p>Would it be better to just refactor this kind of code in any way?</p>
",https://stackoverflow.com/questions/42893116/android-local-unit-testing-for-file-exists,"['java', 'android', 'unit-testing', 'android-studio', 'junit']",248,FALSE,1,0
Unit Testing using C# with void function,"<p>How can I do unit testing for the below class, as there is no any values in the code and there is no return and I should do the unit testing without modifying the code. What should I write in the test unit</p>

<p>Any Help?</p>

<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace ORS
{
    public partial class DoctorAddEditMarks : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Label2.Text = """" + Session[""Username""];
        }

        protected void LinkButton2_Click(object sender, EventArgs e)
        {
            Response.Redirect(""~/DoctorMainPage.aspx"");
        }

        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            Response.Redirect(""~/LoginPage.aspx"");
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i &lt; GridView1.Rows.Count; i++)
            {

                GridViewRow row = GridView1.Rows[i];

                string coursecode = DropDownList1.SelectedValue.ToString();
                string marktype = DropDownList2.SelectedValue.ToString();
                string fullmark = TextBox1.Text;
                string stid = row.Cells[0].Text;
                TextBox txtmark = (TextBox)row.Cells[1].FindControl(""TextBox2"");
                string mark = txtmark.Text;

                String strConnString = ConfigurationManager.ConnectionStrings[""ConnectionString""].ConnectionString;
                SqlConnection con = new SqlConnection(strConnString);
                String query = ""insert into Marks values (@St_ID, @CourseCode, @MarkType, @Mark, @FullMark)"";
                SqlCommand cmd = new SqlCommand(query, con);
                cmd.Parameters.AddWithValue(""@CourseCode"", coursecode);
                cmd.Parameters.AddWithValue(""@St_ID"", stid);
                cmd.Parameters.AddWithValue(""@MarkType"", marktype);
                cmd.Parameters.AddWithValue(""@Mark"", mark);
                cmd.Parameters.AddWithValue(""@FullMark"", fullmark);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();

            }

            ScriptManager.RegisterStartupScript(this, this.GetType(), ""alert"", ""alert('Marks are SuccessFully Saved');window.location ='DoctorAddEditMarks.aspx';"", true);

        }
}
}
</code></pre>
",https://stackoverflow.com/questions/43764475/unit-testing-using-c-with-void-function,"['c#', 'unit-testing']",110,FALSE,1,1
Apply &quot;assertTrue&quot; unit testing to pandas DataFrame?,"<p>Using unit testing of python, how can I check that the column names of pandas DataFrame <code>df</code> coincide with column names of the list?</p>

<pre><code>import unittest

column_names_list = [""col1"",""col2"",""col3""]

assertTrue(df.columns in column_names_list)
</code></pre>

<p>For example, I should get False for this <code>df</code>:</p>

<pre><code>col1   col2   col3   col4
aasa   4546   5643   shsh
...
</code></pre>
",https://stackoverflow.com/questions/47019730/apply-asserttrue-unit-testing-to-pandas-dataframe,"['python', 'pandas', 'unit-testing', 'python-unittest']",1780,TRUE,1,2
Unit Testing Vue.js Button Press With Mocha,"<p>My code looks something like this:</p>

<pre><code>&lt;div v-if=""day &lt; 30"" class=""text-center""&gt;
  &lt;h1&gt;Day {{ day }} of 30 :: {{ time }}&lt;/h1&gt;
  &lt;a @click=""advanceGame"" class=""btn btn-lg btn-success"" href=""#"" role=""button""&gt;Next&lt;/a&gt;
&lt;/div&gt;

&lt;div v-else class=""text-center""&gt;
  &lt;h1&gt;Game Over!&lt;/h1&gt;
&lt;/div&gt;
</code></pre>

<p>What I'd like to do via a Mocha unit test is when the button is clicked the internal state of the data inside the component is changed. How do I do that? My data looks like this...</p>

<pre><code>data () {
  return {
    day: 1,
    time: '7AM'
  }
}
</code></pre>
",https://stackoverflow.com/questions/45155861/unit-testing-vue-js-button-press-with-mocha,"['javascript', 'unit-testing', 'mocha.js', 'vuejs2', 'vue-component']",488,FALSE,1,0
Unit testing IO Int and similar in Haskell,"<p>From <a href=""https://wiki.haskell.org/H-99:_Ninety-Nine_Haskell_Problems"" rel=""noreferrer"">Ninety-Nine Haskell Problems</a>:</p>

<p><a href=""https://wiki.haskell.org/99_questions/21_to_28"" rel=""noreferrer"">Question 23</a>: <em>Extract a given number of randomly selected elements from a list.</em></p>

<p>This is a partial solution. For simplicity, this code just selects one element from a list.</p>

<pre><code>import System.Random (randomRIO)

randItem :: [a] -&gt; IO a
randItem xs = do
    i &lt;- randomRIO (0,length xs - 1)
    return $ xs !! i
</code></pre>

<p>so <code>randItem [1..10]</code> would return an <code>IO Int</code> that corresponds to (but does not equal) some Int from 1 through 10.</p>

<p>So far, so good. But what kind of tests can I write for my randItem function? What relationship--if any--can I confirm between the input and output?</p>

<p>I can use the same logic as the above function to produce <code>m Bool</code>, but I cannot figure out how to test for <code>m Bool</code>. Thank you.</p>
",https://stackoverflow.com/questions/46791466/unit-testing-io-int-and-similar-in-haskell,['haskell'],559,TRUE,8,1
"Unit testing, dependency injection and AutoMapper annotations","<p>I've just recently used MVC for the first time to build a CRUD application on a SQL Server database.  The Entity Framework and the provided scaffolding utilities made this pretty easy. I particularly like how I can use data annotations in the model to centralize label names, validation, etc. for the data fields.  I found MVC to be intuitive, organized and I was able to add custom functionality like change tracking using the Entity Framework without a lot of extra code or frustration.</p>

<p>Then I decided to take it to the next level and incorporate unit testing.  Things quickly got a lot more complicated.</p>

<p>I read that unit testing with the actual database is problematic and slow and generally not recommended.  It's preferable to swap in mock database calls or use an in-memory database substitute.  Makes sense.  So, the first thing I did was code a separate repository layer to isolate the database calls. I soon discovered that this, in itself, is not sufficient.  In order to easily swap one repository for another at test time without rewriting code, it's necessary to inject the correct repository implementation into the controllers through the constructor using the inversion of control pattern with dependency injection.  Since dependency injection relies on interfaces, I had to add interface definitions for all the repository classes, install Ninject to manage the injection and wire things up to inject the right interface implementations. I also implemented a Unit of Work interface to encapsulate the process of updating possibly multiple repositories and committing all the changes once.</p>

<p>I then discovered that when editing existing records in my CRUD application the built-in field mappers can't post back an edited object that's constructed with dependency injection.  This next led me to the philosophy of separate, simplified view models for each view that only define the precise field information required by the view and using AutoMapper to map the data model to each view model and back again after post.  So, after more learning, installing and wiring, I got this working.  Unfortunately, I then discovered that while AutoMapper maps the field values between items, it does not map the data annotations.  This means that I have to duplicate all the data annotations between the data model and the 4 or 5 view models for each class for the labeling, field validation, etc. to work.  I found a few suggestions to address this on SO, but they didn't seem simple or robust.  I know this shouldn't be a showstopper, but it's the first serious obstacle I've encountered that I can't find a reasonable solution for and it's bugging me.</p>

<p>My questions:</p>

<ol>
<li><p>Does anyone have a proven method for getting AutoMapper to also map the data annotations?  Is there another mapper that works similarly but solves this problem?  </p></li>
<li><p>All of the above work came about from a simple desire to do some unit testing with a substitute database.  My project's code size and complexity grew significantly from the original MVC project and classes auto-created using scaffolding.  I know the consensus is that this is the ""right"" way to organize a project for testing and for future development and refactoring, but is it all really worth it?  I could have a much simpler project if my tests just used a copy of the real database.  I'd love to hear other people's experiences and perspective.</p></li>
</ol>
",https://stackoverflow.com/questions/44317437/unit-testing-dependency-injection-and-automapper-annotations,"['asp.net-mvc', 'entity-framework', 'unit-testing', 'automapper', 'ninject.web.mvc']",428,TRUE,1,2
Kentico Unit Testing on method with DocumentHelper,"<p>I have a method which is using DocumentHelper API from Kentico:</p>

<pre><code>public static TreeNode GetDocument(string pageType, string aliasPath)
{
     var document = DocumentHelper.GetDocuments().Types(pageType).Path(aliasPath, PathTypeEnum.Single).FirstOrDefault();
     return document;
}
</code></pre>

<p>I wanted to do a unit test for this method, but I'm not sure how can I fake the DocumentHelper output. Any suggestions?</p>
",https://stackoverflow.com/questions/43671094/kentico-unit-testing-on-method-with-documenthelper,"['unit-testing', 'static', 'kentico']",279,TRUE,1,1
Creating java.util.map.Entry instance to help unit testing,"<p>In my code, I have a <code>for</code> loop like,</p>

<pre><code>for( final Entry&lt;Object, Object&gt; entry : fileTypeProperties.entrySet()) {
    saveFileTypeToCompany(registeredCompany,
             entry.getKey().toString(), 
             entry.getValue().toString());
}
</code></pre>

<p>So, while unit testing, how to create an instance of <code>Entry</code> (i.e., <code>java.util.map.Entry</code>) ?</p>
",https://stackoverflow.com/questions/43222679/creating-java-util-map-entry-instance-to-help-unit-testing,"['java', 'junit', 'mockito', 'powermockito']",1969,TRUE,1,2
Karma Webpack Jasmine Unit Testing not working,"<p>I am trying to setup testing with Karma, Jasmine, Webpack in AngularJS.
My webpack is working fine and I can run my website using <code>npm start</code></p>

<p>A simple test works fine but the moment I try to add my app.js everything goes downhill.</p>

<p>I have tried many many many searches and many solutions. Please dont think, I am writing this question the moment I hit a deadend. I have spent all day today just googling and find possible solutions.</p>

<p>There is my karma.conf.js file</p>

<pre><code>// Karma configuration
// Generated on Mon Sep 18 2017 09:27:36 GMT+1000 (AEST)

var webpackConfig = require('./webpack.config.js');


module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    frameworks: ['jasmine'],

    // ... normal karma configuration
    files: [
        './node_modules/jasmine-core/lib/jasmine-core/jasmine.js',
        './node_modules/angular/angular.js',                                        // angular
        './node_modules/angular-mocks/angular-mocks.js',                            // loads our modules for tests

        // all files for test
        './resources/assets/js/auth/app.js',
        './resources/assets/js/account/invoices/*.spec.js',
    ],

    preprocessors: {
        // add webpack as preprocessor
        './resources/assets/js/account/invoices/*.spec.js':     ['webpack'],
    },

    webpack: {
        // webpack configuration
        webpackConfig
    },

    webpackMiddleware: {
      // webpack-dev-middleware configuration
      // i. e.
      stats: 'errors-only'
    },

    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],


    // web server port
    port: 9876,

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

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_DEBUG,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],

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

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}
</code></pre>

<p>The test that I have written is</p>

<pre><code>describe('Unit testing Dash', function() {
    var $compile,
        $rootScope;

    // Load the myApp module, which contains the directive
    beforeEach(angular.mock.module('app'));

    // Store references to $rootScope and $compile
    // so they are available to all tests in this describe block
    beforeEach(inject(function(_$compile_, _$rootScope_){
        // The injector unwraps the underscores (_) from around the parameter names when matching
        $compile = _$compile_;
        $rootScope = _$rootScope_;
    }));

    it('Replaces the element with the appropriate content', function() {
        // Compile a piece of HTML containing the directive
        var element = $compile(""&lt;dash-list&gt;&lt;/dash-list&gt;"")($rootScope);
        // fire all the watches, so the scope expression {{1 + 1}} will be evaluated
        $rootScope.$digest();
        // Check that the compiled element contains the templated content
        expect(element.html()).toContain(""Unpaid"");
    });
});
</code></pre>

<p>And it fails with this error:</p>

<pre><code>18 09 2017 15:00:18.554:DEBUG [web-server]: serving (cached): project/resources/assets/js/account/invoices/dash.spec.js
18 09 2017 15:00:18.557:DEBUG [web-server]: serving (cached): project/resources/assets/js/account/invoices/add-business.spec.js
18 09 2017 15:00:18.576:DEBUG [web-server]: serving: project/node_modules/karma/static/context.js
Chrome 60.0.3112 (Mac OS X 10.12.6) ERROR
  Uncaught SyntaxError: Unexpected token import
  at resources/assets/js/auth/app.js:1
</code></pre>

<p>I am using OSX. Technically, webpack should serve the compiled file to Karma. But unexpected token <strong>import</strong> means that file is not being compiled and served to Karma.</p>

<p>Please help.</p>

<p><em>I even tried to compile with babel but that didnt go anywhere either. I moved to webpack because we already have webpack config built and project is compiled using webpage.config</em></p>

<p><strong>UPDATE</strong></p>

<p>To anyone who stubble upon this question, I used the OPTION #1 by Felix.
I just included the compiled files in the Karma. It worked like charm.</p>

<p>Webpack auto compile files whenever files are changed, so just adding the output worked fine.</p>

<p>My files array looked like following</p>

<pre><code>files: [
    './node_modules/jasmine-core/lib/jasmine-core/jasmine.js',
    './node_modules/angular/angular.js',                                        // angular
    './node_modules/angular-mocks/angular-mocks.js',                            // loads our modules for tests
    './resources/assets/js/account/stripe.spec.js',
    './node_modules/angular-stripe/index.js',
    './node_modules/angular-stripe-checkout/angular-stripe-checkout.js',

    // all files for test
    './public/assets/vendor.bundle.js',
    'http://localhost:8080/assets/account.js',
    './resources/assets/js/account/invoices/*.spec.js',
</code></pre>

<p><em>I had to use http for the 2nd option unfortunately but it is working fine.</em></p>
",https://stackoverflow.com/questions/46271962/karma-webpack-jasmine-unit-testing-not-working,"['angularjs', 'karma-jasmine', 'karma-webpack']",2502,TRUE,1,2
Call Method inside a Method Unit testing,"<p>I got a presenter to be tested. Presenter contains a method which calls another method on some success return. Now how do I check whether that success return calls that method or not?</p>

<p>Here is the sample code, it simply verifies if a method of non mock object
<code>tutorProfileDataReceived(tutorProfiledata)</code> is the method I need to ensure to be called <code>onResponse</code>.   </p>

<p>Now this gives Actually, there were zero interactions with this mock.</p>

<pre><code>Call call = apiInterface.getTutorProfile(tutorProfile);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                TutorProfile tutorProfiledata = (TutorProfile) response.body();
                tutorProfileDataReceived(tutorProfiledata);
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                Log.d(TAG,""getting suggestions call cancel"");
                call.cancel();
            }
        });
</code></pre>

<p>Testing work...</p>

<pre><code>@Before
    public void setUp(){
        MockitoAnnotations.initMocks(this);
        apiInterface = NetworkContext.getInstance().getService(APIInterface.class);
        presenter = Mockito.spy(new TutorProfilePresenter(viewMock , contextMock));

    }

    @Test

        public void getTutorDataTest(){
            int searchId = 2;

            TutorProfile profileSender = new TutorProfile(searchId);
            Call&lt;TutorProfile&gt; call = apiInterface.getTutorProfile(profileSender);

            try {
                Response&lt;TutorProfile&gt; response = call.execute();
                TutorProfile profileReceiver = response.body();

                Mockito.verify(presenter).tutorProfileDataReceived(profileReceiver);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
</code></pre>
",https://stackoverflow.com/questions/44386339/call-method-inside-a-method-unit-testing,"['android', 'unit-testing', 'junit', 'mockito', 'android-testing']",580,FALSE,1,0
"Unit Testing Swift, CoreLocation issue with info.plist","<p>I am testing my project with XCode, which has a CLLocationManager that updates location. I have added the Privacy - always usage description in the test and project info.plist file(both).
But when I run the test here is the log : </p>

<pre><code>This app has attempted to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSLocationAlwaysUsageDescription key with a string value explaining to the user how the app uses this data
</code></pre>

<p>Anyone has this issue or know how to fix it</p>
",https://stackoverflow.com/questions/45885693/unit-testing-swift-corelocation-issue-with-info-plist,"['swift', 'unit-testing', 'core-location', 'xctest', 'info.plist']",360,TRUE,1,1
Unit testing NodeJS Promise inside a function,"<p>Im trying to unit test a function that calls a promise...</p>

<p>Using Mocha, Sinon. I have a functional block like this:</p>

<p>myfile.js:</p>

<pre><code>    let OuterDependecy = require('mydep');
    function TestFunction(callback) {
        OuterDependency.PromiseFunction().then(response =&gt; {  

       //some logic here
     }).catch(err =&gt; {callback(err)});
</code></pre>

<p>inside my test i have used <a href=""https://www.npmjs.com/package/proxyquire"" rel=""nofollow noreferrer"">proxyquire</a> to mock the outerdependecy</p>

<p>testfile.js</p>

<pre><code>let proxyquire = require('proxyquire');
let OuterDepStub = {};
let testingFunc = proxyquire('myfile.js', {'mydep': OuterDepStub});
</code></pre>

<p>... then inside my testing block</p>

<pre><code>    let stubCallback = function() {
                console.log('Stub dubadub dub'); //note...i can use sinon.spy here instead
    };

   beforeEach(()=&gt;{
            OuterDependency.PromiseFunction = function(arg) {
               return  new Promise((resolve, reject)=&gt;{
                   reject('BAD');
               });
            };


            spy = sinon.spy(stubCallback);
       });
</code></pre>

<p>my actual test now calls the main ""testfunction"" </p>

<pre><code>it('Catches Errors, and calls back using error', done =&gt; {
            TestFunction(stubCallback);
            expect(spy).to.have.been.called;
            done();
        });
</code></pre>

<p>I see the stub being called (the console log, hence why i didnt want to use sinon.spy)  but the spy is saying its not called. and unit test fails.</p>

<p>I believe this is probably due to a race condition of sorts where the promise is resolving after my test is run... is there anyway to delay the test until my promise is resolve.</p>

<p>i know in in angularjs promise testing, there was a way to ""tick"" the promise so it resolves when you want to. possible in nodejs?</p>
",https://stackoverflow.com/questions/47554438/unit-testing-nodejs-promise-inside-a-function,"['javascript', 'node.js', 'unit-testing', 'mocha.js']",1486,TRUE,1,1
Unit testing image tag with image object,"<p>i have following reactjs code snippet:</p>

<pre><code>import lionIcon from 'assets/images/lion.svg';
import dogIcon from 'assets/images/dog.svg';

&lt;img
    className=""animal-btn-img""
    src={isLion ? lionIcon : dogIcon}
  /&gt;
</code></pre>

<p>how do i unit test that based on 'isLion' prop, appropriate animal object is set on the img tag.?</p>

<pre><code>let img = wrapper.find('.animal-btn-img');
console.log(img.prop('src'));
</code></pre>

<p>the above console.log returns only empty object as {}</p>
",https://stackoverflow.com/questions/47675781/unit-testing-image-tag-with-image-object,"['reactjs', 'enzyme']",3309,TRUE,1,1
Unit testing angular directive with link function,"<p>My link function of a directive</p>

<ol>
<li>shows some dummy mock</li>
<li>ask for external data (promise).</li>
<li>Whenever the promise resolves or rejectes dummy data is hidden</li>
</ol>

<p>Is there a way to unit test directive, checking that the dummy data is presented namely is it possible to </p>

<ol>
<li>compile directive</li>
<li>do not resolve promises</li>
</ol>

<p>as both $apply and $digest are resolving the promise and in unit test i am either before compilation or after compilation and promise resolving.</p>
",https://stackoverflow.com/questions/46276726/unit-testing-angular-directive-with-link-function,"['javascript', 'unit-testing', 'angularjs-directive']",38,FALSE,1,0
Unit testing mock DbContext DbSet&lt;&gt; is null,"<p>Trying to write unit tests that run against <code>DbContext</code>, in .Net Core. I have performed the same in full framework EF and all works. </p>

<p>The code below represents the minimum code to recreate the issue. I have stripped out anything that isn't implemented</p>

<p>I have the following mocks</p>

<pre><code>// DbContext
public class MockDbContext : DbContext
{
    public virtual DbSet&lt;State&gt; State { get; set; }
}
</code></pre>

<p>The Repository</p>

<pre><code>// Mock of my repository
public class MockRepository&lt;TModel&gt; : IRepository&lt;TModel&gt; where TModel : class
{
    MockDbContext _context;
    DbSet&lt;TModel&gt; _dbSet;

    public MockRepository(MockDbContext context)
    {
        _context = context;
        // THIS IS NULL
        _dbSet = _context.Set&lt;TModel&gt;();
    }

    public async Task&lt;IList&lt;TModel&gt;&gt; GetAllAsync()
    {
        return _dbSet.ToListAsync().Result;
    }

    public void Add(TModel t)
    {
        _context.Add(t);
    }
}
</code></pre>

<p>The Unit of work</p>

<pre><code>// Unit of work
public class MockUnitOfWork : IUnitOfWork
{
    private Mock&lt;MockDbContext&gt; _mockDbContext;
    private IRepository&lt;State&gt; _stateRepo;

    public MockUnitOfWork()
    {
        var mockState = new List&lt;State&gt;() { new State { StateId = 1, Name = ""Added"" }, new State { StateId = 1, Name = ""Deleted"" } }.AsQueryable();

        var mockStateSet = new Mock&lt;DbSet&lt;State&gt;&gt;();
        mockStateSet.As&lt;IQueryable&lt;State&gt;&gt;().Setup(m =&gt; m.Provider).Returns(mockState.Provider);
        mockStateSet.As&lt;IQueryable&lt;State&gt;&gt;().Setup(m =&gt; m.Expression).Returns(mockState.Expression);
        mockStateSet.As&lt;IQueryable&lt;State&gt;&gt;().Setup(m =&gt; m.ElementType).Returns(mockState.ElementType);
        mockStateSet.As&lt;IQueryable&lt;State&gt;&gt;().Setup(m =&gt; m.GetEnumerator()).Returns(mockState.GetEnumerator());


        _mockDbContext = new Mock&lt;MockDbContext&gt;();
        _mockDbContext.Setup(o =&gt; o.State).Returns(mockStateSet.Object);
    }       
    public void SaveAsync()
    {
        _mockDbContext.Object.SaveChanges();
    }

    public IRepository&lt;State&gt; StateRepository =&gt; _stateRepo ?? (_stateRepo = new MockRepository&lt;State&gt;(_mockDbContext.Object));
}
</code></pre>

<p>I'm attempting to test some service code, which isn't included here, though the problem can be recreated by calling the following, from a test method.</p>

<pre><code>MockUnitOfWork unitOfWork = new MockUnitOfWork();
var x = unitOfWork.StateRepository.GetAllAsync().Result;
</code></pre>

<p>We also have an extension that implements pretty much what can be found <a href=""https://msdn.microsoft.com/en-us/library/dn314429.aspx"" rel=""nofollow noreferrer"">Entity Framework Testing with a Mocking Framework</a> under the testing async section. This also results in a null on the <code>DbSet&lt;&gt;</code></p>

<p>Any idea what i might be missing?</p>
",https://stackoverflow.com/questions/47891001/unit-testing-mock-dbcontext-dbset-is-null,"['c#', 'entity-framework', 'unit-testing', 'moq']",2002,TRUE,1,1
Unit testing a signed assembly in C#,"<p>I'm attempting to write some unit tests for a strongly named assembly. The unit tests are in a UnitTests project, the code is in a Plugins project, and they are both part of the same solution. Plugins is strongly signed. UnitTests has a reference to Plugins and everything compiles nicely.</p>

<p>When I try to run a test the test fails with an exception, ""Could not load file or assembly... Strong name validation failed""</p>

<p>If I disable signing for Plugins the tests work, but signing is required for how the plugins are used. How can I solve this?</p>
",https://stackoverflow.com/questions/44395836/unit-testing-a-signed-assembly-in-c,"['c#', 'unit-testing', 'code-signing']",1088,FALSE,1,1
Angular2 Component Unit Testing with Service Dependency,"<p>So I have this PromptComponent and the content will be updated by a service data.
Now I am trying to do the unit test this component which has this service dependency. 
Here is the Component:</p>

<pre><code>export class PromptComponent {
    @Input() module: any;
    @select() selectedPrompt;
    constructor(private moduleService: ModuleService){}
}
</code></pre>

<p>Here is the service:</p>

<pre><code>  getQuote(): Promise&lt;string&gt; {
    return new Promise(resolve =&gt; {
      setTimeout( () =&gt; resolve(this.nextQuote()), 500 );
    });
  }
  private nextQuote() {
    if (this.next === quotes.length) { this.next = 0; }
    return quotes[ this.next++ ];
  }
</code></pre>

<p>Here is the unit test code: </p>

<pre><code>  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [
        PromptComponent,
      ],
      providers: [ ModuleService]
    });

    fixture = TestBed.createComponent(PromptComponent);
    component = fixture.componentInstance;
    const moduleService = fixture.debugElement.injector.get(ModuleService);
    spy = spyOn(moduleService, 'getQuote').and.returnValue(Promise.resolve(testService));  
</code></pre>

<p>I referred to the official demo on the angular documentation 
<a href=""https://angular.io/resources/live-examples/testing/ts/eplnkr.html"" rel=""nofollow noreferrer"">https://angular.io/resources/live-examples/testing/ts/eplnkr.html</a>, as inside the TwainComponent.spec. </p>

<p>Something really weird is that as expected, inside the official demo, the TwainComponent test passed smoothly. But I, on the other hand, got this strange injectionError. If I remove the parameter inside the constructor, I am able to create the fixture instance but get injection error when it runs thorught the injector.get() part. But as soon as I put the <code>private moduleService:ModuleService</code> back inside the component constructor, I will get fixture undefined and also with the injection error. </p>

<p>So that means I cannot even execute my code to the actual service injection part (<code>fixture.debugElement.injector.get(ModuleService)</code>), I already got the error.</p>

<p>Does anybody have the same issue? 
My code is almost identical to the demo code on Plunker. Have no clue how to move forward....</p>
",https://stackoverflow.com/questions/43668026/angular2-component-unit-testing-with-service-dependency,"['unit-testing', 'angular', 'service', 'dependency-injection', 'jasmine']",739,FALSE,1,0
wordpress-develop unit testing couldn&#39;t fetch mysqli,"<p>I've seen a lot of mysqli errors on stack overflow, but none seem to relate to wordpress-develop</p>

<p>I set up the test folder, bootstrap.php.</p>

<pre><code>if ( function_exists( 'xdebug_disable' ) ) {
xdebug_disable();
}
if ( false !== getenv( 'WP_DEVELOP_DIR' ) ) {
require getenv( 'WP_DEVELOP_DIR' ) . '\tests\phpunit\includes\bootstrap.php';
}
if ( false !== getenv( 'WP_PLUGIN_DIR' ) ) {
define( 'WP_PLUGIN_DIR', getenv( 'WP_PLUGIN_DIR' ) );
}
</code></pre>

<p>phpunit.xml</p>

<pre><code>&lt;phpunit bootstrap=""tests/bootstrap.php""&gt;
    &lt;testsuites&gt;
        &lt;testsuite&gt;
            &lt;directory prefix=""test-"" suffix="".php""&gt;./tests/&lt;/directory&gt;
        &lt;/testsuite&gt;
    &lt;/testsuites&gt;
&lt;/phpunit&gt;
</code></pre>

<p>config</p>

<pre><code>define( 'DB_NAME', 'bitnami_wordpress_testing' );
define( 'DB_USER', 'root' );
define( 'DB_PASSWORD', '' );
define( 'DB_HOST', 'localhost' );
define( 'DB_CHARSET', 'utf8' );
define( 'DB_COLLATE', '' );
</code></pre>

<p>When I run a simple test</p>

<pre><code>class test extends WP_UnitTestCase {
    public function test_foo_is_foo() {
        $this-&gt;assertTrue( 'foo' === 'foo' );
    }
}
</code></pre>

<p>I get the result along with a slew of warnings.</p>

<pre><code>PHP Warning:  mysqli_query(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1812
PHP Warning:  mysqli_errno(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1708
PHP Warning:  mysqli_error(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1735
PHP Warning:  mysqli_affected_rows(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1760
PHP Warning:  mysqli_query(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1812
PHP Warning:  mysqli_errno(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1708
PHP Warning:  mysqli_error(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1735
PHP Warning:  mysqli_affected_rows(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1760
PHP Warning:  mysqli_query(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1812
PHP Warning:  mysqli_errno(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1708
PHP Warning:  mysqli_error(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1735
PHP Warning:  mysqli_affected_rows(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1760
PHP Warning:  mysqli_query(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1812
PHP Warning:  mysqli_errno(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1708
PHP Warning:  mysqli_error(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1735
PHP Warning:  mysqli_affected_rows(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1760
PHP Warning:  mysqli_query(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1812
PHP Warning:  mysqli_errno(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1708
PHP Warning:  mysqli_error(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1735
PHP Warning:  mysqli_affected_rows(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1760
PHP Warning:  mysqli_query(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1812
PHP Warning:  mysqli_errno(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1708
PHP Warning:  mysqli_error(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1735
PHP Warning:  mysqli_affected_rows(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1760
PHP Warning:  mysqli_query(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1812
PHP Warning:  mysqli_errno(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1708
PHP Warning:  mysqli_error(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1735
PHP Warning:  mysqli_affected_rows(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1760
PHP Warning:  mysqli_query(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1812
PHP Warning:  mysqli_errno(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1708
PHP Warning:  mysqli_error(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1735
PHP Warning:  mysqli_affected_rows(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1760
PHP Warning:  mysqli_query(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1812
PHP Warning:  mysqli_errno(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1708
PHP Warning:  mysqli_error(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1735
PHP Warning:  mysqli_affected_rows(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1760
PHP Warning:  mysqli_query(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1812
PHP Warning:  mysqli_errno(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1708
PHP Warning:  mysqli_error(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1735
PHP Warning:  mysqli_affected_rows(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1760
PHP Warning:  mysqli_query(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1812
PHP Warning:  mysqli_errno(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1708
PHP Warning:  mysqli_error(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1735
PHP Warning:  mysqli_affected_rows(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1760
PHP Warning:  mysqli_query(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1812
PHP Warning:  mysqli_errno(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1708
PHP Warning:  mysqli_error(): Couldn't fetch mysqli in C:\Documents\wordpress-develop\src\wp-includes\wp-db.php on line 1735
</code></pre>

<p>I tested a couple basic methods and don't seem to be getting info from the database either. Not sure if there is any significance in the fact that the warnings are repeated. Does anyone with wordpress-develop experience know where this issue is likely coming from. Or perhaps anyone know of a better method/preferred tutorial for getting unit testing with wordpress up and running?</p>
",https://stackoverflow.com/questions/45989601/wordpress-develop-unit-testing-couldnt-fetch-mysqli,"['wordpress', 'mysqli', 'phpunit']",221,FALSE,1,1
Spring boot Integration unit testing NoSuchBeanDefinitionException exception,"<p>I created a sample IntegrationFlow as shown below:</p>

<pre><code>@Configuration
@EnableIntegration
@IntegrationComponentScan
@ComponentScan
public class RegisterHostFlow {
  private final Logger LOG = LoggerFactory.getLogger(this.getClass());

  @MessagingGateway
  public interface RegisterHostGateway{
      @Gateway(requestChannel = ""registerHostInputChannel"")
      Host registerHost(Host host);
  }

  @Bean
  public IntegrationFlow httpInboundGatewayFlow() {
      return IntegrationFlows.from(""registerHostInputChannel"")
            .handle((host, headers) -&gt;  {
                        return host;
            })
            .enrich(e -&gt; e
                    .requestPayload(Message::getPayload)
                    .property(""uuid"", ""34563456345634563456"")
                    .property(""id"", ""1234"")
            )
            .get();
  }
}
</code></pre>

<p>I am calling this from a spring MVC controller as below:</p>

<pre><code>RegisterHostFlow.RegisterHostGateway registerHostGateway = applicationContext.getBean(RegisterHostFlow.RegisterHostGateway.class);
    Host host1 = registerHostGateway.registerHost(host);
</code></pre>

<p>When I write a unit test to do some sanity testing as shown below, application fails to load with the error, NoSuchBeanException:</p>

<pre><code>@RunWith(SpringRunner.class)
@WebMvcTest(HostController.class)
@EnableIntegration
@IntegrationComponentScan
public class HostControllerTest {
 @Autowired
 private MockMvc mvc;

@Test
public void  registerHost_passedInHost_returnJson() throws Exception {
    this.mvc.perform(post(""/hostservice/v1/hosts"").contentType(MediaType.APPLICATION_JSON). content('someJsonStringGoesHere'))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8));
}
</code></pre>

<p>Below is the exception I see:</p>

<pre><code>org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'registerHostInputChannel' available

at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
</code></pre>

<p>Any pointers to how to have ApplicationContext autowire the integration beans when in test mode?</p>
",https://stackoverflow.com/questions/43878692/spring-boot-integration-unit-testing-nosuchbeandefinitionexception-exception,"['spring-boot', 'spring-integration', 'spring-mvc-test']",774,TRUE,1,1
Unit Testing C With Functions Not in Header,"<p>I'm starting to get into unit testing and I'm having trouble understanding something. My struggle boils down to how I would go about testing functions that are only in the .c source, and not declared in the .h header. There's certain functions that shouldn't need to be called outside of the implementation because they're only relevant to that specific file. Since they're not visible to other parts of the program, that means my unit testing cases file can't see those inner functions, therefore making me unable to test them. I've gone around the issue by using forward declarations in the test cases file, but that seems kinda messy and would get to be a pain to go and change if I modify the function parameters.</p>

<p>Are these functions just not meant to be covered by unit testing? I've read that with OOP, you shouldn't be testing private functions because they're tested implicitly through the public functions, but it feels uncomfortable to not have these functions covered (some of which can get quite complex).</p>
",https://stackoverflow.com/questions/46531419/unit-testing-c-with-functions-not-in-header,"['c', 'unit-testing', 'automated-tests', 'private']",3758,TRUE,8,2
Angular: Unit Testing Routing : Expected &#39;&#39; to be &#39;/route&#39;,"<p>Am working on unit testing for my routing under my Angular app ,</p>

<p>My routes are delacred in a specific module which is imported under the app.module.ts , </p>

<p>here is my routing module:</p>

<p><strong>app-routing.module.ts</strong></p>

<pre><code>import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { LoginComponent } from './login/login.component';
import { WelcomeComponent } from './welcome/welcome.component';
import { CustomersListComponent } from './customer/customers-list/customers-list.component';
import { CustomerDetailComponent } from './customer/customer-detail/customer-detail.component';
import { ApplicationParametersComponent } from './superAdministrator/application-parameters/application-parameters.component';
import { InscriptionComponent } from './inscription/inscription.component';

const routes: Routes = [
  { path: '', redirectTo: '/login', pathMatch: 'full' },
  { path: 'login',  component: LoginComponent },
  { path: 'login/:keyWording',  component: LoginComponent },
  { path: 'welcome', component: WelcomeComponent },
  { path: 'customers-list', component: CustomersListComponent },
  { path: 'customer-create', component: CustomerDetailComponent },
  { path: 'customer-detail/:idCustomer', component: CustomerDetailComponent },
  { path: 'application-parameters', component: ApplicationParametersComponent },
  { path: 'inscription', component: InscriptionComponent }
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}
</code></pre>

<p>Here is my app.module.ts (where am used to import the routing module :</p>

<pre><code>import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { SharedModule } from './../shared/shared.module';
import { LoginComponent } from './login/login.component';
import { WelcomeComponent } from './welcome/welcome.component';
import { AppComponent } from './app.component';
import { CustomerModule } from './customer/customer.module';
import { ApplicationParametersComponent } from './superAdministrator/application-parameters/application-parameters.component';
import { InscriptionComponent } from './inscription/inscription.component';

import { DxProgressBarModule } from 'devextreme-angular';

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    WelcomeComponent,
    ApplicationParametersComponent,
    InscriptionComponent
  ],
  imports: [
    AppRoutingModule, /* HERE IS THE ROUTING FILE */

    SharedModule,
    CustomerModule,
    DxProgressBarModule/*,
    BrowserAnimationsModule,
    BrowserModule*/
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code></pre>

<p>Under my test file , i followed the tuto from this blog :
<a href=""https://codecraft.tv/courses/angular/unit-testing/routing/"" rel=""noreferrer"">https://codecraft.tv/courses/angular/unit-testing/routing/</a></p>

<p>My test file for the routing testing is the following :</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
// DevExtreme Module
import {DxProgressBarModule, DxTemplateModule} from 'devextreme-angular';
// Router Modules
import {RouterTestingModule} from '@angular/router/testing';
// Services and HTTP Module
import { SessionService } from './../shared/service';
import { HttpService } from './../shared/service';
import {HttpModule} from '@angular/http';
// Routs testing
import {Router, RouterModule} from '@angular/router';
import {fakeAsync, tick} from '@angular/core/testing';
import {Location} from '@angular/common';
import {LoginComponent} from './login/login.component';
import {WelcomeComponent} from './welcome/welcome.component';
import {ApplicationParametersComponent} from './superAdministrator/application-parameters/application-parameters.component';
import {InscriptionComponent} from './inscription/inscription.component';
import {CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';
import {FormsModule} from '@angular/forms';


describe('Testing the application routes', () =&gt; {

  let location: Location;
  let router: Router;
  let fixture;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule, FormsModule , DxTemplateModule , HttpModule ],
      providers:    [SessionService , HttpService ],
      declarations: [
        AppComponent,
        LoginComponent,
        WelcomeComponent,
        ApplicationParametersComponent,
        InscriptionComponent
      ],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ]

    });

    router = TestBed.get(Router);
    location = TestBed.get(Location);

    fixture = TestBed.createComponent(AppComponent);
    router.initialNavigation();
  });

  it('navigate to ""inscription"" takes you to /inscription', fakeAsync(() =&gt; {
    router.navigate(['inscription']);
    tick();
    expect(location.path()).toBe('/inscription');
  }));
});
</code></pre>

<p>My test fails , indicating this :</p>

<pre><code>Expected '' to be '/inscription'.
    at Object.&lt;anonymous&gt; (webpack:///src/app/app-routing.spec.ts:52:28 &lt;- src/test.ts:143891:33)
    at Object.&lt;anonymous&gt; (webpack:///~/@angular/core/@angular/core/testing.es5.js:348:0 &lt;- src/test.ts:34691:26)
    at ZoneDelegate.invoke (webpack:///~/zone.js/dist/zone.js:391:0 &lt;- src/polyfills.ts:1546:26)
    at ProxyZoneSpec.Array.concat.ProxyZoneSpec.onInvoke (webpack:///~/zone.js/dist/proxy.js:79:0 &lt;- src/test.ts:232357:39)
</code></pre>

<p><strong>Ideas ??</strong></p>
",https://stackoverflow.com/questions/45564557/angular-unit-testing-routing-expected-to-be-route,"['angular', 'unit-testing', 'typescript', 'routes', 'karma-jasmine']",14602,TRUE,8,1
"MVC, MOQ Unit Testing Web API Method","<p>I've been following a regular pattern for unit testing my Web API methods using MOQ.  This time I have a controller method that's a little different and I can't figure out why the test is failing.</p>

<p>Here's the standard look of one of our methods.  We make a call to the repository and return OK.</p>

<p><strong>API Method</strong></p>

<pre><code>    [HttpPost]
    public IHttpActionResult SampleMethod(SampleModel model)
    {
        var result= _myRepository.SampleMethod(model.Field1, model.Field2);

        return Ok();
    }
</code></pre>

<p>I usually use the following tests for something like this.</p>

<p><strong>Unit Tests</strong></p>

<pre><code>    /// &lt;summary&gt;
    /// Tests the SampleMethod is run
    /// &lt;/summary&gt;
    [TestMethod]
    public void SampleMethod_Is_Run()
    {
        //Arrange
        mockRepository
          .Setup(x =&gt; x.SampleMethod(It.IsAny&lt;string&gt;(), It.IsAny&lt;string&gt;()))
          .Returns(It.IsAny&lt;EmailItem&gt;());  //forgot to add this the first time
        var controller = new MyController(mockRepository.Object);

        //Act
        controller.SampleMethod(It.IsAny&lt;string&gt;(), It.IsAny&lt;string&gt;());

        //Assert
        mockRepository.VerifyAll();
    }

    /// &lt;summary&gt;
    /// Tests the SampleMethod returns correct status code
    /// &lt;/summary&gt;
    [TestMethod]
    public void SampleMethod_Returns_OK()
    {
        //Arrange
        mockRepository
          .Setup(x =&gt; x.SampleMethod(It.IsAny&lt;string&gt;(), It.IsAny&lt;string&gt;()))
          .Returns(It.IsAny&lt;EmailItem&gt;());  //forgot to add this the first time;
        var controller = new MyController(mockRepository.Object);
        controller.Request = new HttpRequestMessage();
        controller.Configuration = new HttpConfiguration();

        //Act
        var response = controller.SampleMethod(It.IsAny&lt;string&gt;(), It.IsAny&lt;string&gt;());

        //Assert
        Assert.IsInstanceOfType(response, typeof(OkResult));
    }
</code></pre>

<p>Now let's say I have a method like this, which calls off to another class for sending an email.  Why won't those unit tests work anymore?</p>

<p><strong>New API Method</strong></p>

<pre><code>    [HttpPost]
    public IHttpActionResult SampleMethod(SampleModel model)
    {
        var emailItem= _myRepository.SampleMethod(model.Field1, model.Field2);

        //With this additional code, the test will fail
        EmailSender emailSender = new EmailSender();
        emailSender.BuildEmail(emailItem.ToAddress, emailItem.Subject);

        return Ok();
    }
</code></pre>

<p>The error message on test fail I get is this, but there is no where to see extra exception information.</p>

<pre><code>    ""System.Web.Http.HttpResponseException: Processing of the HTTP request resulted in an exception.  Please see the HTTP response returned by 'Response' property of this exception for details.""
</code></pre>
",https://stackoverflow.com/questions/44803961/mvc-moq-unit-testing-web-api-method,"['c#', 'asp.net', 'unit-testing', 'model-view-controller', 'moq']",1997,TRUE,1,1
JavaScript: Unit Testing Factory Function Default Parameters,"<p>Here is a simple factory function that I want to test using Mocha to make sure that it is run with the proper default parameters.</p>

<p>I had the intuition that Sinon Spies were the right tools for the job but it seems, from the documentation and online examples that they only work on object methods?!</p>

<pre><code>function foo (bar=baz) {
  // do something with bar here
  // more code...
  return somethingOtherThanBar
}
</code></pre>

<p>The test should enable me to check that <strong>bar</strong> is indeed <strong>baz</strong>.</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/44915472/javascript-unit-testing-factory-function-default-parameters,"['javascript', 'unit-testing', 'mocha.js', 'sinon']",580,FALSE,1,0
Unit testing generators with `return` and `yield`,"<p><strong>Given this function</strong></p>

<pre><code>function* backflip(query) {
  return yield 123;
}
</code></pre>

<p><strong>And this test</strong></p>

<pre><code>describe('backflip', () =&gt;
  it('should do that ^', () =&gt;
    let handlerInstance = handler();
    expect(handlerInstance.next().value).to.equal(123);
    expect(handlerInstance.next().done).to.equal(true);
  );
);
</code></pre>

<p>Istanbul, should say all branches are covered, but in fact this covers 3 of 4. Removing <code>return</code> fixes the problem. </p>

<ul>
<li>Is <code>return</code> and <code>yield</code> together an antipattern?</li>
<li>Is this a bug?</li>
</ul>

<p><strong>For context, Babel compiles this as</strong></p>

<pre><code>""use strict"";

var _marked = [backflip].map(regeneratorRuntime.mark);

function backflip(query) {
  return regeneratorRuntime.wrap(function backflip$(_context) {
    while (1) {
      switch (_context.prev = _context.next) {
        case 0:
          _context.next = 2;
          return 123;

        case 2:
          return _context.abrupt(""return"", _context.sent);

        case 3:
        case ""end"":
          return _context.stop();
      }
    }
  }, _marked[0], this);
}
</code></pre>
",https://stackoverflow.com/questions/42307997/unit-testing-generators-with-return-and-yield,"['unit-testing', 'ecmascript-6', 'generator', 'babeljs', 'istanbul']",354,TRUE,1,2
Unit Testing Z Entity Framework Plus Extensions,"<p>When using Z.EntityFramework.Plus extensions, I cannot find a way to mock/substitute what the context returns when any of the plus extensions, not just Future(), are being used. Everything I try throws a NullReferenceException within the z extensions future library. </p>

<p>Repository Example:</p>

<pre><code>public Task&lt;DocumentDomain&gt; GetDocuments(int id)
{
  var futureQuery1 = _context.ReportTypes.Where(x =&gt; x.IsReadOnly).Future();
  var futureQuery2 = _context.Reports.Where(x =&gt; x.CreateDate &lt; DateTime.Now.AddDays(-10)).Future();
  var futureQuery3 = _context.Person.DeferredFirstOrDefault(x =&gt; x.Id == id).FutureValue();

   return new DocumentDomain(futureQuery1.ToList(), futureQuery2.ToList(), futureQuery3.Value);
}
</code></pre>

<p>Unit Test Repository:</p>

<pre><code>    [Fact]
    public async Task ShouldGetDocumentsForPerson1()
    {
       _context = Substitute.For&lt;IMyDbContext&gt;();
       _context.ReportTypes = new FakeDbSet();
       _context.ReportTypes.AddRange(GetFakeReportTypes());
       // ...etc..arrange for Reports and Person

       var repo = new DocumentRepository(_context);

       // CRASHES HERE ON futureQuery1 at .Future()
       var domain = await repo.GetDocuments(1); // fake id

       Assert.IsTrue(domain.Documents.Count &gt; 0);
    }
</code></pre>

<p>Without using Futures it works fine. I've tried mocking out a few different ways but always get an error. Most of the time it's a ""oops Z extensions encountered an error"" exception. </p>

<p>I'm thinking it's because Z extensions is expecting a real ObjectContext but not sure how to overcome this. Has anyone experienced similar issues? Does anyone know of any solutions? Thanks.</p>
",https://stackoverflow.com/questions/45623651/unit-testing-z-entity-framework-plus-extensions,"['c#', 'entity-framework', 'unit-testing', 'nsubstitute', 'entity-framework-plus']",1553,TRUE,1,1
Haxe unit testing for the C# target,"<p>Being new to Haxe I'm trying to run munit tests for the C# target. Initially, I ran <code>haxelib run munit config</code> and successfully executed tests in JavaScript and C++. I grabbed test.hxml straight from the example generated by the 'config' command.</p>

<p>When adapted to C#, <code>haxe run munit test</code> does practically nothing (only prints <em>Massive Unit - Copyright 2017 Massive Interactive. Version 2.1.2</em> to console).</p>

<p>Is this expected behavior? Is something not supported for C# as of now? How do I run unit tests written in Haxe for C# target?</p>

<p>Below is modified test.hxml:</p>

<pre><code># CSharp
-main TestMain
-lib munit
-lib hamcrest
-cp src

-cp test
-cs build/csharp_test
</code></pre>

<p>Also, please notice that I have no issues compiling to C# target in general, as well as executing apps built for C# target.</p>

<p>Haxe version: <em>3.4.2 (git build master @ 890f8c7)</em></p>
",https://stackoverflow.com/questions/43467996/haxe-unit-testing-for-the-c-target,['haxe'],141,TRUE,1,2
Unit Testing Mongoose Model Callback with Sinon,"<p>I have code that looks like this:</p>

<pre><code>function dummy (options, callback) {
  MModel.find({x: options.y},
  function (err, res) {
    if (err) {
      return callback(err);
    }
    if (res) {
      callback(null, res.sort({timestamp : 1}));
    } else {
      callback(null, {});
    }
  }).sort({timestamp : -1}).limit(5);
}
</code></pre>

<p>I am attempting to unit test this function however I cannot stub the function MModel.find because it has a res.sort within it and a .sort followed by a .limit outside. If I use a stub it says that the .sort is a property and cannot be used as a function. The next thing I tried was mocking the model itself using sinon-mongoose, however, I was running into the issue that exec is not a function since I was following the sinon-mongoose documentation:</p>

<pre><code>sinon.mock(MongooseModel)
  .expects('find')
  .chain('limit').withArgs(10)
  .chain('sort').withArgs('-date')
  .chain('exec')
  .yields(null, 'SOME_VALUE');
</code></pre>

<p>I added the done callback and played around with adding the done callback to expects('find').withArgs({ x: 'abc' }, done) and it was giving me an expectation error that said ""unexpected function find({ x:'abc'}, function (){}) when expected function is find({ x:'abc'}, function (){}[,...])"". Does anybody know what function (){}[,...] means as compared to function (){}?</p>

<p>Any help is appreciated. Thanks!</p>
",https://stackoverflow.com/questions/44188675/unit-testing-mongoose-model-callback-with-sinon,"['javascript', 'unit-testing', 'mongoose', 'mocking', 'sinon']",145,FALSE,1,1
Asp.Net MVC Angularjs Unit testing without nodejs,"<p>The application I am currently working have a Asp.Net MVC serving up the pages and angularjs on the client side. I am looking to set up the unit testing on the angularjs controllers, services. Is there a way to set up unit testing for angularjs scripts without NodeJs. Or is the only way to Unit test the client side contollers through Grunt, Jasmine and Karma and mentioned on most of the articles.
Thank you</p>
",https://stackoverflow.com/questions/41876977/asp-net-mvc-angularjs-unit-testing-without-nodejs,"['angularjs', 'asp.net-mvc', 'unit-testing']",74,FALSE,1,1
Unit testing &quot;invisible&quot;/&quot;implementation dependent&quot; private fields?,"<p>Well I have a unit that does some really expensive calculations. (I have  decently high resolution heatmap-images captured by a high speed camera from a windtunnel experiment and I need to calculate the airspeed based on the heat transfer per time during a linear part).  </p>

<p>Typically a prelimenary calculation ""takes"" between 10 seconds and a few minutes for a single ""timeframe and test"".<br>
However for a different timeframe, a lot of the calculations are ""similar"". So at some point I started adding a caching of the calculations.</p>

<p>Now this is completely internal to the class, without any visibility to the outside world (As it should be).<br>
I can test if the ""caching is correct"" by running the calculations on a ""hot"" and a ""cool"" class.</p>

<p>However how would I check that the cached value is even stored at all? Should I try to inspect the private stat? Also at the moment this is just a project for me learning to C# (implementing old projects from python); if this project was based on TDD, how would I write a TDD test description to describe such a caching property? The only visible external indication is that ""the function is a few times faster"". But I can't test against that really.</p>
",https://stackoverflow.com/questions/42335862/unit-testing-invisible-implementation-dependent-private-fields,"['c#', 'unit-testing']",54,FALSE,1,0
Unit testing the c# double lock pattern,"<p>I'm experimenting writing some unit tests for the following code</p>

<pre><code>private bool _initCalled = false;
private void Initialize()
{
    if (!_initCalled)
    {
        lock (this)
        {
            if (_initCalled)
                return;
            NoConfigInit();
            _initCalled = true;
        }
    }
}
</code></pre>

<p>What is the best way to test this code to hit the code path <code>if (_initCalled) return</code>?</p>

<p>Alternative ways of representing this code are also welcome, but I'm curious about how to test these patterns for correctness.</p>
",https://stackoverflow.com/questions/44560640/unit-testing-the-c-double-lock-pattern,"['c#', 'unit-testing']",961,TRUE,1,2
Unit testing in Angular 2 using karma,"<p>I have been trying to understand how unit testing works in angular , I am still trying to understand angular 2 and its syntax which is making trying to understand testing a little more difficult.More or less I try to follow the examples listed here :<a href=""https://angular.io/docs/ts/latest/guide/testing.html#!#testbed"" rel=""nofollow noreferrer"">https://angular.io/docs/ts/latest/guide/testing.html#!#testbed</a></p>

<p>In my project I have component </p>

<p>workflow-display.component:</p>

<pre><code>import { Component,Input} from '@angular/core';
//some other imports hidden

@Component({
    selector: 'workflow-display',
    template: require('./workflow-display.component.html')
})
export class WorkflowDisplayComponent implements OnInit {

    taskQuery: string = 'process=workstream&amp;taskStatus=RUNNING'; // the query parameters to pass to the tasks web service
    workbenchTaskPage: string = 'wsIndex'; // workbench page to use to open tasks
    tasks: IGrcTask[];
    currentTask: IGrcTask;
    @Input()
    environment: String;
    //some properties may hidden due to being irrelevant to the question




    constructor(private _workflowService: WorkflowService) {

    }

   //some other functions hidden

    //called on double click event in the html dom,THIS IS the function I want to test
    openTask(event: any, task: any) {
        //this.enviroment is initiliaze/bound by app.component through one way binding
        window.open(this.environment + this.workbenchTaskPage + ""?taskId="" + task.taskId + ""&amp;activitiWorkflow=true"");
    }



}
</code></pre>

<p>This is my HMTL template page </p>

<p>workflow-display.component.html:</p>

<pre><code> &lt;!--container div ,table and other HTML hidden--&gt;

                    &lt;tbody *ngIf='!tasks || tasks.length == 0'&gt;
                      &lt;tr&gt;
                          &lt;td align=""left"" colspan=""8""&gt;There are no tasks.&lt;/td&gt;
                      &lt;/tr&gt;
                    &lt;/tbody&gt;

                    &lt;tbody *ngIf='(taskMode == ""workorder"") &amp;&amp; tasks &amp;&amp; tasks.length'&gt;
                      &lt;ng-container *ngFor='let task of tasks; let i=index'&gt;
                          &lt;tr (dblclick)=""openTask($event, task)""
                            id=""workspace_table_wo_{{ task.workOrderId }}_task_{{ task.taskId }}_workorder""
                            [class.table-active]=""isSelected(task)""&gt;
    &lt;!--remaining html hidden to avoid been clear--&gt;
</code></pre>

<p>So I want to test basically couple of things ,firstly that the DOM i.e each tr has the appropriate event i.e <code>(dblclick)=""openTask($event, task)""</code> and the opentask function itself ,not sure what the exact way to go about is.</p>

<p>My attempted spec file,I didn't write any test yet ,This is where I am wanting..</p>

<p>workflow-display.component.spec.ts:</p>

<pre><code>import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By }              from '@angular/platform-browser';
import { DebugElement }    from '@angular/core';

import { WorkflowDisplayComponent } from './workflow-display.component';

describe('WorkflowDisplayComponent (inline template)', () =&gt; {

    let comp:    WorkflowDisplayComponent;
    let fixture: ComponentFixture&lt;WorkflowDisplayComponent&gt;;
    let de:      DebugElement;      //Element to test
    let el:      HTMLElement;       //HMTL of element

    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            declarations: [ WorkflowDisplayComponent ], // declare the test component
        });

        fixture = TestBed.createComponent(WorkflowDisplayComponent);

        comp = fixture.componentInstance; // BannerComponent test instance

        // query for the title &lt;h1&gt; by CSS element selector
        de = fixture.debugElement.query(By.css('good way to select the tr??'));
        el = de.nativeElement;
    });
});
</code></pre>
",https://stackoverflow.com/questions/41946339/unit-testing-in-angular-2-using-karma,"['angular', 'typescript', 'karma-jasmine']",2851,TRUE,1,1
Unit testing BLE application in IOS (Swift),"<p>We've developed an app that connects to a BLE dongle and everything is working thru the BLE connection.</p>

<p>Now we decided to add Unit testing ( And Yes, i know it is much better to do TDD and not this way but this is the situation)</p>

<p>In the app everything is working, but when i'm trying to develop the unit tests i can't go pass the connection phase (GAT) i'm not getting the connection working an in any case the tests go thru one after the other and don't stop to wait for the connection to happen and authentication and nothing)</p>

<pre><code>func testConnect() {
    if viewController == nil {
        let storyboard = UIStoryboard(name: ""Main"", bundle: nil)
        viewController = storyboard.instantiateViewController(withIdentifier: ""ViewController"") as? ViewController

        if let vc = viewController {
            _ = vc.view
        }
    }

    viewController?.connectBluetooth();
}


func testAuthenticateByPin() {
    delay(5) {
        var error: NSError? = nil

        self.datConnection?.connect(""ABCDEFG"", withError: &amp;error)
        XCTAssertNotNil(error, ""Connect Error: \(String(describing: error))"")
        print(""Connection: \(String(describing: error))"")

        self.datConnection?.authenticate(byPIN: ""AD$FGR#"", withError: &amp;error)
        XCTAssertNotNil(error, ""Error: \(String(describing: error))"")
        print(""Auth: \(String(describing: error))"")
    }
}



func delay(_ delay:Double, closure:@escaping ()-&gt;()) {
    let when = DispatchTime.now() + delay
    DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}
</code></pre>

<p><strong>Any one knows how to create a BLE unit test and how to create a Delay between unit tests?</strong></p>
",https://stackoverflow.com/questions/47667575/unit-testing-ble-application-in-ios-swift,"['ios', 'swift', 'unit-testing']",738,TRUE,1,1
Unit testing PHP that calls filesystem functions,"<p>I want to test a new method in a helper class with phpUnit.</p>

<pre><code>public function removeDuplicateLines() {
    $lines = file($this-&gt;getFilePath());
    $lines = array_unique($lines);
    file_put_contents($this-&gt;getFilePath(), implode($lines));
}
</code></pre>

<p>Is it possible to test a method that calls file() and file_put_contents(), without creating a file in the test case itself? Is there a recommended way to test the above method in PHP?</p>
",https://stackoverflow.com/questions/42014894/unit-testing-php-that-calls-filesystem-functions,"['php', 'unit-testing', 'filesystems']",43,TRUE,1,2
Unit testing for domain classes using Grails,"<p>Currently searching for tutorials, explanations and examples.
I've tried different examples and came up to different errors.
My current error is :</p>

<blockquote>
  <p>| Error Compilation error compiling [unit] tests: startup failed:</p>
</blockquote>

<p>and in my test reports. It outputs this :</p>

<p><strong>Unit Test Results - Summary
No tests executed.</strong></p>

<p>My ""UserSpec.groovy"" code is this :</p>

<pre><code>package newmyproject245

import grails.test.mixin.*
import spock.lang.Specification

@TestFor(User)
class UserSpec extends ConstraintSpecification {

    def setup() {
        Expectations.applyTo User
    }

    def cleanup() {
    }

    void testShouldDoNothing() {
        Expectations.applyTo User

        user.""password is not blank""
        user.""password is not nullable""
        user.""name is not blank""
        user.""name is not nullable""
    }

    void testEventNameConstraints() {
        Expectations.applyTo User
        def user = new User()

        user.""name is not blank""
        user.""name is not nullable""
    }
}
</code></pre>

<p>Can anybody help. I'm new in grails.
Thanks!</p>

<p>Additional to the above problem,
when I omitted the <strong>Contraints</strong> in class as shown :</p>

<pre><code>class UserSpec extends Specification {
</code></pre>

<p>I came up to this error :</p>

<blockquote>
  <p>| Running 1 unit test... 1 of 1 
  | Failure: initializationError(org.junit.runner.manipulation.Filter) 
  | java.lang.Exception: No tests found matching grails test target
  pattern filter from org.junit.runner.Request$1@12c27788
    at org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:35)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:138) 
  | Completed 1 unit test, 1 failed in 0m 0s 
  | Error Fatal error running tests: Not-null property references a transient value - transient instance must be saved before current operation : newmyproject245.Order.product -> newmyproject245.Product; nested exception is org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved before current operation : newmyproject245.Order.product -> newmyproject245.Product (Use --stacktrace to see the full trace)</p>
</blockquote>

<p>someone help. Again, Thanks!</p>
",https://stackoverflow.com/questions/41438871/unit-testing-for-domain-classes-using-grails,"['unit-testing', 'grails', 'groovy']",1483,FALSE,1,1
Unit testing of SimpleChannelInboundHandler&lt;FullHTTPRequest&gt; in netty,"<p>I am new to netty framework.We have a API Handler implementing SimpleChannelInboundHandler and overriding the ChannelRead0 function that takes ChannelHandlerContext and the FullHTTPRequest.Now I need to do unit testing mocking the inputs.
Can anyone help me with this.</p>
",https://stackoverflow.com/questions/46782547/unit-testing-of-simplechannelinboundhandlerfullhttprequest-in-netty,"['unit-testing', 'mockito', 'netty']",723,FALSE,0,1
Mocha/Sinon - Unit testing promises in JavaScript,"<p>While learning <strong>electron</strong>, I decided I would also like to train testing techniques in JavaScript. I have following code:</p>

<pre><code>const winston = require('winston');
const AutoLaunch = require('auto-launch');

const launchFunction = (mb) =&gt; {
  const autolaunch = new AutoLaunch();

  autolaunch
    .isEnabled()
    .then((isEnabled) =&gt; {
      if (isEnabled) {
        return;
      }
      autolaunch.enable();
    })
    .catch((err) =&gt; {
      winston.error(err);
    });
};
</code></pre>

<p>I would like to assert if <strong>autolaunch.enabled()</strong> is properly triggered under specific condition and I have a lot of problem with writing any test that won't force me to create stub with exact copy of function from <strong>then()</strong>. There is an option that maybe something is wrong in this design of this solution - I can (and would like to) change code to make it more testable. How should I cope with that problem without compromising code testability?</p>

<p>I use <strong>mocha</strong> and <strong>sinon</strong> but I don't feel really attached to those tools</p>
",https://stackoverflow.com/questions/42378042/mocha-sinon-unit-testing-promises-in-javascript,"['javascript', 'unit-testing', 'mocha.js']",57,FALSE,-1,1
Matlab: Create workspace variables in unit testing,"<p>I have a class that read all variables from the workspace and get a list of all of them that are transfer functions (class type <code>tf</code>), and store them in another class (not represented here).</p>

<pre><code>classdef TransferFunctionFactory &lt; handle
  % This class allows to import a series of transfer function loaded from
  % different sources, like a file folder, workspace and so on..

  % Public section
  methods(Access = public)

    function collection = fromWorkspace(this)
      % Create a collection of transfer function that are stored in the workspace.
      % Returns:
      %  Collection of transfer functions.
      collection = App.TransferFunctionCollection();
      variables = who; % Here I should see w1, w2, w3, and w4 in variables
      for i = 1 : length(variables)
        if isa(eval(variables{i}), 'tf')
          trf = App.TransferFunction();
          trf.setAttribute('Name', variables{i});
          trf.setTransferFunction(eval(variables{i}));
          collection.addTransferFunction(trf);
        end
      end

    end
  end
</code></pre>

<p>I want to perform a unit testing, so I've created a test class:</p>

<pre><code>classdef TransferFunctionFactory &lt; matlab.unittest.TestCase

  methods (Test)

    function loadControllersFromWorkspace(testCase)
      collection = factory.fromWorkspace();
      testCase.verifyGreaterThanOrEqual(collection.getSize(), 3);
    end

  end

end
</code></pre>

<p>In order to perform unit testing, I need to set some variable in the workspace to be analysed from the function. I've tried something like:</p>

<pre><code>function loadControllersFromWorkspace(testCase)
  factory = App.TransferFunctionFactory();
  assignin('base', 'w1', tf(1 + 's'));
  assignin('base', 'w2', tf(3 / 's'));
  assignin('base', 'w3', 4.3);
  assignin('base', 'w4', tf(1 / ('s' + 1)));
  who
  collection = factory.fromWorkspace();
  testCase.verifyGreaterThanOrEqual(collection.getSize(), 3);
end
</code></pre>

<p>but it does not work. when I enter the <code>factory.fromWorkspace</code> method, I cannot see <code>w1</code>, <code>w2</code>, <code>w3</code>, <code>w4</code> as output of <code>who</code>, and I cannot use them.</p>

<p>How can I set variables in workspace in the unit test class method, so they are visible from functions/methods that are called inside the test? </p>
",https://stackoverflow.com/questions/45276376/matlab-create-workspace-variables-in-unit-testing,"['matlab', 'unit-testing', 'workspace']",329,TRUE,0,1
"React, how to simulate user input for unit testing?","<p>I have been trying to unit test a react component that takes in user input. More specifically I'm trying to test the <code>onChange</code> function within the react component. However I can't seem to set the input value, I've tried a few different ways suggested on the internet and none seem to work. Below is the component I'm trying to test.</p>

<pre><code>class Input extends Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event) {
    /* Check if max length has been set. If max length has been
    set make sure the user input is less than max Length, otherwise
    return before updating the text string. */
    if(this.props.maxLength) {
      if(event.target.value.length &gt; this.props.maxLength) {
        return;
      }
    }
    this.setState({ value: event.target.value });
  }

  render () {
    const { disabled, label, maxLength, multiline, type, value, ...others} = this.props;
    const theme = themeable(others.theme);

    let inputClassName = classNames({
      ""input"": type !== 'checkbox',
      ""checkbox"": type == 'checkbox',
      disabled,
      multiline,
      value,
      [`${this.props.className}`]: !!this.props.className
    });

    return (
      &lt;div {...theme(1, 'container')}&gt;
        {this.props.label ? &lt;label htmlFor={this.props.htmlFor} {...theme(2, 'label')}&gt;{label}&lt;/label&gt; : null}
          &lt;input value={this.state.value} {...theme(3, ...inputClassName)} onChange={this.handleChange} type={type} /&gt;
      &lt;/div&gt;
    );
  }
}
</code></pre>

<p>I found this issue: <a href=""https://github.com/airbnb/enzyme/issues/76"" rel=""noreferrer"">https://github.com/airbnb/enzyme/issues/76</a> and tried the suggestions towards the bottom, I keep getting either undefined or a blank string. I tried levibuzolic's suggestion of using enzyme's simulate change, which can be seen below. However this just returns <code>AssertionError: expected '' to equal 'abcdefghij'</code></p>

<pre><code>it('Make sure inputted text is shorter than max length', function() {
    const result = mount(&lt;Input maxLength={10}&gt;&lt;/Input&gt;);
    result.find('input').simulate('change', {target: {value: 'abcdefghijk'}});
    expect(result.state().value).to.equal(""abcdefghij"");
});
</code></pre>

<p>Then I tried takkyuuplayer's suggestion which is also below. This also fails with <code>AssertionError: expected '' to equal 'abcdefghij'</code></p>

<pre><code>  it('Make sure inputted text is shorter than max length', function() {
    const result = mount(&lt;Input maxLength={10}&gt;&lt;/Input&gt;);
    result.find('input').node.value = 'abcdefghijk';
    expect(result.state().value).to.equal(""abcdefghij"");
  });
</code></pre>

<p>I found this article: <a href=""https://medium.com/javascript-inside/testing-in-react-getting-off-the-ground-5f569f3088a#.f4gcjbaak"" rel=""noreferrer"">https://medium.com/javascript-inside/testing-in-react-getting-off-the-ground-5f569f3088a#.f4gcjbaak</a> and tried their way which also failed.</p>

<pre><code>  it('Make sure inputted text is shorter than max length', function() {
    const result = mount(&lt;Input maxLength={10}&gt;&lt;/Input&gt;);
    let input = result.find('input');
    input.get(0).value = 'abcdefghijk';
    input.simulate('change');
    expect(result.state().value).to.equal(""abcdefghij"");
  });
</code></pre>

<p>Finally I tried using the react test utils as suggested by <a href=""https://stackoverflow.com/questions/24730019/simulating-text-entry-with-reactjs-testutils"">Simulating text entry with reactJs TestUtils</a>, below is the code I tried, however this failed with the error message: <code>TypeError: Cannot read property '__reactInternalInstance$z78dboxwwtrznrmuut6wjc3di' of undefined</code></p>

<pre><code>  it('Make sure inputted text is shorter than max length', function() {
    const result = mount(&lt;Input maxLength={10}&gt;&lt;/Input&gt;);
    let input = result.find('input');
    TestUtils.Simulate.change(input, { target: { value: 'abcdefghijk' } });
    expect(result.state().value).to.equal(""abcdefghij"");
  });
</code></pre>

<p>So how does one simulate user input so they can test the <code>onChange</code> function?</p>
",https://stackoverflow.com/questions/41451729/react-how-to-simulate-user-input-for-unit-testing,"['javascript', 'unit-testing', 'reactjs', 'jestjs', 'enzyme']",34940,TRUE,14,1
Required fields for Unit Testing in c#,"<p>I have an application form in my project and I want to write unit tests.
My code behind has required fields for server side validation to ensure the field is not blank. I need help to know if I've written this right because this is only my second day of writing unit test. please be nice i am only 13.</p>

<pre><code>[Required(ErrorMessage = ""Please provide a title"")]        
public string Title
{
    get; set;
}
</code></pre>

<p>Then in my unit test I did</p>

<pre><code>public void TitleIsNotBlank()
{
    Assert.IsNotNullOrEmpty(_vm.Title);
}
</code></pre>

<p>Would this check that field is not blank?</p>
",https://stackoverflow.com/questions/45122965/required-fields-for-unit-testing-in-c,"['c#', 'unit-testing']",1674,TRUE,0,1
Unit Testing a Class Wrapping a Container,"<p>My class wraps a C# List to extend it with input validation. I test the simple case of calling the AddRows() method with valid data and check items have been added to the internal list.</p>

<p>It seems to me that my test should only care if AddRange() was called on the List, however I actually have to manually check these elements have been added to the underlying list. I feel this is out of scope of the test as it is testing functionality provided by the List and not the ManagedList.</p>

<p>I could resolve this by injecting the List as a dependency to the ManagedList class and substituting in a mocked list in my test that validates if AddRange() was called with the correct data. However having to pass a List as a dependency into my ManagedList class seems a bit over the top.</p>

<p>I feel like I have 2 options:</p>

<ul>
<li>Test functionality already provided by the internal List</li>
<li>Inject the list as a dependency so it can be mocked</li>
</ul>

<p>Am I missing an obvious third option here? If not, which one of the above is the preferable option?</p>

<p><strong>In summary</strong></p>

<p><strong>Managed List Class</strong></p>

<pre><code>class ManagedList
{
    private readonly List&lt;Dictionary&lt;string, object&gt;&gt; _data = new List&lt;Dictionary&lt;string, object&gt;&gt;();

    public ReadOnlyCollection&lt;Dictionary&lt;string, object&gt;&gt; GetData()
    {
        return new ReadOnlyCollection&lt;Dictionary&lt;string, object&gt;&gt;(_data);
    }

    public void AddRows(List&lt;Dictionary&lt;string, object&gt;&gt; rows)
    {
        if (rows.Any(row =&gt; !row.ContainsKey(""id"")))
            throw new Exception(""All rows must have an id"");

        _data.AddRange(rows);
    }
}
</code></pre>

<p><strong>Test</strong></p>

<pre><code>[Test]
public void AddRowsSucceedsWithId()
{
    var managedList = new ManagedList();
    var row = new Dictionary&lt;string, object&gt; {{""id"", ""Item1""}};
    var rows = new List&lt;Dictionary&lt;string, object&gt;&gt; {row, row, row};

    CollectionAssert.IsNotSupersetOf(managedList.GetData(), rows);

    managedList.AddRows(rows);

    CollectionAssert.IsSupersetOf(managedList.GetData(), rows);
}
</code></pre>
",https://stackoverflow.com/questions/42723783/unit-testing-a-class-wrapping-a-container,"['c#', 'unit-testing', 'dependency-injection', 'nunit']",86,FALSE,0,1
Unit testing DI with CoreData won&#39;t work,"<p>I'm trying to write a test to make sure that my view model's model property when set calls my fetchPlan method from the model and then sets my 'plan' property in my view model. It seems to be setting the property but the values are missing...</p>

<p>Here's my view model</p>

<pre><code>final class PlanProgressViewModel: PlanProgressViewModelView {

// MARK: - Properties
fileprivate var plan: PlanData?

// MARK: - PlanProgressViewModelView
weak var viewDelegate: PlanProgressViewModelViewDelegate?

var model: PlanModel? {
    didSet {
        model?.fetchCurrentPlan(completionHandler: { (plan) in
            guard let plan = plan else {return}
            self.plan = plan
        })
    }
}
// Testing this fails...
var planName: String! {
    guard let plan = plan else {return ""No plan""}
    return plan.name
}

var planProgressionString: String! {
    return ""\(Int(round(self.progress * 100)))%""
}

var progress: Double! {
    guard let plan = plan, let workouts = plan.workouts, let completedWorkouts = plan.completedWorkouts else {return 0}
    return Double(Int(completedWorkouts) / workouts.count)
}
}
</code></pre>

<p>Here's my test suite, i'm using a mock to return hardcoded data from the model.</p>

<pre><code>var sut: PlanProgressViewModel!
var model: MockPlanModel!
var moc: NSManagedObjectContext!

override func setUp() {
    super.setUp()
    moc = setupInMemoryMOC()

    let mockModel = MockPlanModel(moc: moc)
    model = mockModel

    let viewModel = PlanProgressViewModel()
    viewModel.model = model
    sut = viewModel
}

override func tearDown() {
    moc = nil
    model = nil
    sut = nil
    super.tearDown()
}
// This passes
func testModelFetchesCurrentPlanOnce() {
    XCTAssertEqual(model.fetchPlanWasCalled, 1)
}

// This is failing
func testPlanName() {
    XCTAssertEqual(sut.planName, ""Test plan"")
}
</code></pre>

<p>Here's my method for setting up a in memory persistent store...</p>

<pre><code>public func setupInMemoryMOC() -&gt; NSManagedObjectContext {
let mom = NSManagedObjectModel.mergedModel(from: [Bundle.main])
let psc = NSPersistentStoreCoordinator(managedObjectModel: mom!)

do {
    try psc.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil)
} catch {
    fatalError()
}

let moc = NSManagedObjectContext.init(concurrencyType: .mainQueueConcurrencyType)
moc.persistentStoreCoordinator = psc

return moc }
</code></pre>

<p>Here's my mock for the model which returns hardcoded data...</p>

<pre><code>public class MockPlanModel: MWPlanModel {
var fetchPlanWasCalled = 0

override public func fetchCurrentPlan(completionHandler: @escaping (_ plan: PlanData?) -&gt; ()) {
    fetchPlanWasCalled += 1

    let moc = setupInMemoryMOC()
    let plan = createTestPlan(moc: moc)

    completionHandler(plan)
}}
</code></pre>

<p>Here's my helper method for creating the model object, (PlanData is a protocol that my 'Plan' NSManaged object inherits).</p>

<pre><code>public func createTestPlan(moc: NSManagedObjectContext) -&gt; PlanData {
let plan: Plan = Plan(context: moc)
plan.name = ""Test plan""
plan.completedWorkouts = 5
plan.currentPlan = true

for _ in 0..&lt;5 {
    plan.mutableOrderedSetValue(forKeyPath: #keyPath(Plan.workouts)).add(createTestCompletedWorkout(moc: moc))
}

return plan }
</code></pre>

<p>The plan name should be ""Test plan"" as that is what i set the hardcoded value to be but it fails and returns an empty string instead...
<a href=""https://i.stack.imgur.com/c6JzC.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/c6JzC.png"" alt=""enter image description here""></a></p>

<p>Really stuck on this, i'm fairly new to testing so i appreciate any help with this. Thanks</p>
",https://stackoverflow.com/questions/46354319/unit-testing-di-with-coredata-wont-work,"['ios', 'swift', 'unit-testing', 'core-data', 'dependency-injection']",111,FALSE,0,1
Recommendation for unit-testing of annotations spock,"<p>What is the recommendation for test of annotation within my own plugin module for grails. Here is my thoughts?</p>

<ol>
<li>Have a <code>subfolder</code> of <code>Test classes</code> within the <code>unittest</code> folder where my new annotations are present.</li>
<li>Deprecate the <code>TestClasses</code></li>
</ol>

<p>Is there a better way?</p>
",https://stackoverflow.com/questions/46747546/recommendation-for-unit-testing-of-annotations-spock,"['grails', 'spock']",67,FALSE,0,0
flask_sqlalchemy create_all() fails silently in unit testing,"<p>I'm writing unit tests for a REST API written in Flask with the flask_sqlalchemy extension. Because I have a number of model classes, I wrote a <code>TestCase</code> subclass to do the standard setUp/cleanUp of the test database. All my test classes inherit from this. Each test succeeds when run alone, but when I run more than one test in a single class, the second setUp() fails on the <code>self.db.session.commit()</code> (I'm trying to add an entry to the User table) because <code>self.db.create_all()</code> has (silently) failed to create any tables.
Here is my base test class, in the <code>__init__.py</code> of the test package:</p>

<pre><code>import unittest

from .test_client import TestClient
from .. import create_app
from pdb import set_trace as DBG

class ApiTest(unittest.TestCase):
    default_username = 'fred'
    default_password = 'bloggs'
    db = None

    def setUp(self):
        try:
            self.app = create_app('testing')
            self.addCleanup(self.cleanUp)
            self.ctx = self.app.app_context()
            self.ctx.push()
            from .. import db
            self.db = db
            self.db.session.commit()
            self.db.drop_all(app=self.app)
            from ..models import User, Player, Team, Match, Game
            # self.app.logger.debug('drop_all())')
            self.db.create_all(app=self.app)
            # self.app.logger.debug('create_all())')
            user = User(user_name=self.default_username)
            user.password = self.default_password
            self.db.session.add(u)
            self.db.session.commit()
            self.client = TestClient(self.app, user.generate_auth_token(), '')
        except Exception, ex:
            self.app.logger.error(""Error during setUp: %s"" % ex)
            raise

    def cleanUp(self):
        try:
            self.db.session.commit()
            self.db.session.remove()
            self.db.drop_all(app=self.app)
            # self.app.logger.debug('drop_all())')
            self.ctx.pop()
        except Exception, ex:
            self.app.logger.error(""Error during cleanUp: %s"" % ex)
            raise
</code></pre>

<p>Can anyone tell me what's wrong here please?</p>

<p>EDIT: Added the code for <code>create_app()</code> as requested.</p>

<pre><code># chessleague/__init__.py
import os

from flask import Flask, g
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager


from . import config


app = None
db = None  # The database, initialised in create_app()


def create_app(config_name):
    app = Flask(__name__)
    app.config.update(config.get_config(config_name))
    # if app.config['USE_TOKEN_AUTH']:
    #     from api.token import token as token_blueprint
    #     app.register_blueprint(token_blueprint, url_prefix='/auth')
    import logging
    from logging.handlers import SysLogHandler
    syslog_handler = SysLogHandler()
    syslog_handler.setLevel(logging.WARNING)
    app.logger.addHandler(syslog_handler)

    login_manager = LoginManager()
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app)
    global db
    db = SQLAlchemy(app)
    db.init_app(app)
    from .models import User,Player,Game,Match,Team,Post
    db.create_all()
    from .api import api as api_blueprint
    app.register_blueprint(api_blueprint, url_prefix='/chessleague')
    return app
</code></pre>

<p>`</p>
",https://stackoverflow.com/questions/44501631/flask-sqlalchemy-create-all-fails-silently-in-unit-testing,"['python', 'unit-testing', 'flask', 'flask-sqlalchemy']",1377,TRUE,0,2
Unit Testing in UWP application throws COMException,"<p>Here is the setup I used to reproduce my issue:</p>

<ol>
<li><p>Create a UWP Library with the one call as follows:</p>

<pre><code>using namespace Windows::UI::ViewManagement;
void noop() {
  auto bounds = ApplicationView::GetForCurrentView()-&gt;VisibleBounds;
}
</code></pre>

<p>This function uses the ApplicationView to get the screen bounds of the current app instance.</p></li>
<li><p>Create another UWP Test App which references the library. Within it's test method, I call the noop() from MyLib.</p></li>
</ol>

<p>On running the tests, it fails and throws a Platform::COMException^. Is there something I am missing?</p>

<p>Thanks for your time.</p>
",https://stackoverflow.com/questions/44020239/unit-testing-in-uwp-application-throws-comexception,"['uwp', 'windows-10-universal', 'windows-10-mobile']",86,FALSE,0,1
Lifetime of Request Sessions in Unit Testing,"<p>I'm working on a unit tests for an API client class. 
There is a class variable <code>self.session</code> that is supposed to hold the session. 
In my setup method for my test I create a new instance of the client class and then call its authenticate method. However when the tests themselves go to send requests using this object they all return 401 forbidden errors. </p>

<p>If I move the authenticate call (but not the creation of the class) into the tests and out of setup everything works great, but I understand that that defeats the purpose of setup(). </p>
",https://stackoverflow.com/questions/44464654/lifetime-of-request-sessions-in-unit-testing,"['python-3.x', 'python-requests', 'python-unittest']",34,FALSE,0,1
AssertionError Unexpected method call when unit testing,"<p>I'm currently unit testing a method of my controller. Simply trying to test if the method returns the right string.</p>

<pre><code>@RequestMapping(value = ""/createTestscenario"", method = RequestMethod.POST)
public String createTestscenario(@PathVariable(""tdid"") Integer testdesignID, @ModelAttribute(""testscenario"") Testscenario testscenario){

    Testdesign testdesign = this.testdesignService.getTestdesignById(testdesignID);
    testscenario.setTestdesign(testdesign);
    testdesign.getTestscenarioSet().add(testscenario);
    this.testdesignService.saveTestdesign(testdesign);

    return ""redirect:/projects"";
}
</code></pre>

<p>This is my unit test</p>

<pre><code>@Test
public void createTestscenario1() throws Exception {

    Testdesign testdesign = new Testdesign();
    testdesign.setId(1);

    Testscenario testscenario = new Testscenario();
    testscenario.setId(1);
    Testscenario testscenario2 = new Testscenario();
    testscenario.setId(2);
    Set&lt;Testscenario&gt; set = new HashSet&lt;&gt;(Arrays.asList(testscenario));
    testdesign.setTestscenarioSet(set);
    testscenario.setTestdesign(testdesign);

    EasyMock.expect(testdesignService.getTestdesignById(1)).andReturn(testdesign);
    EasyMock.replay(testdesignService);

    String test = controller.createTestscenario(1, testscenario2);

    EasyMock.verify(testdesignService);

    Assert.assertEquals(""redirect:/projects"", test);
}
</code></pre>

<p>When I run the test i get the error:</p>

<pre><code>java.lang.AssertionError: 
  Unexpected method call TestdesignServiceImpl.saveTestdesign(com.example.testclusters.model.Testdesign@28feb3fa):
</code></pre>

<p>I honestly don't know where the error lies. I can't Mock the saveTestdesign method like:</p>

<pre><code>EasyMock.expect(testdesignService.save(testdesign)).andReturn(..);
</code></pre>

<p>Because save is a void method.</p>

<p>Does someone know how to fix this unit test?</p>
",https://stackoverflow.com/questions/47791732/assertionerror-unexpected-method-call-when-unit-testing,"['java', 'unit-testing', 'easymock']",3174,TRUE,0,1
Unit testing on laravel file downloading location,"<p>I am new to Laravel. I am writing unit testing on laravel for downloading a csv file. When I run the test case, I get <code>assertResponseStatus</code> as 200 and I need to open the created csv file and I am unable to find the location of downloaded file. How can I find the downloaded file. </p>

<p><strong>This is the controller fuction</strong></p>

<pre><code>    public function generateCsv(){

    $list = $this-&gt;csvRepo-&gt;getDetails();

    $heading = array(
        'heading 1',
        'heading 2',
        'heading 3'
    );

    $this-&gt;csvRepo-&gt;generateCsv($heading,'csv',$list);
}
</code></pre>

<p>I need to know the location of downloaded file when run the test case</p>
",https://stackoverflow.com/questions/44150766/unit-testing-on-laravel-file-downloading-location,"['laravel', 'unit-testing', 'csv', 'download']",1423,TRUE,0,1
Unit Testing HttpContext overwrites behavior of ISitecorecontext,"<p>In my test class i mocked the sitecore context like below to get items from my fake database:</p>

<p><code>ISitecoreContext _sitecoreContext = new SitecoreContext();</code></p>

<p>After this I tried to switch the logged in user as below :</p>

<p><code>using (new Sitecore.Security.Accounts.UserSwitcher(@""extranet\John"", true))
  {
    // Do something
  }</code></p>

<p>Eveything is working fine until I needed to set the value of <code>HttpContext.Current</code> which I added before the instantiation of sitecore context object</p>

<p><code>HttpContext.Current = new HttpContext(
    new HttpRequest("""", ""http://tempuri.org"", """"),
    new HttpResponse(new StringWriter())
    );</code></p>

<p>Now when I tried to debug my code, the line that switched another user is throwing an error </p>

<p><code>Value cannot be null, parameter name : folder</code></p>

<p>Why is it happening? Does the <code>httpcontext</code> overwrites the context of <code>isitecorecontext</code>?</p>
",https://stackoverflow.com/questions/43525189/unit-testing-httpcontext-overwrites-behavior-of-isitecorecontext,"['sitecore', 'nunit']",130,FALSE,0,0
Java build.xml unit testing with Travis-CI,"<p>I am trying to set up unit testing with Travis-CI for my java project, and I am having some difficulties. The issue is that I would like it to run all of the unit tests I have in the src/test/ file without having to specify the test name directly. This is because I will keep adding tests, and I would not like to constantly export the build.xml file. The xml I currently have is:</p>

<pre><code>    &lt;?xml version=""1.0"" encoding=""UTF-8"" standalone=""no""?&gt;
    &lt;!-- WARNING: Eclipse auto-generated file.
          Any modifications will be overwritten.
          To include a user specific buildfile here, simply create one in the same
          directory with the processing instruction &lt;?eclipse.ant.import?&gt;
          as the first entry and export the buildfile again. --&gt;
&lt;project basedir=""."" default=""build"" name=""COSC 4F90""&gt;
&lt;property environment=""env""/&gt;
&lt;property name=""junit.output.dir"" value=""junit""/&gt;
&lt;property name=""debuglevel"" value=""source,lines,vars""/&gt;
&lt;property name=""target"" value=""1.8""/&gt;
&lt;property name=""source"" value=""1.8""/&gt;

&lt;path id=""COSC 4F90.classpath""&gt;
    &lt;pathelement location=""bin""/&gt;
    &lt;pathelement location=""lib/commons-math3-3.6.1.jar""/&gt;
    &lt;pathelement location=""lib/junit.jar""/&gt;
    &lt;pathelement location=""lib/org.hamcrest.core_1.3.0.v201303031735.jar""/&gt;
&lt;/path&gt;

&lt;target name=""init""&gt;
    &lt;mkdir dir=""bin""/&gt;
    &lt;copy includeemptydirs=""false"" todir=""bin""&gt;
        &lt;fileset dir=""src""&gt;
            &lt;exclude name=""**/*.launch""/&gt;
            &lt;exclude name=""**/*.java""/&gt;
        &lt;/fileset&gt;
    &lt;/copy&gt;
&lt;/target&gt;

&lt;target name=""clean""&gt;
    &lt;delete dir=""bin""/&gt;
&lt;/target&gt;

&lt;target depends=""clean"" name=""cleanall""/&gt;
&lt;target depends=""build-project"" name=""build""/&gt;

&lt;target depends=""init"" name=""build-project""&gt;
    &lt;echo message=""${ant.project.name}: ${ant.file}""/&gt;
    &lt;javac debug=""true"" debuglevel=""${debuglevel}"" destdir=""bin"" includeantruntime=""false"" source=""${source}"" target=""${target}""&gt;
        &lt;src path=""src""/&gt;
        &lt;classpath refid=""COSC 4F90.classpath""/&gt;
    &lt;/javac&gt;
&lt;/target&gt;

&lt;target name=""test"" depends=""build""&gt;&lt;!--depends=""build""--&gt;
  &lt;junit printsummary=""withOutAndErr"" haltonfailure=""yes""&gt;
      &lt;classpath&gt;
        &lt;path refid=""COSC 4F90.classpath"" /&gt;
        &lt;!--pathelement location=""${test.build.dir}""/--&gt;
      &lt;/classpath&gt;
      &lt;formatter type=""brief"" usefile=""false"" /&gt;
      &lt;batchtest&gt;
          &lt;fileset dir=""COSC 4F90.classpath"" includes=""**/*Test*.java"" /&gt;
      &lt;/batchtest&gt;
  &lt;/junit&gt;
&lt;/target&gt;
&lt;/project&gt;
</code></pre>

<p>The error that I receive with Travis-CI is </p>

<pre><code>    Cannot find symbol
    [javac] import simulation.creature.NeuralNet;
    [javac]                           ^            
</code></pre>

<p>If anyone could help me out it would be much appreciated.</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/41646283/java-build-xml-unit-testing-with-travis-ci,"['java', 'xml', 'junit', 'travis-ci', 'cannot-find-symbol']",426,FALSE,0,0
Unit testing logic in controller OnActionExecuting event,"<p>There is a custom logic to set the page title in my controller's OnActionExecuting event which sets default value for title if it is not set using an attribute on action methods:</p>

<pre><code>[PageTitle(""Overriden page title"")]
public ActionResult About()
{
    return View();
}

public ActionResult Error()
{
    return View();
}

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
    //Page title
    var title = filterContext.ActionDescriptor.GetCustomAttributes(typeof(PageTitleAttribute), false);
    if (title.Length == 1)
        ViewBag.Title = ((PageTitleAttribute)(title[0])).Parameter;
    else
        ViewBag.Title = ""Default Website Title"";
}
</code></pre>

<p>How can I unit test this functionality?</p>
",https://stackoverflow.com/questions/41498492/unit-testing-logic-in-controller-onactionexecuting-event,"['asp.net-mvc', 'unit-testing', 'moq']",1122,TRUE,0,1
How to simulate proxy during unit testing?,"<p>I have a Node.js library that makes <code>https.request</code> (<a href=""https://nodejs.org/api/https.html"" rel=""nofollow noreferrer"">https://nodejs.org/api/https.html</a>) calls to external sources.</p>

<p>In some cases, the user of the library may be behind a proxy. Due to configuration (or misconfiguration?) of the proxy, users behind the proxy may experience issues with SSL certificates. In this case, in order to make https requests in Node, you need to set the <code>https.request</code> option: <code>rejectUnauthorized</code> to be <code>false</code>. (on a related note, these proxies typically require <code>npm --strict-ssl=false</code> as well)</p>

<p>How can I setup a test that simulates being behind a proxy that rejects signed certificates so that I can ensure that my library will work properly for those behind proxies such as these?</p>

<p>I'm using <code>mocha</code> and/or <code>chai</code> as the testing library and <code>nock</code> to simulate external sources that are being called.</p>
",https://stackoverflow.com/questions/42076276/how-to-simulate-proxy-during-unit-testing,"['javascript', 'node.js', 'ssl', 'testing', 'proxy']",1235,FALSE,0,1
Mongoose model chain unit testing (Regular Callback),"<p>I am trying to unit test:</p>

<pre><code>myModel.find({""id"": someId}, callback)
    .sort({timestamp: -1})
    .limit(100)
</code></pre>

<p>I used sinon-mongoose and came up with the following</p>

<pre><code>myModel
    .expects('find').withArgs({""id"": 'def'})
    .chain('exec')
    .yields(null, 'abc')
    .chain('sort').withArgs({timestamp: -1})
    .chain('limit').withArgs(100);
</code></pre>

<p>However, I run into the issue that the done function is not being called and the test times out. Anyone have experience stubbing the regular callback over the exec callback using sinon-mongoose?</p>

<p>If I change my model code to:</p>

<pre><code>myModel.find({""id"": someId}
    .exec(callback)
    .sort({timestamp: -1})
    .limit(100)
</code></pre>

<p>The unit test works. Thus, I think it's a problem in stubbing the exec callback vs regular callback.</p>
",https://stackoverflow.com/questions/44203764/mongoose-model-chain-unit-testing-regular-callback,"['javascript', 'unit-testing', 'mongoose', 'sinon']",64,FALSE,0,1
Unit testing a partial text searching service,"<p>I'm trying to unit test a search function I have that will match a partially entered string to a result if one exists. 
My failing test: </p>

<pre><code>    [Theory(DisplayName = ""Retrieve a Customer by partial name if the customer exists."")]
    [InlineData(""fifth"")]
    public async Task ProviderClass_GetCustomersByPartialName(string name)
    {
        var mockISecurityTokenProvider = new Mock&lt;ISecurityTokenProvider&gt;();
        mockISecurityTokenProvider.Setup(i =&gt; i.GetSecurityToken()).Returns(() =&gt; new SecurityToken
        {
            CurrentAccessLevel = AccessLevel.Full
        });

        var customerRepository = new CustomerRepository(_context, mockISecurityTokenProvider.Object);
        var irrelevantRepo = new irrelevantRepo(_context, mockISecurityTokenProvider.Object);

        var service = new CustomerProvider(customerRepository, irrelevantRepo,
            new CustomerFactory(), 
            new Mock&lt;IGenericModelFactory&lt;mockedModel, mockedTable&gt;&gt;().Object,
            new Mock&lt;IGenericModelFactory&lt;mockedModel, mockedTable&gt;&gt;().Object,
            new Mock&lt;IGenericModelFactory&lt;mockedModel, mockedTable&gt;&gt;().Object, 
            new Mock&lt;IGenericModelFactory&lt;mockedModel, mockedTable&gt;&gt;().Object,
            new Mock&lt;IGenericModelFactory&lt;mockedModel, mockedTable&gt;&gt;().Object);

        var item = await service.GetCustomersByPartialNameAsync(name);

        Assert.True(item?.Any(i =&gt; i.Name.ToLower().Contains(name.ToLower())));
</code></pre>

<p>And the service code I am testing: </p>

<pre><code>public async Task&lt;IEnumerable&lt;Customer&gt;&gt; GetCustomersByPartialNameAsync(string name,
        CancellationToken cancellationToken = new CancellationToken())
    {
        var items =
            await _customerReader.GetCustomers()
                //Includes of tables where relevant results might be
                .Where(i =&gt; i.CustomerStatusId == 1 &amp;&amp; i.Name.ToLower().Contains(name.ToLower()))
                .ToListAsync(cancellationToken);

        return items.Select(Create);
    }
</code></pre>

<p>What am I doing wrong?</p>
",https://stackoverflow.com/questions/45701407/unit-testing-a-partial-text-searching-service,"['c#', 'unit-testing', 'xunit']",72,FALSE,0,1
What is exactly mocking in unit testing?,"<p>I am trying to test an http server functionality and this is the first time I get exposed to the notions of mocks, stubs and fakes. I'm reading this book that it says mocking is describing the state of a complex object at a certain moment, like a snapshot, and testing the object as it is actually the real one. right? I understand this. what I don't understand is what is the point of writing unit tests and assertions of certain cases that we fully describe in the mock object. If we set the expectations of arguments and return values on the mocking object, and we test for those exact values, the test will always pass. Please correct me. I know I am missing something here.</p>
",https://stackoverflow.com/questions/45466110/what-is-exactly-mocking-in-unit-testing,"['unit-testing', 'testing', 'mocking']",37,FALSE,0,1
Unit testing for exceptions that were catched,"<pre><code>public void methodToBeTested() {
    try {
       //Some logic that throws an exception
    }
    catch(Exception e) {
      //Logic dealing with an exception
    }
}
</code></pre>

<p>Well, with ExpectedException we can check if the method under test has thrown any exception, but how to check it the exception has occurred when method in not throwing, but catching it? </p>
",https://stackoverflow.com/questions/47351256/unit-testing-for-exceptions-that-were-catched,"['java', 'unit-testing', 'exception', 'mockito', 'powermock']",468,FALSE,-2,1
Unit Testing throwing exception in async method,"<p>I'm trying to assert an exception which happens in an async method.<br>
Unfortunately, the assertion doesn't work.</p>

<p>I've made sure via debugging, that the <code>throw new Exception(...)</code> is called in the <code>SaveCategoriesAsync(...)</code> method.</p>

<p>The method with the <code>Action</code> normally works for unit tests... but it seems that it doesn't work with async.</p>

<p>I'm using <strong>FakeItEasy</strong> as mocking framework and <strong>FluentAssertions</strong> as assertion framework.</p>

<pre><code>[TestMethod]
public void SaveCategoriesAsync_When_Then()
{
    A.CallTo(() =&gt; this.articleRepository.GetArticles(A&lt;IList&lt;long&gt;&gt;._)).Returns(new List&lt;ArticleModel&gt;());

    Action action = async () =&gt; await this.testee.SaveCategoriesAsync(new List&lt;int&gt;());

    action.ShouldThrow&lt;Exception&gt;();
}
</code></pre>

<p>What do I have to change to be able to assert the exception?</p>

<p>Thanks in advance</p>
",https://stackoverflow.com/questions/46975144/unit-testing-throwing-exception-in-async-method,"['c#', '.net', 'unit-testing', 'asynchronous', 'async-await']",3278,TRUE,0,2
Redux Action Unit Testing (Mocha &amp; Chai),"<p>I need help with writing unit tests for below Redux actions.
In Google, I saw some examples but the way they wrote their actions seem to be quite different so I am facing some difficulties writing unit tests for my Redux actions.</p>

<p>Below is the Redux actions that I have:</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>import * as types from './readerTypes';

export const documentSuccessAction = (data) =&gt; {
  return (dispatch, getState) =&gt; {
    dispatch({
      type: 'GET_METADATA_SUCCESS',
      metadata: data.document
    });

    dispatch({
      type: 'GET_DOCUMENT_SUCCESS',
      document : data.documentContent
    });
  };
};

export const getDocument = (docID) =&gt; {
  return (dispatch, getState) =&gt; dispatch({
    type: 'API_REQUEST',
    options: {
      method: 'GET',
      service: 'reader',
      endpoint: `document/${docID}`,
      actionTypes: {
        loading: 'GET_DOCUMENT_LOADING',
        success: documentSuccessAction,
        error: 'GET_DOCUMENT_ERROR'
      }
    }
  });
};</code></pre>
</div>
</div>
</p>

<p>Could anyone please help me with this?</p>

<p>Thank you</p>
",https://stackoverflow.com/questions/46673763/redux-action-unit-testing-mocha-chai,"['reactjs', 'unit-testing', 'redux', 'react-redux', 'redux-thunk']",354,FALSE,0,1
Swift unit testing with Realm and RAC,"<p>I am trying to write some unit tests for my app. I am using Realm and RAC frameworks, but neither of them I can use in my unit tests.</p>

<pre><code>import XCTest

@testable import FlightRecords

class RecordsViewModelTests: XCTestCase {

    var viewModelUnderTest: RecordsViewModel!

    override func setUp() {
        super.setUp()
        viewModelUnderTest = RecordsViewModel()
        Realm.Configuration.defaultConfiguration.inMemoryIdentifier = self.name
    }
}
</code></pre>

<p>In the code above, I get an error, but my app is working just normally with Realm (and RAC). The error is:</p>

<blockquote>
  <p>Use of unresolved identifier 'Realm'</p>
</blockquote>

<p>I have tried different combinations for ""Target Membership"" and none of them worked. At this point, I have all frameworks' Target Membership for both app and tests.</p>

<p>Any advice?</p>
",https://stackoverflow.com/questions/46727268/swift-unit-testing-with-realm-and-rac,"['swift', 'unit-testing', 'realm', 'reactive-cocoa']",952,TRUE,0,1
Deadlock using FileOpenPicler when unit testing UWP,"<p>I want to Pick a file for unit testing parts of the application. how ever this is causing deadlock.</p>

<p>If I put breakpoint at <code>CoreApplication</code> line (before Assert.IsNotNull) and start debugging by pressing F10 it wont dead lock, but I get dead lock without  breakpoint.</p>

<p>If I mark method as <code>async</code> and await result, I get <code>InvalidOperationException</code> saying</p>

<blockquote>
  <p>A method was called at an unexpected time.</p>
</blockquote>

<p>How should I fix this issue?</p>

<pre><code>private StorageFile file;    

//[TestMethod, TestCategory(""Basics"")]
public void T01_PickFile()
{
    // initialize picker
    var picker = new FileOpenPicker
    {
        SuggestedStartLocation = PickerLocationId.Desktop,
        ViewMode = PickerViewMode.List
    };
    picker.FileTypeFilter.Add("".txt"");

    // grant access and pick file
    // deadlock if there is no breakpoint
    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =&gt;
    {
        file = picker.PickSingleFileAsync().GetAwaiter().GetResult();
    }).GetAwaiter().GetResult();

    Assert.IsNotNull(file);
}
</code></pre>

<p>Update:</p>

<p>if I wait for result asynchronously the application does not wait and continues the execution before I pick my file and <code>Assert.IsNotNull(file)</code> fails the test. </p>

<p>note: I see FileOpenPicker comes for a second then test fails.</p>

<pre><code>//[TestMethod, TestCategory(""Basics"")]
public async Task T01_PickFile()
{
    // initialize picker
    var picker = new FileOpenPicker
    {
        SuggestedStartLocation = PickerLocationId.Desktop,
        ViewMode = PickerViewMode.List
    };
    picker.FileTypeFilter.Add("".mid"");

    // grant access and pick file
    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =&gt;
    {
        file = await picker.PickSingleFileAsync();
    });

    Assert.IsNotNull(file);
}
</code></pre>

<p>This is how I call this method</p>

<pre><code>[TestMethod, TestCategory(""Basics"")]
public async Task T02_OpenTest()
{
    await T01_PickFile();
}
</code></pre>
",https://stackoverflow.com/questions/43580458/deadlock-using-fileopenpicler-when-unit-testing-uwp,"['c#', 'unit-testing', 'uwp', 'fileopenpicker']",81,FALSE,0,0
React - unit testing with a setup function,"<p>I have the following case:</p>

<pre><code>describe('API - Input component', () =&gt; {
   describe('Input element', () =&gt; {
    it('should have a modifier to its class if data entered is erroneous', () =&gt; {
      const wrapper = shallow(&lt;Input error=""Invalid data"" /&gt;);

      expect(wrapper.find('input').props().className).toBe('form-field__input form-field__input--error');
    });
  });
});
</code></pre>

<p>This works perfectly fine. As long as I pass some data to my <strong>error</strong> props a modifier class should be expected and the test passes.</p>

<p>Now, I want to achieve the same thing but using a setup function. Like this:</p>

<pre><code>function setup () {
  const props = {
    error: {}
  };

  return shallow(&lt;Input {...props} /&gt;);
}

describe('API - Input component', () =&gt; {
   describe('Input element', () =&gt; {
    it('should have a modifier to its class if data entered is erroneous', () =&gt; {
      const wrapper = setup(how do I pass my props here?!);

      expect(wrapper.find('input').props().className).toBe('form-field__input form-field__input--error');
    });
  });
});
</code></pre>

<p>Thanks!</p>
",https://stackoverflow.com/questions/42141863/react-unit-testing-with-a-setup-function,"['unit-testing', 'reactjs', 'mocha.js', 'enzyme']",49,TRUE,0,1
How to catch event while unit testing?,"<p>Hi I have a problem testing an event using <code>NUnit</code>. I'm not even sure if this should be unit or functional test. Let me show you the sample class first (I'm trying to test <code>OnValueInjected</code> event):</p>

<pre><code>public class Foo
{
    private IBar CurrentBar { get; set; }
    public event EventHandler&lt;MoveEventArgs&gt; OnValueInjected;

    public Foo()
    {
        StartFoo();
    }    

    private async void StartFoo()
    {
        await Task.Factory.StartNew(() =&gt;
        {
            while (State != FooState.Finished)
            {
                IResult result = CurrentBar.WaitForValue(); // This is blocking function, wait for a value

                OnValueInjected?.Invoke(this, new ResultEventArgs(result));

                // .. rest of the loop
            }
        });
    }

    public void InjectValue(int a, int b)
    {
        CurrentBar.Inject(a,b);
    }
}
</code></pre>

<p>So, basically what I'm trying to do is to subscribe to the event, call <code>InjectValue</code> and check if the event was called. Like this:</p>

<pre><code>    [Test]
    public void FooOnValueInjectedTest()
    {
        bool OnValueInjectedWasRasied = false;

        IFoo foo = new Foo();
        foo.OnValueInjected += (s, e) =&gt; OnValueInjectedWasRasied = true;

        foo.InjectValue(0,0);

        Assert.AreEqual(true, OnValueInjectedWasRasied);
    }
</code></pre>

<p>Pretty straightforward, BUT it looks like <code>InjectValue</code> is too slow. The test is failing..I think it's too slow, because when I add <code>Thread.Sleep</code> between <code>InjectValue</code> and <code>Assert</code> to works.</p>

<pre><code>        foo.InjectValue(0,0);
        Thread.Sleep(1000);
        Assert.AreEqual(true, OnValueInjectedWasRasied); 
</code></pre>

<p>Is there a better way to test such an event? Thanks</p>

<p>I fixed my class, so it's like that now:</p>

<pre><code>public class Foo
{
    private AutoResetEvent AutoReset { get; }

    private IBar CurrentBar { get; set; }
    public event EventHandler&lt;MoveEventArgs&gt; OnValueInjected;

    public Foo()
    {
        AutoReset = new AutoResetEvent(false);
        StartFoo();
    }

    private async void StartFoo()
    {
        await Task.Factory.StartNew(() =&gt;
        {
            while (State != FooState.Finished)
            {
                IResult result = CurrentBar.WaitForValue(); // This is blocking function, wait for a value

                OnValueInjected?.Invoke(this, new ResultEventArgs(result));

                AutoReset.Set();

                // .. rest of the loop
            }
        });
    }

    public void InjectValue(int a, int b)
    {
        if (CurrentBar.Inject(a,b))
        {
            AutoReset.WaitOne();
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/43562262/how-to-catch-event-while-unit-testing,"['c#', '.net', 'unit-testing', 'testing', 'nunit']",834,TRUE,0,1
Java Unit testing Google AppEngine memcache standalone,"<p>I'm attempting to write unit tests for my Java AppEngine application around my caching service.  Any time I make a get or put I get the following exception:</p>

<blockquote>
  <p><em>Can't make API call memcache.Get in a thread that is neither the</em>
  <em>original request thread nor a thread created by ThreadManager</em></p>
</blockquote>

<p>My implementation is simple enough:</p>

<pre><code>MemcacheServiceFactory.getAsyncMemcacheService(NAMESPACE).get(""key"")
MemcacheServiceFactory.getAsyncMemcacheService(NAMESPACE).put(""key"", ""value"")
</code></pre>

<p>I have also tried:</p>

<pre><code>MemcacheServiceFactory.getMemcacheService(NAMESPACE).get(""key"")
MemcacheServiceFactory.getMemcacheService(NAMESPACE).put(""key"", ""value"")
</code></pre>

<p>This works just fine when I'm running it as a ""local deployment"" as part of my web service as a whole, but the standalone test on this section of code will not work.  </p>

<p>Is there any way to test the memcache service stand alone - outside of the gae envirnment?</p>
",https://stackoverflow.com/questions/44803465/java-unit-testing-google-appengine-memcache-standalone,"['java', 'google-app-engine', 'junit', 'memcached']",331,FALSE,0,1
Selenium Webdriver automaton in C# unit testing,"<p>I have to write unit test methods for testing a web application using selenium to automate testing. I am new to selenium and point which I am not understanding is :
1) I have written a unit test method for login page with wait.Until command</p>

<pre><code> [TestMethod]
    public void LoginWithParameters()
    {
        IWebDriver driver = new ChromeDriver();
        try
        {
            driver.Navigate().GoToUrl(ConfigurationManager.AppSettings[""TestURLLogin""]);
            var userName = driver.FindElement(By.Id(""UserName""));
            var passWord = driver.FindElement(By.Id(""Password""));
            var logOn = driver.FindElement(By.XPath(""//input[@value='Log On']""));
            userName.SendKeys(ConfigurationManager.AppSettings[""UserName""]);
            passWord.SendKeys(ConfigurationManager.AppSettings[""Password""]);
            logOn.Click();

            WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
            var by = By.LinkText(""Home"");
            wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(by));

        }
        catch (Exception ex)
        {

            Assert.Fail(""Test failed. The exception was:\n {0}"", ex.Message.ToString());
        }

        var str = driver.PageSource;

        Assert.IsTrue(str.Contains(""Home""));


    }
</code></pre>

<p>2)after login , I have to fill a form and submit. 
 Now condition is 'only if login test is successful , I have to move to form filling unit test method. if login fails then I don't have to go to form filling unit test method. </p>

<p>As far as I understood about Unit testing, unit test methods are not dependent on other unit test methods. So how to achieve selenium automation with webdirver in C# with these conditions? </p>
",https://stackoverflow.com/questions/42423332/selenium-webdriver-automaton-in-c-unit-testing,"['c#', 'unit-testing', 'selenium']",1079,FALSE,0,0
Unit testing a React function in component,"<p>I need a way to unit test the ""edit"" function in the code below. It is different form the other questions because my function returns no value.</p>

<pre><code>class QslTable extends React.PureComponent {
        this.state = {
        data: [{
            key: '0',
            callSign: {
                editable: true,
                value: 'F1ABD',
            },
            QSODate: {
                editable: true,
                value: '10-05-31',
            },
            band: {
                editable: true,
                value: '32',
            },
            mode: {
                editable: true,
                value: 'Phone',
            },
            dxccEntity: {
                editable: true,
                value: 'France',
            },
            delete: {
                editable: false,
                value: 'Delete',
            },
        }],
    };

      edit(index) {
        const { data } = this.state;
        Object.keys(data[index]).forEach((item) =&gt; {
            if (data[index][item] &amp;&amp; typeof data[index][item].editable !== 'undefined') {
                data[index][item].editable = true;
            }
        });
        this.setState({ data });
    }
}
</code></pre>

<p>This doesn't work:</p>

<pre><code>it('should render the component', () =&gt; {
    const renderedComponent = shallow(&lt;QslTable /&gt;);

    expect(renderedComponent.find('edit')).toBeDefined();

});
</code></pre>

<p>The function doesn't return any value. I have no clue how to test the function. I have looked at the documentation for Jest, but couldn't figure it out. Any help would be appreciated!</p>
",https://stackoverflow.com/questions/44554844/unit-testing-a-react-function-in-component,"['unit-testing', 'reactjs', 'components', 'jestjs']",498,FALSE,0,0
Unit Testing Fragment has caused code inflation,"<p>Upon implementing unit testing on my <code>Fragment</code>, I have doubled the length of code in my class. Are there certain best practices I should follow, or am I over-testing? Should this all be an implementation test instead?</p>

<p>Of particular note is the method <code>connectToBehaviorRelay(behaviorRelay, artistResultFunction, getConsumer(), mySchedulerProvider);</code>. I could remove some of these parameters but I would then have to create further <code>@VisibleForTesting</code> methods.</p>

<pre><code>    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
    {
        ArtistReleasesActivity.component.inject(this);
        View view = inflater.inflate(R.layout.fragment_recyclerview, container, false);
        ButterKnife.bind(this, view);
        connectToBehaviorRelay(behaviorRelay, artistResultFunction, getConsumer(), mySchedulerProvider);
        setupRecyclerView(getActivity());
        return view;
    }

    @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
    public void connectToBehaviorRelay(BehaviorRelay&lt;List&lt;ArtistRelease&gt;&gt; behaviorRelay, ArtistResultFunction artistResultFunction, Consumer&lt;List&lt;ArtistRelease&gt;&gt; consumer, SchedulerProvider mySchedulerProvider)
    {
        behaviorRelay
                .map(artistResultFunction.map(getArguments().getString(""map"")))
                .observeOn(mySchedulerProvider.ui())
                .subscribe(consumer);
    }

    private Consumer&lt;List&lt;ArtistRelease&gt;&gt; getConsumer()
    {
        return o -&gt;
        {
            rvReleasesAdapter.setRemixes(o);
            rvReleasesAdapter.notifyDataSetChanged();
        };
    }

    @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
    public void setupRecyclerView(FragmentActivity activity)
    {
        recyclerView.setLayoutManager(new LinearLayoutManager(activity));
        rvReleasesAdapter = new RecyclerViewReleasesAdapter(activity);
        recyclerView.setAdapter(rvReleasesAdapter);
    }

    @VisibleForTesting
    public void setArtistResultFunction(ArtistResultFunction artistResultFunction)
    {
        this.artistResultFunction = artistResultFunction;
    }

    @VisibleForTesting
    public void setRecyclerView(RecyclerView recyclerView)
    {
        this.recyclerView = recyclerView;
    }
</code></pre>

<p>My question is: do I need to have all these lines or should I move some to a <code>Presenter</code>? Having them within a <code>Fragment</code>'s <code>onCreateView()</code> seems to complicate things.</p>
",https://stackoverflow.com/questions/43350576/unit-testing-fragment-has-caused-code-inflation,"['android', 'unit-testing', 'android-fragments']",39,FALSE,0,0
Scala - unit testing a Column type function,"<p>I have a function <code>isJSON()</code> that return a comparison of type Column.</p>

<pre><code>  def isJSON( element: Column ): Column = {
    element.contains(""{"") &amp;&amp; element.contains(""}"")
  }
</code></pre>

<p>This is how I use it usually and it works as expected:</p>

<pre><code>df.withColumn(""is_json"", isJSON( col(""data"") ))
</code></pre>

<p>I'm trying to write a Unit test using <code>FunSpec</code> but I'm not able to assert on <code>Column</code> type of data.</p>

<pre><code>describe(""isJSON()"") {
  it(""should return false if data is not JSON"") {
    val df = Seq( ""Not a JSON"" ).toDF( ""data"" )
    assert( isJSON( df(""data"") ).equals( lit( false ) ))
  }
}
</code></pre>

<p>Unit test errors out with following stacktrace:</p>

<pre><code>ScalaTestFailureLocation: com.mhedu.common.datalake.DatalakeFunSpecTest$$anonfun$1$$anonfun$apply$mcV$sp$1 at (DatalakeFunSpecTest.scala:29)
org.scalatest.exceptions.TestFailedException: datalake.this.`package`.isJSON(df.apply(""data"")).equals(org.apache.spark.sql.functions.lit(false)) was false
    at org.scalatest.Assertions$class.newAssertionFailedException(Assertions.scala:500)
    at org.scalatest.FunSpec.newAssertionFailedException(FunSpec.scala:1626)
    at org.scalatest.Assertions$AssertionsHelper.macroAssert(Assertions.scala:466)
    at com.mhedu.common.datalake.DatalakeFunSpecTest$$anonfun$1$$anonfun$apply$mcV$sp$1.apply$mcV$sp(DatalakeFunSpecTest.scala:29)
    at com.mhedu.common.datalake.DatalakeFunSpecTest$$anonfun$1$$anonfun$apply$mcV$sp$1.apply(DatalakeFunSpecTest.scala:23)
    at com.mhedu.common.datalake.DatalakeFunSpecTest$$anonfun$1$$anonfun$apply$mcV$sp$1.apply(DatalakeFunSpecTest.scala:23)
    at org.scalatest.Transformer$$anonfun$apply$1.apply$mcV$sp(Transformer.scala:22)
    at org.scalatest.OutcomeOf$class.outcomeOf(OutcomeOf.scala:85)
    at org.scalatest.OutcomeOf$.outcomeOf(OutcomeOf.scala:104)
    at org.scalatest.Transformer.apply(Transformer.scala:22)
    at org.scalatest.Transformer.apply(Transformer.scala:20)
    at org.scalatest.FunSpecLike$$anon$1.apply(FunSpecLike.scala:422)
    at org.scalatest.Suite$class.withFixture(Suite.scala:1122)
    at org.scalatest.FunSpec.withFixture(FunSpec.scala:1626)
    at org.scalatest.FunSpecLike$class.invokeWithFixture$1(FunSpecLike.scala:419)
    at org.scalatest.FunSpecLike$$anonfun$runTest$1.apply(FunSpecLike.scala:431)
    at org.scalatest.FunSpecLike$$anonfun$runTest$1.apply(FunSpecLike.scala:431)
    at org.scalatest.SuperEngine.runTestImpl(Engine.scala:306)
    at org.scalatest.FunSpecLike$class.runTest(FunSpecLike.scala:431)
    at com.mhedu.common.datalake.DatalakeFunSpecTest.org$scalatest$BeforeAndAfter$$super$runTest(DatalakeFunSpecTest.scala:13)
    at org.scalatest.BeforeAndAfter$class.runTest(BeforeAndAfter.scala:200)
    at com.mhedu.common.datalake.DatalakeFunSpecTest.runTest(DatalakeFunSpecTest.scala:13)
    at org.scalatest.FunSpecLike$$anonfun$runTests$1.apply(FunSpecLike.scala:464)
    at org.scalatest.FunSpecLike$$anonfun$runTests$1.apply(FunSpecLike.scala:464)
    at org.scalatest.SuperEngine$$anonfun$traverseSubNodes$1$1.apply(Engine.scala:413)
    at org.scalatest.SuperEngine$$anonfun$traverseSubNodes$1$1.apply(Engine.scala:401)
    at scala.collection.immutable.List.foreach(List.scala:381)
    at org.scalatest.SuperEngine.traverseSubNodes$1(Engine.scala:401)
    at org.scalatest.SuperEngine.org$scalatest$SuperEngine$$runTestsInBranch(Engine.scala:390)
    at org.scalatest.SuperEngine$$anonfun$traverseSubNodes$1$1.apply(Engine.scala:427)
    at org.scalatest.SuperEngine$$anonfun$traverseSubNodes$1$1.apply(Engine.scala:401)
    at scala.collection.immutable.List.foreach(List.scala:381)
    at org.scalatest.SuperEngine.traverseSubNodes$1(Engine.scala:401)
    at org.scalatest.SuperEngine.org$scalatest$SuperEngine$$runTestsInBranch(Engine.scala:396)
    at org.scalatest.SuperEngine.runTestsImpl(Engine.scala:483)
    at org.scalatest.FunSpecLike$class.runTests(FunSpecLike.scala:464)
    at org.scalatest.FunSpec.runTests(FunSpec.scala:1626)
    at org.scalatest.Suite$class.run(Suite.scala:1424)
    at org.scalatest.FunSpec.org$scalatest$FunSpecLike$$super$run(FunSpec.scala:1626)
    at org.scalatest.FunSpecLike$$anonfun$run$1.apply(FunSpecLike.scala:468)
    at org.scalatest.FunSpecLike$$anonfun$run$1.apply(FunSpecLike.scala:468)
    at org.scalatest.SuperEngine.runImpl(Engine.scala:545)
    at org.scalatest.FunSpecLike$class.run(FunSpecLike.scala:468)
    at com.mhedu.common.datalake.DatalakeFunSpecTest.org$scalatest$BeforeAndAfter$$super$run(DatalakeFunSpecTest.scala:13)
    at org.scalatest.BeforeAndAfter$class.run(BeforeAndAfter.scala:241)
    at com.mhedu.common.datalake.DatalakeFunSpecTest.run(DatalakeFunSpecTest.scala:13)
    at org.scalatest.tools.SuiteRunner.run(SuiteRunner.scala:55)
    at org.scalatest.tools.Runner$$anonfun$doRunRunRunDaDoRunRun$3.apply(Runner.scala:2563)
    at org.scalatest.tools.Runner$$anonfun$doRunRunRunDaDoRunRun$3.apply(Runner.scala:2557)
    at scala.collection.immutable.List.foreach(List.scala:381)
    at org.scalatest.tools.Runner$.doRunRunRunDaDoRunRun(Runner.scala:2557)
    at org.scalatest.tools.Runner$$anonfun$runOptionallyWithPassFailReporter$2.apply(Runner.scala:1044)
    at org.scalatest.tools.Runner$$anonfun$runOptionallyWithPassFailReporter$2.apply(Runner.scala:1043)
    at org.scalatest.tools.Runner$.withClassLoaderAndDispatchReporter(Runner.scala:2722)
    at org.scalatest.tools.Runner$.runOptionallyWithPassFailReporter(Runner.scala:1043)
    at org.scalatest.tools.Runner$.run(Runner.scala:883)
    at org.scalatest.tools.Runner.run(Runner.scala)
    at org.jetbrains.plugins.scala.testingSupport.scalaTest.ScalaTestRunner.runScalaTest2(ScalaTestRunner.java:138)
    at org.jetbrains.plugins.scala.testingSupport.scalaTest.ScalaTestRunner.main(ScalaTestRunner.java:28)
</code></pre>

<p>Is there any way I can write assertions for <code>Column</code> type or somehow extract raw value of column in Boolean and do the comparison?</p>
",https://stackoverflow.com/questions/45555190/scala-unit-testing-a-column-type-function,"['scala', 'unit-testing', 'scalatest']",1104,TRUE,0,1
Null error while unit testing for webcontrols,"<p>I am trying to unit test the function </p>

<pre><code>int add(a,b)
{
  int c = txtInputBox.value;
  int d = a+b+c;
  return d;
}
</code></pre>

<p>here, I am just passing the values a and b. I am not passing the value for C. It's taking from a textbox. </p>

<p>When I call the function in my web application project, the function works fine since I taking the value of C from the aspx page control. </p>

<p>But when I run this function from the unit test project, text box control fail as the page will not get loaded, so the textbox also will not get loaded. The function add(a,b) is executed through unit test project.</p>

<blockquote>
  <p>Hence, txtInputBox  will be null</p>
</blockquote>

<p>This the unit test goes to a debug error, null exception and unit test go to catch and the unit test fails.</p>

<p>How to solve this issue?</p>
",https://stackoverflow.com/questions/46236027/null-error-while-unit-testing-for-webcontrols,"['c#', 'asp.net', '.net', 'unit-testing', 'testing']",70,TRUE,0,1
the value from unit testing not found,"<p>I am beginner with unit testing. I have class for testing and the value not show. I don't know root cause from. the value transaction time not show. I don't really understand for this code. Maybe you can give me explanation why the value not show. the code:</p>

<p>class testing:</p>

<pre><code>@Test
public void Testing2() throws Exception {
    RequestEmailTO requestEmailTo = new RequestEmailTO();
    Date transDate = DateUtil.now();
    Map&lt;String, String&gt; maps = new HashMap&lt;String, String&gt;();
    requestEmailTo.setTransactionTime(DateUtil.formatDateToStr(transDate, ""yyyy-MM-dd hh:mm:ss.SSS""));

    List&lt;NameValuePair&gt; result = SendEmailRequestGenerator.generateRequest(maps);
    System.out.println(result);
}
</code></pre>

<p>RequestEmailTO:</p>

<pre><code>public class RequestEmailTO extends RequestBaseFormParamTO{

    @FormParam(""processCode"")
    private String processCode;
    @FormParam(""tos"")
    private String to;
    @FormParam(""ccs"")
    private String cc;
    @FormParam(""bccs"")
    private String bcc;
    @FormParam(""subject"")
    private String subject;
    @FormParam(""message"")
    private String message;
    @FormParam(""chdrNum"")
    private String chdrNum;
    @FormParam(""policyHolder"")
    private String policyHolder;
    @FormParam(""agentType"")
    private String agentType;
    @FormParam(""agentName"")
    private String agentName;
    @FormParam(""emailAgent"")
    private String emailAgent;
    @FormParam(""replyTo"")
    private String replyTo;
    // setter and getter
    }
</code></pre>

<p>RequestBaseFormParamTO :</p>

<pre><code>public class RequestBaseFormParamTO extends BaseFormParamTO {
    @FormParam(""channelId"")
    private String channelId;
    @FormParam(""signatureString"")
    private String signatureString;
    // setter and getter
}
</code></pre>

<p>SendEmailRequestGenerator:</p>

<pre><code>public class SendEmailRequestGenerator {
public static List&lt;NameValuePair&gt; generateRequest(Map&lt;String, String&gt; maps){

        List&lt;NameValuePair&gt; parameters = new ArrayList&lt;NameValuePair&gt;();
        parameters.add(new BasicNameValuePair( 
                ApplicationConstanta.EmailConstanta.TO, maps.get(ApplicationConstanta.EmailConstanta.TO)));
        parameters.add(new BasicNameValuePair(
                ApplicationConstanta.EmailConstanta.SUBJECT, maps.get(ApplicationConstanta.EmailConstanta.SUBJECT)));
        parameters.add(new BasicNameValuePair(
                ApplicationConstanta.EmailConstanta.CC, maps.get(ApplicationConstanta.EmailConstanta.CC)));
        parameters.add(new BasicNameValuePair(
                ApplicationConstanta.EmailConstanta.BCC, maps.get(ApplicationConstanta.EmailConstanta.BCC)));
        parameters.add(new BasicNameValuePair(
                ApplicationConstanta.EmailConstanta.MESSAGE, maps.get(ApplicationConstanta.EmailConstanta.MESSAGE)));
        parameters.add(new BasicNameValuePair(
                ApplicationConstanta.EmailConstanta.TRANSACTION_ID, maps.get(ApplicationConstanta.EmailConstanta.TRANSACTION_ID)));
        parameters.add(new BasicNameValuePair(
                ApplicationConstanta.EmailConstanta.TRANSACTION_TIME, maps.get(ApplicationConstanta.EmailConstanta.TRANSACTION_TIME)));
        parameters.add(new BasicNameValuePair(
                ApplicationConstanta.EmailConstanta.CHANNEL_ID, maps.get(ApplicationConstanta.EmailConstanta.CHANNEL_ID)));
        parameters.add(new BasicNameValuePair(
                ApplicationConstanta.EmailConstanta.SIGNATURE_STRING, maps.get(ApplicationConstanta.EmailConstanta.SIGNATURE_STRING)));
        parameters.add(new BasicNameValuePair(
                ApplicationConstanta.EmailConstanta.PROCESS_CODE, maps.get(ApplicationConstanta.EmailConstanta.PROCESS_CODE)));
        parameters.add(new BasicNameValuePair(
                ApplicationConstanta.EmailConstanta.REPLY_TO, maps.get(ApplicationConstanta.EmailConstanta.REPLY_TO)));

        return parameters;
    }
}
</code></pre>

<p>the result:
[tos, subject, ccs, bccs, message, transactionId, transactionTime, channelId, signatureString, processCode, replyTo]</p>
",https://stackoverflow.com/questions/47545085/the-value-from-unit-testing-not-found,"['java', 'maven', 'unit-testing']",31,TRUE,-1,1
Unit Testing Private Functions within jQuery Plugins,"<p>I really want to start unit testing my code,  so I thought to start adding tests to some plugins I've written using QUnit.  However, I like to create custom classes/objects within my plugins to group properties and methods together, and have some separation.  On top of that, these have their own private methods.</p>

<p>I'm trying to get my head around the best way to refactor my code to allow for unit testing.  I don't like the idea of making everything public, or polluting the window object with a bunch of custom objects.  But maybe that's how things should be done?</p>

<p>Perhaps I just need some better ideas as to workflow.  Like maybe the scripts for development are all public, but when I minify it using Grunt it wraps it back up into an anonymous function?</p>

<p>Anyway, I wrote this quickly as a crude example of what I'm talking about as far as my plugin structure.  How would I write a unit test to test the 'getNewPosition' method?</p>

<pre><code>(function( $ ) {
""use strict"";

// Custom Object
var MyClass = function( element ) {
    var speed = 1;
    // Private Function
    var getNewPosition = function() {
        var currentPosition = parseFloat( element.css( ""top"" ) );
        return currentPosition + speed;
    }

    return {
        // Public Function
        update: function() {
            var newPosition = getNewPosition();
            element.css( ""top"", newPosition.toString() + ""px"" );
        }
    }
};


// jQuery Plugin
$.fn.myPlugin = function() {
    var aryElements = [];
    this.each( function() {
        var myObj = new MyClass( $( this ) );
        aryElements.push ( myObj );

    });

    $( window ).on( ""scroll"", function( event ) {
        $.each( aryElements, function( i, element ) {
            element.update();
        });

    });
    return this;
};
}( jQuery ));
</code></pre>

<p>Any help would be greatly appreciated!  Thanks!</p>
",https://stackoverflow.com/questions/42024556/unit-testing-private-functions-within-jquery-plugins,"['jquery', 'unit-testing', 'jquery-plugins', 'qunit']",140,FALSE,0,1
Unit testing generic extension method with nUnit,"<p>I wrote extention method to <code>XElement</code> class and afterwards I wanted to test it , but I am having difficulties with invoking it in my unit test. I also want to make the test generic.</p>

<p>This is the method, <code>AsBoolean</code> is simple extention of string that is not important:</p>

<pre><code>/// &lt;summary&gt;
///     Safely gets value from attribute.
/// &lt;/summary&gt;
/// &lt;typeparam name=""T""&gt; Return type.&lt;/typeparam&gt;
/// &lt;param name=""xElem""&gt;&lt;see cref=""XElement""/&gt; in which attribute will be searched.&lt;/param&gt;
/// &lt;param name=""attrName""&gt; Name of the attribute that is going to be searched. &lt;/param&gt;
/// &lt;param name=""defaultValue""&gt; Default value of the return value. &lt;/param&gt;
/// &lt;param name=""throwExceptions""&gt; Determines if this method will throw exceptions. &lt;/param&gt;
/// &lt;returns&gt; Converted value to type &lt;see cref=""T""/&gt;&lt;/returns&gt;
public static T SafeGetValue&lt;T&gt;(this XElement xElem, string attrName, T defaultValue = default(T), bool throwExceptions = false)
{
    // Sets up default value for result
    var result = defaultValue;
    var value = xElem.Attribute(attrName)?.Value;

    if (value == null) { return result; }

    try
    {
        // Treats boolean type a bit differently as .NET converter is a bit harsh.
        if (typeof(T) == typeof(bool))
        {
            // Converts string to boolean using custom extension
            result = (T) Convert.ChangeType(value.ToBoolean(), typeof(T));
            return result;
        }

        result = (T) Convert.ChangeType(value, typeof(T));
        return result;
    }
    catch (InvalidCastException ex)
    {
        Logger.LogManager.GetLogger($""{nameof(XElementExtensions)} "" +
                                        $""threw {ex} because it can't convert {value} to type {typeof(T)}"");
        if (throwExceptions)
        {
            throw;
        }
    }
    catch (Exception ex)
    {
        Logger.LogManager.GetLogger($""{nameof(XElementExtensions)} threw {ex}!"");

        if (throwExceptions)
        {
            throw;
        }
    }

    return result;
}
</code></pre>

<p>Now I want to test it like that :</p>

<pre><code>[TestFixture]
public class SafeGetValueTests
{
    private XDocument _doc;

    [SetUp]
    public void Setup()
    {
         _doc = XDocument.Parse(@""
          &lt;root&gt;
           &lt;bool&gt;&lt;/bool&gt;
           &lt;int&gt;&lt;/int&gt;
           &lt;string&gt;&lt;/string&gt;
           &lt;double&gt;&lt;/double&gt;
           &lt;decimal&gt;&lt;/decimal&gt;
           &lt;datetime&gt;&lt;/datetime&gt;
          &lt;/root&gt;
        ""); 
    }

    [TestCase(""bool"",""boolAttr"", 234235, typeof(bool))]
    [TestCase(""bool"", ""boolAttr"", ""dsfgdf"", typeof(bool))]
    [TestCase(""bool"", ""boolAttr"", 234235, typeof(bool))]
    public void SafeGetValueShouldReturnDefaultValueWhenInvokedWithTypeThatCannotBeConvertedToTheValue(
        string elementName, string attrName, object attrValue, Type type)
    {
        //Arrange
        _doc.Element(elementName)?.SetAttributeValue(attrName, attrValue);
        var genericMethod = typeof(XElementExtensions).GetMethod(""SafeGetValue"");
        genericMethod = genericMethod.MakeGenericMethod(type);
        //Act
        var value = genericMethod.Invoke(_doc.Element(elementName), 
            BindingFlags.OptionalParamBinding | 
            BindingFlags.InvokeMethod |
            BindingFlags.Static, 
            null, 
            new[] {attrName , Type.Missing, Type.Missing},
            CultureInfo.InvariantCulture);

        //Assert
        Assert.AreEqual(value, default(bool));
    }
}
</code></pre>

<p>But the invocation keeps failing with:</p>

<blockquote>
  <p>An exception of type 'System.Reflection.TargetParameterCountException' occurred in mscorlib.dll but was not handled in user code.Additional information: Parameter count mismatch.</p>
</blockquote>

<p>How do I test such scenario?</p>
",https://stackoverflow.com/questions/44843130/unit-testing-generic-extension-method-with-nunit,"['c#', 'unit-testing', 'generics']",792,TRUE,0,1
bcrypt causing unit testing to go crazy,"<p>I am using Webpack. Karma and Mocha to run a unit test:</p>

<pre><code>const assert = require('assert');
//const bcrypt = require('bcrypt');

describe('encryptPass', function() {
    it('returned hash should return ', function() {
        assert.equal(1, 1);
    });
});
</code></pre>

<p>When I comment out the bcrypt include line, the test runs fine. However, when I leave this line in, it prints a whole load of information and errors to the console:</p>

<pre><code>&gt; auth_app@1.0.0 test /tidee/auth_app
&gt; NODE_ENV=test karma start

Hash: 745e3239cb5645ae9c7c
Version: webpack 1.14.0
Time: 15923ms
                                 Asset     Size  Chunks             Chunk Names
 79515ad0788973c533405f7012dfeccd.woff  22.7 kB          [emitted]
  f4769f9bdb7466be65088239c12046d1.eot  20.1 kB          [emitted]
9b281482a6fbc52739698e0c130ea52a.woff2  11.3 kB          [emitted]
 1fff7dfa22a6c8ba9382ad03726139d3.woff  27.1 kB          [emitted]
 f2bce001e16fa48466239a51378474d1.woff    28 kB          [emitted]
 36eeac2edc10f0533f49c8e008896e40.woff  38.4 kB          [emitted]
 6a00de061f4fcc2ae24f25da53a02f4d.woff  13.2 kB          [emitted]
 fa2772327f55d8198301fdb8bcfc8158.woff  23.4 kB          [emitted]
448c34a56d699c29117adc64c43affeb.woff2    18 kB          [emitted]
  89889688147bd7575d6327160d64e760.svg   109 kB          [emitted]
                                  main  5.62 MB       0  [emitted]  main
        tests/unit/encryptPass_test.js  14.3 MB       1  [emitted]  tests/unit/encryptPass_test.js
chunk    {0} main (main) 5.43 MB
    [0] multi main 28 bytes {0}
    [1] ./~/react/react.js 56 bytes {0} [built]
    [2] ./~/process/browser.js 5.3 kB {0} {1} [built]
    [3] ./~/moment/moment.js 123 kB {0} [built]
    [4] ./~/babel-runtime/helpers/classCallCheck.js 208 bytes {0} [built]
    [5] ./~/babel-runtime/helpers/inherits.js 1.11 kB {0} [built]
    [6] ./~/babel-runtime/helpers/possibleConstructorReturn.js 542 bytes {0} [built]
    [7] ./~/babel-runtime/helpers/extends.js 544 bytes {0} [built]
    [8] ./~/babel-runtime/helpers/objectWithoutProperties.js 280 bytes {0} [built]
    [9] ./~/classnames/index.js 1.1 kB {0} [built]
   [10] ./~/react-bootstrap/lib/utils/bootstrapUtils.js 5.7 kB {0} [built]
   [11] ./~/fbjs/lib/invariant.js 1.49 kB {0} [built]
   [12] ./~/fbjs/lib/warning.js 2.1 kB {0} [built]
   [13] ./~/react-dom/lib/reactProdInvariant.js 1.24 kB {0} [built]
   [14] ./~/react-prop-types/lib/elementType.js 1.44 kB {0} [built]
   [15] ./~/object-assign/index.js 1.99 kB {0} {1} [built]
   [16] ./~/buffer/index.js 48.6 kB {0} {1} [built]
   [17] ./~/react-dom/lib/ReactDOMComponentTree.js 6.16 kB {0} [built]
   [18] ./~/invariant/browser.js 1.52 kB {0} [built]
   [19] ./~/mongoose/lib/utils.js 18 kB {0} [built]
   [20] ./~/warning/browser.js 1.81 kB {0} [built]
   [21] ./~/fbjs/lib/ExecutionEnvironment.js 1.06 kB {0} [built]
   [22] ./~/mongoose/lib/error.js 1.34 kB {0} [built]
   [23] ./~/react-bootstrap/lib/utils/createChainedFunction.js 1.04 kB {0} [built]
   [24] ./~/react-bootstrap/lib/utils/StyleConfig.js 573 bytes {0} [built]
   [25] ./~/react-dom/index.js 59 bytes {0} [built]
   [26] ./~/mongoose/lib/schematype.js 26.5 kB {0} [built]
   [27] ./~/react-bootstrap/lib/utils/ValidComponentChildren.js 4.36 kB {0} [built]
   [28] ./~/react/lib/ReactComponentTreeHook.js 10.4 kB {0} [built]
   [29] ./~/axios/lib/utils.js 7.46 kB {0} [built]
   [30] ./~/jquery/dist/jquery.js 267 kB {0} [built]
   [31] ./~/react-dom/lib/ReactInstrumentation.js 601 bytes {0} [built]
   [32] ./~/fbjs/lib/emptyFunction.js 1.08 kB {0} [built]
   [33] ./~/mongoose/lib/document.js 68.8 kB {0} [built]
   [34] ./~/core-js/library/modules/_core.js 117 bytes {0} [built]
   [35] ./~/core-js/library/modules/_wks.js 368 bytes {0} [built]
   [36] ./~/react-bootstrap/lib/SafeAnchor.js 3.8 kB {0} [built]
   [37] ./~/react-dom/lib/ReactUpdates.js 9.53 kB {0} [built]
   [38] ./~/react-intl/lib/index.js 62.1 kB {0} [built]
   [39] ./~/react/lib/ReactCurrentOwner.js 623 bytes {0} [built]
   [40] ./~/react-dom/lib/SyntheticEvent.js 9.18 kB {0} [built]
   [41] ./client/src/helpers/doFetch.js 4.55 kB {0} [built]
...
WARNING in ./~/bcrypt/bcrypt.js
Critical dependencies:
6:15-36 the request of a dependency is an expression
 @ ./~/bcrypt/bcrypt.js 6:15-36

WARNING in ./~/node-pre-gyp/lib/pre-binding.js
Critical dependencies:
19:22-48 the request of a dependency is an expression
 @ ./~/node-pre-gyp/lib/pre-binding.js 19:22-48

WARNING in ./~/bcrypt/CHANGELOG.md
Module parse failed: /tidee/auth_app/node_modules/bcrypt/CHANGELOG.md Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected character '#' (1:0)
    at Parser.pp$4.raise (/tidee/auth_app/node_modules/acorn/dist/acorn.js:2221:15)
    at Parser.pp$7.getTokenFromCode (/tidee/auth_app/node_modules/acorn/dist/acorn.js:2756:10)
    at Parser.pp$7.readToken (/tidee/auth_app/node_modules/acorn/dist/acorn.js:2477:17)
    at Parser.pp$7.nextToken (/tidee/auth_app/node_modules/acorn/dist/acorn.js:2468:15)
    at Parser.parse (/tidee/auth_app/node_modules/acorn/dist/acorn.js:515:10)
    at Object.parse (/tidee/auth_app/node_modules/acorn/dist/acorn.js:3098:39)
    at Parser.parse (/tidee/auth_app/node_modules/webpack/lib/Parser.js:902:15)
    at NormalModule.&lt;anonymous&gt; (/tidee/auth_app/node_modules/webpack/lib/NormalModule.js:104:16)
    at NormalModule.onModuleBuild (/tidee/auth_app/node_modules/webpack-core/lib/NormalModuleMixin.js:310:10)
    at nextLoader (/tidee/auth_app/node_modules/webpack-core/lib/NormalModuleMixin.js:275:25)
    at /tidee/auth_app/node_modules/webpack-core/lib/NormalModuleMixin.js:259:5
    at Storage.finished (/tidee/auth_app/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:38:16)
    at /tidee/auth_app/node_modules/graceful-fs/graceful-fs.js:78:16
    at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:415:3)
 @ ./~/bcrypt ^\.\/.*$
</code></pre>

<p>and it goes on an on!!</p>
",https://stackoverflow.com/questions/41837766/bcrypt-causing-unit-testing-to-go-crazy,"['unit-testing', 'bcrypt']",439,FALSE,0,0
VS Unit Testing can&#39;t open database (sqlite3),"<p>I am using Visual Studio with unit testing. Created a test project, whose directory sits inside the project I am testing. </p>

<p>I am trying to ""unit test"" a function which opens database files, and creates class objects based on the contents of the database.
The function itself actually works fine.</p>

<pre><code>bool import_materials_from_db(const char *db_name){
    sqlite3 *db;
    int rc = sqlite3_open_v2(db_name, &amp;db, 2, NULL);
    if (rc != SQLITE_OK) {
        std::cout &lt;&lt; ""The database \"""" &lt;&lt; db_name &lt;&lt; ""\"" was not found.\n"";
        return false;
    }
}
</code></pre>

<p>I've cut the function down significantly, as this is the point where it fails.
RC indicates the error code SQLITE_CANTOPEN (14).
The other thing passed to the function is an std::vector&lt;> holding my class. Don't believe this is particularly relevant.</p>

<p>I call the function like so:</p>

<pre><code>import_materials_from_db(""materials.db"");
</code></pre>

<p>This works great within the main application, but as soon as I try it within my unit testing:</p>

<pre><code>import_materials_from_db(""test_database.db"");
</code></pre>

<p>I have no luck.</p>

<p>Project Directory:</p>

<pre><code>Advanced_Task_1\
</code></pre>

<p>Unit Testing Directory:</p>

<pre><code>Advanced_Task_1\UnitTest1\
</code></pre>

<p>I have tried placing the database file within each directory just in case.
I have tried passing ""..\test_database.db"" etc. etc.
Lastly, it's worth mentioning, I am sure this is the correct file name and I am sure there is information inside the database to be read. Still no luck.</p>

<p>Any ideas on what exactly I am doing wrong? I tried the ""look at the directory above"" trick like I do in project settings ""..\"" but it didn't like that either.</p>
",https://stackoverflow.com/questions/47366863/vs-unit-testing-cant-open-database-sqlite3,"['c++', 'visual-studio', 'unit-testing', 'c++11', 'sqlite']",231,FALSE,0,1
Mocha unit testing: where to create variables,"<p>I'm just getting into unit testing for the first time. Using Mocha in Node as the testing framework. All the examples I've come across create variables inside the <code>it()</code>. Does it matter if they are created inside or outside of <code>it()</code>? For example, if I have multiple <code>it()</code>s inside a <code>describe()</code>, and I need the same mocked data across all of the <code>it()</code>s. I'd rather not re-create the same variable repeatedly, if possible.</p>

<pre><code>describe ('MyClass', function () {
    let myObj = new MyObj // Mock data here
    it ('Should be...', function () {
        ....
    })
    it ('Should be...', function () {
        ....
    })
    ...
})
</code></pre>
",https://stackoverflow.com/questions/45766878/mocha-unit-testing-where-to-create-variables,"['node.js', 'unit-testing', 'mocha.js']",119,TRUE,0,1
Unit testing angular factory method with callbacks,"<p>I have a factory which has a method which does a $http call . it takes two obj params and 4 callbacks . How do i unit  test the method and it's callbacks using Karma -Jasmine ? all the other answers on stack aren't helping me with callbacks . </p>

<pre><code>app.factory('somefactory', ['$http','$rootScope','dependency',
function($http, $rootScope,dependency){

var factory = {
//two obj params and 4 callback parmas           
  method:function(obj1,obj2,succCallbk,failureCallbk,errCallbk,completeCallbk){
        $http({
          method: obj.method,
          url: url,
          data: requestData
        }).success(function(data, status, headers, config){
             if(someCondition){
            _succCallbk(data, status);
            }
             if(someCondition){
            _completeCallbk(data, status);
            }
          })
          .error(function(err){
           if(someCondition){
             _errCallbk()}
            })
           }
          };
 return factory;
})
</code></pre>
",https://stackoverflow.com/questions/42408324/unit-testing-angular-factory-method-with-callbacks,"['angularjs', 'unit-testing', 'jasmine', 'karma-jasmine']",60,FALSE,0,0
how to do unit testing for this?,"<pre><code>def login_user(request):
    if request.method == ""POST"":
        username = request.POST['username'] #this is my first field to be tested
        password = request.POST['password']  #this is my second field to be tested
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                playlists = Playlist.objects.filter(user=request.user)
                return render(request, 'index.html', {'playlists': playlists})
        else:
            return render(request, 'login.html', {'error_message': 'Invalid login'})
    return render(request, 'login.html')
</code></pre>

<h1>how can i do testing to this code in django and what all i need to install in order to test it</h1>
",https://stackoverflow.com/questions/43220541/how-to-do-unit-testing-for-this,"['django', 'unit-testing', 'automated-tests', 'pytest', 'pytest-django']",55,TRUE,0,1
java.lang.NullPointerException in Unit Testing spring service class,"<p>In a simple mvc application in spring boot , I want to do unit testing of a class of service layer called LibraryService (interface) and LibraryServiceImpl.</p>

<pre><code>public interface LibraryService {

    /*
     * Returns media library object given the library object id.
     */
    public MediaLibraryDetail getLibraryById(ObjectId libraryId);
}
</code></pre>

<p>Below we see it's implementation</p>

<pre><code>@Service
public class LibraryServiceImpl implements LibraryService {

    @Autowired
    private LibraryDAOImpl libDao;


    @Override
    public MediaLibraryDetail getLibraryById(ObjectId libraryId) {
        return libDao.getLibraryById(libraryId);
    }
}
</code></pre>

<p>We can see it has dependency on a class <code>MediaLibraryDetail</code>. Also, <code>ObjectId</code> is another class which is type of its parameter <code>libraryId</code>.</p>

<p>I want to do unit testing in spring boot for method <code>getLibraryById()</code>.</p>

<p>Here's is my code:</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)
public class LibraryServiceImplTest {

    @Mock
    private LibraryDAO libDao = new LibraryDAOImpl();
    @Mock
    private ObjectId libraryId;
    @InjectMocks
    private  LibraryService libraryService =new LibraryServiceImpl();


    @Test
    public void getLibraryByIdTest(){

    MediaLibraryDetail mediaLibraryDetail =new MediaLibraryDetail();
    mediaLibraryDetail.setCollectionName(""abc"");

    when(libDao.getLibraryById(libraryId)).thenReturn(mediaLibraryDetail);
    assertSame(mediaLibraryDetail,libraryService.getLibraryById(libraryId));

    }
}
</code></pre>

<p>I am getting this error <code>java.lang.NullPointerException</code> on this last line <code>assertSame(mediaLibraryDetail,libraryService.getLibraryById(libraryId));</code></p>

<p>Where am I wrong ?</p>
",https://stackoverflow.com/questions/43517377/java-lang-nullpointerexception-in-unit-testing-spring-service-class,"['java', 'spring', 'unit-testing', 'spring-mvc']",3926,TRUE,0,3
Instrumental unit testing of activity with FirebaseAuth,"<p>I'm trying to setup and instrumental unit test for <code>Activity</code> with <code>FirebaseAuth</code>. When I run the application, everything works just fine. The problem is within the setup of instrumental unit tests. </p>

<p><strong>Activity:</strong></p>

<pre><code>public final class GoogleSignInActivity extends AppCompatActivity{
  @Override
    protected void onCreate(final Bundle savedInstanceState) {
       ...
       if (FirebaseApp.getApps(this).isEmpty()) {
        FirebaseApp.initializeApp(this);
       }

       mFirebaseAuth = FirebaseAuth.getInstance();
  }
}
</code></pre>

<p><strong>Test:</strong></p>

<pre><code>@RunWith(AndroidJUnit4.class)
public class GoogleSignInActivityIntegrationTest extends UiTestPrerequesites {

@Rule
public final ActivityTestRule&lt;GoogleSignInActivity&gt; mActivityRule = new ActivityTestRule&lt;&gt;(
        GoogleSignInActivity.class, false, true);

@Before
public void setup(){
    if (FirebaseApp.getApps(InstrumentationRegistry.getContext()).isEmpty()) {
        FirebaseApp.initializeApp(InstrumentationRegistry.getContext());
    }
}   

@Test
@SmallTest
public void implements_GoogleSignInWorkerFragment_GoogleSignInUiChangesListener() {
    //FirebaseApp.initializeApp(InstrumentationRegistry.getContext()); (this doesn't help)
    assertThat(mActivityRule .getActivity(),
                notNullValue());
}
</code></pre>

<p>}</p>

<p><strong>Exception (only when running test, not app):</strong></p>

<pre><code>Caused by: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.twofortyfouram.ui.test. Make sure to call FirebaseApp.initializeApp(Context) first.
</code></pre>
",https://stackoverflow.com/questions/42978192/instrumental-unit-testing-of-activity-with-firebaseauth,"['android', 'unit-testing', 'firebase', 'firebase-authentication']",593,TRUE,0,1
C# RhinoMock Nested Mapping Tables Unit Testing,"<p>Below are three tables one of them is Master table and two are relation with each one. while doing unit testing I am not able to get the few test cases scenario based on the my business logic. </p>

<pre><code>public class Employee
{
    public int ID { get; set; }
    public string Name { get; set; }
    public virtual ICollection&lt;EmployeeDepartment&gt; EmployeeDepartments { get; set; }
}

public class EmployeeDepartment
{
    public int EmployeeID { get; set; }
    public int DepartmentID { get; set; }

    public virtual Department { get; set; }
    public virtual Employee{ get; set; }
}

public class Department
{
    public int ID { get; set; }
    public string DName { get; set; }
    public virtual ICollection&lt;EmployeeDepartment&gt; EmployeeDepartments { get; set; }
}
</code></pre>

<p>Here is my unit test method code: </p>

<pre><code>// Arrange
var employees = new FakeDbSet&lt;Employee&gt;();            
Expect.Call(dataContext.Set&lt;Employee&gt;()).Return(employees).Repeat.Any();

// Act
--Code for Service Method

// Assert
var actualEmpl = this.actualEmpl;
Assert.IsTrue(actualEmpl.EmployeeDepartment.Any(w =&gt; w.Department.DName == ""ABC""));
</code></pre>

<blockquote>
  <p>My problem here is I always get ""w.Department.DName"" is null. Please
  help me to get it resolve.</p>
  
  <p>Department is master table list (min 20 rows) and EmployeeDepartment
  can only have single or couple of records.</p>
</blockquote>
",https://stackoverflow.com/questions/43431257/c-rhinomock-nested-mapping-tables-unit-testing,"['c#', 'unit-testing', 'rhino-mocks']",28,FALSE,0,0
Unit Testing .Component using $componentController - specifcially $postLink,"<p>Inside my $postLink method that i am manually firing in the unit test the vm/$ctrl values from the binding are not defined.</p>

<p><a href=""https://plnkr.co/edit/Frj8WvGM4bh0gRAKJhUS?p=preview"" rel=""nofollow noreferrer"">Working Link</a></p>

<p><a href=""https://puu.sh/uGL5s/787279a494.png"" rel=""nofollow noreferrer"">Console Error Image</a></p>

<p>Component Spec</p>

<pre><code>angular.module('softwearplayApp')
.component('swImageEditor', {
    templateUrl: 'views/sw-image-editor.html',
    bindings: {
      image: '&lt;',
      close: '&amp;',
      mode: '&lt;',
      save: '&amp;'
    },
    controller: SwImageEditorController
  });
</code></pre>

<p>PostLink Method</p>

<pre><code>$ctrl.$postLink = function() {
  console.log($ctrl.image); //&lt;----------- $ctrl.image is defined
  $timeout(function() {
    var img = new Image();

    img.src = $ctrl.image.url; //&lt;--------- $ctrl.image is undefined
    img.classList.toggle('hidden');

    imageContainer = $element[0].querySelector('.image-editor__container');
    cropResultContainer = $element[0].querySelector('.image-editor__crop-result');

    imageContainer.append(img);

    cropper = new Cropper(img, {
      aspectRatio: ASPECT_RATIO[$ctrl.mode]['4/3'],
      ready: function() {
        $ctrl.isLoading = false;
      }
    });
  });
};
</code></pre>

<p>After the $timeout is flushed the binding that we have passed in become undefined.</p>

<p>Unit Test:</p>

<pre><code>var
    $componentController,
    $timeout,
    $ctrl,
    $rootScope = {},
    LOCALS = {
      $element: {}
    },
    BINDINGS = {
      image: {url: 'abcdef'},
      close: function() {},
      mode: 'landscape',
      save: function() {
      }
    },
    ASPECT_RATIO;

  beforeEach(inject(function(_$rootScope_, $compile, $templateCache, _$componentController_, _ASPECT_RATIO_, _$timeout_) {
    ASPECT_RATIO = _ASPECT_RATIO_;
    $timeout = _$timeout_;
    $componentController = _$componentController_;
    $rootScope = _$rootScope_;
    LOCALS.$scope = $rootScope.$new();
    LOCALS.$element = angular.element('&lt;sw-image-editor&gt;&lt;/sw-image-editor&gt;');
    LOCALS.$element = $compile(LOCALS.$element)(LOCALS.$scope);
  }));

    it('should define the $postLink', function() {
     $ctrl = $componentController('swImageEditor', LOCALS, BINDINGS);
      $ctrl.$postLink();
      $timeout.flush();
      expect($ctrl.showCroppedImage).toBeTruthy();
      expect($ctrl.isLoading).toBeFalsy();
    });

  });
</code></pre>
",https://stackoverflow.com/questions/42721090/unit-testing-component-using-componentcontroller-specifcially-postlink,"['javascript', 'angularjs', 'unit-testing', 'angular-components']",540,FALSE,0,0
Robolectric Unit Testing ClassCastException on Custom Layout,"<p>I have ""ClassCastException"" on Robolectric Unit Testing when I test Activity or Fragment with Custom Layout or Custom Component on an android app.
Example : 
<strong>CrumbView</strong> that extends LinearLayout. When I start a fragment I got an error : 
<strong><em>java.lang.ClassCastException: com.app.test.ui.view.CrumbView cannot be cast to com.app.test.ui.view.CrumbView</em></strong>
Does Anyone knows how to fix it? or it's not yet supported by Robolectric?</p>

<pre><code>java.lang.ClassCastException: com.app.test.ui.view.DrawerView cannot be cast to com.app.test.ui.view.DrawerView

at com.app.test.ui.activity.equipements.EquipementsActivity.onCreate(EquipementsActivity.java:61)
at android.app.Activity.performCreate(Activity.java:6975)
at org.robolectric.util.ReflectionHelpers.callInstanceMethod(ReflectionHelpers.java:232)
at org.robolectric.android.controller.ActivityController$1.run(ActivityController.java:58)
at org.robolectric.shadows.ShadowLooper.runPaused(ShadowLooper.java:364)
at org.robolectric.shadows.CoreShadowsAdapter$1.runPaused(CoreShadowsAdapter.java:26)
at org.robolectric.android.controller.ActivityController.create(ActivityController.java:55)
at org.robolectric.android.controller.ActivityController.create(ActivityController.java:65)
at com.app.test.ui.activity.equipements.EquipementsActivityTest.setUp(EquipementsActivityTest.java:24)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.powermock.modules.junit4.rule.PowerMockStatement$1.run(PowerMockRule.java:83)
at org.powermock.reflect.internal.WhiteboxImpl.performMethodInvocation(WhiteboxImpl.java:1846)
at org.powermock.reflect.internal.WhiteboxImpl.doInvokeMethod(WhiteboxImpl.java:810)
at org.powermock.reflect.internal.WhiteboxImpl.invokeMethod(WhiteboxImpl.java:675)
at org.powermock.reflect.Whitebox.invokeMethod(Whitebox.java:401)
at org.powermock.classloading.AbstractClassloaderExecutor.getResult(AbstractClassloaderExecutor.java:76)
at org.powermock.classloading.AbstractClassloaderExecutor.invokeWithClassLoader(AbstractClassloaderExecutor.java:64)
at org.powermock.classloading.AbstractClassloaderExecutor.executeWithClassLoader(AbstractClassloaderExecutor.java:56)
at org.powermock.classloading.SingleClassloaderExecutor.execute(SingleClassloaderExecutor.java:33)
at org.powermock.classloading.AbstractClassloaderExecutor.execute(AbstractClassloaderExecutor.java:40)
at org.powermock.modules.junit4.rule.PowerMockStatement.evaluate(PowerMockRule.java:75)
at org.robolectric.internal.SandboxTestRunner$2.evaluate(SandboxTestRunner.java:226)
at org.robolectric.internal.SandboxTestRunner.runChild(SandboxTestRunner.java:108)
at org.robolectric.internal.SandboxTestRunner.runChild(SandboxTestRunner.java:35)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.robolectric.internal.SandboxTestRunner$1.evaluate(SandboxTestRunner.java:62)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner$2.call(DelegatingPowerMockRunner.java:149)
at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner$2.call(DelegatingPowerMockRunner.java:141)
at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner.withContextClassLoader(DelegatingPowerMockRunner.java:132)
at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner.run(DelegatingPowerMockRunner.java:141)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:121)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:57)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)
</code></pre>

<p>The Line onCreate(EquipementsActivity.java:61) is pointing :
<strong>DrawerView drawerView = findViewById(R.id.drawer);</strong></p>

<pre><code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_equipements);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    DrawerLayout drawer = findViewById(R.id.drawer_layout);
    DrawerView drawerView = findViewById(R.id.drawer);
    ActionBarDrawerToggle toggle .......
</code></pre>
",https://stackoverflow.com/questions/47391630/robolectric-unit-testing-classcastexception-on-custom-layout,"['java', 'android', 'unit-testing', 'android-fragments', 'robolectric']",893,TRUE,0,1
Jasmine 2.0 unit testing for angularjs factory,"<p>I am new to writing jasmine test cases for angularJS factory. 
I want to test the entire factory, but I'm unable to fetch <code>getKeys</code>. Here's my factory.</p>

<p><strong>My Factory is:</strong></p>

<pre><code>'use strict';
var a11yModule = angular.module('TestModule', ['ui.bootstrap']);
a11yModule.factory('TestFacotry', ['$q', '$timeout', function ($q, $timeout) {
    return {
        getKeys: function () {
            return {
                ""abc"": 32,
                ""gpa"": 33,
                ""end"": 35
            };
        }
    };
}])
</code></pre>

<p><strong>My Unit Spec is:</strong></p>

<pre><code>describe('modu testing', function () {
    var TestFacotryMock, q, timeout;
    beforeEach(module('TestModule', ['ui.bootstrap']));

    beforeEach(inject(function (_$q_, _$timeout_, _TestFacotry_) {
        q = _$q_;
        timeout = _$timeout_;
        TestFacotryMock = _TestFacotry_;

    }));

    it('Should ', function () {
        //var output = TestFacotryMock.getKeys.something();
        expect(typeof getKeys()).toBe('function');
    });

});
</code></pre>

<p><strong>Error is</strong></p>

<p>Error: [$injector:modulerr] Failed to instantiate module TestModule due to:
Error: [$injector:modulerr] Failed to instantiate module ui.bootstrap due to:
Error: [$injector:nomod] Module 'ui.bootstrap' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.</p>
",https://stackoverflow.com/questions/43864466/jasmine-2-0-unit-testing-for-angularjs-factory,"['angularjs', 'unit-testing', 'karma-jasmine', 'jasmine2.0', 'angular-factory']",519,TRUE,0,1
How to do unit testing with Laravel Localization?,"

<p>I'm using <code>mcamara/laravel-localization</code> package and I can't figure out how to make it work with my unit tests. Both of the following fail with red:</p>

<pre class=""lang-php prettyprint-override""><code>// 1. This one results in ""Redirecting to http://myapp.dev/en""
$this-&gt;get('/')-&gt;assertSee('My App Homepage');

// 2. This one results in 404
$this-&gt;get('/en')-&gt;assertSee('My App Homepage');
</code></pre>

<p>In the browser, <code>http://myapp.dev</code> returns 302 with a redirect to <code>http://myapp.dev/en</code>, fair enough. However, <code>http://myapp.dev/en</code> returns 200. So both cases work 100% fine on the front-end, but not with unit tests.</p>

<p>I <em>do</em> have some customization however, which once again, works like charm in the browser.</p>

<pre class=""lang-php prettyprint-override""><code>// in web.php
Route::group([
    'prefix' =&gt; app('PREFIX'), // instead of LaravelLocalization::setLocale()
    'middleware' =&gt; ['localeSessionRedirect', 'localizationRedirect']],
    function() {
        Route::get('/', function() {
            return view('home');
        });
    }
]);

// in AppServiceProvider.php
public function boot()
{
    // This, unlike LaravelLocalization::setLocale(), will determine the 
    // language based on URL, rather than cookie, session or other
    $prefix = request()-&gt;segment(1); // expects 'en' or 'fr'
    $this-&gt;app-&gt;singleton('PREFIX', function($app) use ($prefix) {
        return in_array($prefix, ['en', 'fr']) ? $prefix : null;
    });
}
</code></pre>

<p>Hopefully this code makes sense to you. Thanks!</p>

<h3>UPDATE</h3>

<p>I addressed this problem with the package in a <a href=""https://github.com/mcamara/laravel-localization/issues/435"" rel=""noreferrer"">GitHub issue #435</a>.</p>

<h3>UPDATE 2</h3>

<p>Insofar as I could figure it out, it seems that you can safely test your localized routes as long as you specify the locale in the base URL in your phpunit XML file: </p>

<pre class=""lang-php prettyprint-override""><code>&lt;env name=""APP_URL"" value=""http://myapp.dev/en""/&gt;
</code></pre>

<p>However, this would work for your localized GET endpoints (which start with a locale prefix, e.g. 'en'), but not for non-localized POST, PUT, etc. (which don't have any prefix). Hence, you can't really test both kinds of endpoints at the same time, unless you use Dusk (which I don't, as it's an overkill and much slower, almost the same as doing it manually).</p>
",https://stackoverflow.com/questions/43440215/how-to-do-unit-testing-with-laravel-localization,"['laravel', 'phpunit', 'laravel-5.4', 'laravel-localization']",3912,TRUE,6,2
unit testing directive with link using controller,"<p>I'm trying to unit test my directive that set form validity depending on a controller variable.
My directive code :</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>angular.module('myModule',[])
        .directive('myDirective', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attr, ctrl) {
            scope.$watch(""mailExist"", function(){
                if(scope.mailExist) {
                    ctrl.$setValidity('existingMailValidator', false);
                } else {
                    ctrl.$setValidity('existingMailValidator', true);
                }
            });
        }
    };
});</code></pre>
</div>
</div>
</p>

<p>When trying to unit test this directive, I'm trying to isolate the controller ctrl with this code:</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>describe('directive module unit test implementation', function() {
    var $scope,
        ctrl,
        form;
   
    beforeEach(module('myModule'));
   
    beforeEach(inject(function($compile, $rootScope) {
        $scope = $rootScope;
        var element =angular.element(
            '&lt;form name=""testform""&gt;' +
                '&lt;input name=""testinput"" user-mail-check&gt;' +
            '&lt;/form&gt;'
        ); 
        var ctrl = element.controller('userMailCheck');
        $compile(element)($scope);
        $scope.$digest();
        form = $scope.testform;
    }));
      
    describe('userMailCheck directive test', function() {
       it('should test initial state', function() {
           expect(form.testinput.$valid).toBe(true);
       }); 
    });
});</code></pre>
</div>
</div>
</p>

<p>Running this test, I still obtain:
 Cannot read property '$setValidity' of undefined
that's mean I haven't really inject a controller.
What is wrong in my test?</p>
",https://stackoverflow.com/questions/41792246/unit-testing-directive-with-link-using-controller,"['angularjs', 'unit-testing', 'angularjs-directive']",622,TRUE,0,1
.CopyToDataTable() is not available for unit testing?,"<p>I want to write a Testmethod with using <code>.CopyToDataTable()</code>. But <code>.CopyToDataTable()</code> is not available for unit testing, only <code>.Copy()</code>. The Error say's: </p>

<blockquote>
  <p>DataRow[] has no extension for .CopyToDataTable(). </p>
</blockquote>

<p>Why?</p>

<p>In my normal classes the same two lines work and I got no error.</p>

<pre><code>using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Text;
using System.Data;

namespace home.Tests
{
    [TestClass()]
    public class LinkIOTests
    {
        [TestMethod()]
        public void ReadDataTest()
        {
            DataTable ExcelDaten = new DataTable();
            DataTable LineTable = ExcelDaten.Select(""STRECKE = 'TestName'"").CopyToDataTable();
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/44754841/copytodatatable-is-not-available-for-unit-testing,"['c#', 'unit-testing']",51,TRUE,0,1
Lombok with Spring compatible for Unit testing?,"<p>I just try to get used to Lombok but have already a problem.</p>

<p>I used that <a href=""http://www.baeldung.com/intro-to-project-lombok"" rel=""nofollow noreferrer"">http://www.baeldung.com/intro-to-project-lombok</a> and another tutorial but these and google cannot help.</p>

<p>My classes:</p>

<pre><code>package springprojekt;

import lombok.Data;
import lombok.RequiredArgsConstructor;

import java.io.Serializable;
import java.util.concurrent.atomic.AtomicInteger;
@Data
@RequiredArgsConstructor
public class Person implements Serializable {

    private static AtomicInteger idGenerator = new AtomicInteger();

    private final String firstName;
    private final String lastName;
    private final int id;


    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
        id = idGenerator.getAndIncrement();
    }
}
</code></pre>

<p>and my test</p>

<pre><code>package springprojekt;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {

    @Test
    public void contextLoads() {
        Person person = new Person(""Max"", ""Peter"");
    }

}
</code></pre>

<p>I understood that lombok creates getter and setter (in that case not applicable) for me.
I actually want access in that test like person.getFirstName()
But my IDE (IntelliJ Ultimate) denies to work because there is no matching method.
So how can I test it please? Or did I do anything wrong?</p>
",https://stackoverflow.com/questions/43542713/lombok-with-spring-compatible-for-unit-testing,"['spring', 'unit-testing', 'lombok']",1507,FALSE,0,0
Using Alembic in unit testing a SQLAlchemy app?,"<p>I have and ORM app that uses SQLAlchemy, Alembic for migration and Pytest for testing. In my testing, I have a database as a fixture. It used to be, before I used migrations, that I dropped all the tables and recreated them for each testing session. </p>

<p>Now that I am using migrations, I want to use Alembic in creating my fixtures too because I believe that mimics a production environment more closely.(Is that a good rationale?)</p>

<p>One way to do it is to <code>downgrade()</code> all the way down and <code>upgrade()</code> up each time. I don't really like this. I might be wrong.</p>

<p>Another would be to <code>drop_all()</code> and <code>create_all()</code> for unit tests, and just write another test that stamps the database with head and tests an <code>upgrade</code> and <code>downgrade</code>.</p>

<p>Is there another good/standard way to integrate migrations with fixtures so I do not have to use <code>drop_tables</code>?</p>

<p>Or is there a way to, after <code>drop_tables</code> stamp the db as ""tail"" or empty? without explicitly using the migration hash for revision 0, cause that creates dependencies, something like <code>alembic downgrade -1</code> that will make it go back to year 0. Thank you.</p>
",https://stackoverflow.com/questions/41905890/using-alembic-in-unit-testing-a-sqlalchemy-app,"['python', 'unit-testing', 'sqlalchemy', 'integration-testing', 'alembic']",8125,TRUE,6,1
Unit testing ContainerRequestFilter which uses ResourceInfo with mockito,"<p>I'm trying to use Mockito to unit test a ContainerRequestFilter, which is applied using @NameBinding. The filter checks an annotation field to determine what to do.
See sample code:</p>

<p><strong>Annotation</strong></p>

<pre><code>@Target({TYPE, METHOD})
@NameBinding
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    MyEnum info() default MyEnum.DEFAULT;
}
</code></pre>

<p><strong>MyEnum</strong></p>

<pre><code>public enum MyEnum {
    VALUE1,
    VALUE2,
    DEFAULT
}
</code></pre>

<p><strong>Annotated Filter which uses MyEnum as conditional</strong></p>

<pre><code>@MyAnnotation
public class MyFilter implements ContainerRequestFilter {

    @Context
    private ResourceInfo resourceInfo;

    @Override
    public void filter(ContainerRequestContext containerRequestContext) throws IOException {

        if (resourceInfo.getResourceMethod().getAnnotation(MyAnnotation.class).info().equals(MyEnum.VALUE1)) 
        {
            // set some value or throw some exception (this can be verified in the test)
        }

        if (resourceInfo.getResourceMethod().getAnnotation(MyAnnotation.class).info().equals(MyEnum.VALUE2))
        {
           // set some value or throw some exception (this can be verified in the test)
        }
    }
}
</code></pre>

<p><strong>Annotated Resource methods</strong></p>

<pre><code>@Path(""/somepath1"")
public class MyResource1
{
    @GET
    @MyAnnotation(info = MyEnum.VALUE1)
    public Response someResourceMethod()
    {
        // return response
    } 
}


@Path(""/somepath2"")
public class MyResource2
{
    @GET
    @MyAnnotation(info = MyEnum.VALUE2)
    public Response someResourceMethod()
    {
        // return response
    } 
}
</code></pre>

<p>This design makes it easy to just add enum values when there are new conditions to be added to the filter.</p>

<p>How can I unit test <code>MyFilter</code>, by varying the values in the conditional?</p>

<p>One approach I tried was to mock <code>ResourceInfo</code> and then return mock <code>Method</code> when <code>resourceInfo.getResourceMethod()</code>, but this cannot be done since Method is a final class. </p>

<p>Also mocking objects you don't own is not recommended, so is there a different approach to test this? I am also not wedded to Mockito, so open to any other suggestions.</p>
",https://stackoverflow.com/questions/45576542/unit-testing-containerrequestfilter-which-uses-resourceinfo-with-mockito,"['java', 'unit-testing', 'jersey', 'jax-rs', 'mockito']",6184,TRUE,5,1
Unit testing with Generic Repository in .net Core,"<p>I'm building a test project to fiddle around with .net core and I'm hitting a snag of some sorts. The basic idea of the toying around is adding products to the context, no biggie right. Well wrong. Because I was raised as a good programmer I always start off from the TDD way to go. So I tried the following test.</p>

<pre><code>[Fact]
public async Task AddProduct_ReturnCreatedWithProduct()
{
    Product testProduct = ProductHelpers.GenerateTestProduct();
    var mockRepo = new Mock&lt;IRepository&lt;Product&gt;&gt;();
    mockRepo.Setup(repo =&gt; repo.Get(testProduct.ProductID)).Returns(Task.FromResult(testProduct));
    var controller = new ProductController(mockRepo.Object);

    var result = await controller.Post(new ProductViewModel() { ProductID = 1, ProductShortDesc = PRODUCT_SHORTDESC, ProductDescription = PRODUCT_DESC });
    var okResult = Assert.IsType&lt;OkObjectResult&gt;(result);
    var returnProduct = Assert.IsType&lt;Product&gt;(okResult.Value);
    Assert.Equal(testProduct.ProductShortDesc, returnProduct.ProductShortDesc);
    Assert.Equal(testProduct.ProductDescription, returnProduct.ProductDescription);
}

public static Product GenerateTestProduct()
{
    return new Product()
    {
        ProductID = 1,
        ProductShortDesc = ""FRI"",
        ProductDescription = ""Fristi""
    };
}
</code></pre>

<p>Which should return a decent <code>OkObjectResult</code>. Well no it doesn't. So I went deep diving in to the controller which gave me this.</p>

<pre><code>[HttpPost]
public async Task&lt;ActionResult&gt; Post([FromBody]ProductViewModel model)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);
    else
    {
        var product = await _productRepository.AddEntity(model.ToEntity());
        if (product == null)
            return StatusCode(500);
        else
            return Ok(product);
    }
}

public interface IRepository&lt;T&gt;
{
    Task&lt;T&gt; Get&lt;TKey&gt;(TKey id);
    IQueryable&lt;T&gt; GetAll();
    Task&lt;T&gt; AddEntity(T entity);
    Task DeleteEntity(T entity);
    Task Update(T entity);
}

public class ProductRepository : IRepository&lt;Product&gt;
{
    protected readonly DbContext Context;
    protected DbSet&lt;Product&gt; DbSet;

    public ProductRepository(ApplicationContext context)
    {
        Context = context;
        DbSet = context.Set&lt;Product&gt;();
    }

    public async Task&lt;Product&gt; AddEntity(Product entity)
    {
        try
        {
            await Context.Set&lt;Product&gt;().AddAsync(entity);
            await Save();
            return await Get(entity.ProductID);
        }
        catch (System.Exception ex)
        {
            Debug.WriteLine(ex.Message);
            throw ex;
        }
    }
    //Rest left out for shortness off this post
}
</code></pre>

<p>So running the code via postman gave me the following result:
<a href=""https://i.stack.imgur.com/syVFw.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/syVFw.png"" alt=""enter image description here""></a></p>

<p>So going back to the test because I thought, yes it works somehow now..
<a href=""https://i.stack.imgur.com/VqgHS.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/VqgHS.png"" alt=""enter image description here""></a></p>

<pre><code>[HttpPost]
public async Task&lt;ActionResult&gt; Post([FromBody]ProductViewModel model)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);
    else
    {
        var product = await _productRepository.AddEntity(model.ToEntity());
        if (product == null)
            return StatusCode(500);
        else
            return Ok(product);
    }
}
</code></pre>

<p>So that didn't go well either. I tried debugging the code to find the root cause but for some reason its not letting me step through in the interface code to find out why the Add doesn't work on my unit test, but does work on the normal postman test. (Just My Code is disabled). Hopefully some of you can help me out with this</p>
",https://stackoverflow.com/questions/41716775/unit-testing-with-generic-repository-in-net-core,"['c#', 'unit-testing', 'asp.net-core', 'moq', 'xunit']",2637,TRUE,5,1
Returnsasync(null) creates a build error when using Moq for unit testing in VS15,"<p>When I use <code>ReturnsAsync(null)</code> in a C# unit test method in Visual Studio (with <code>Moq</code>), I get the error: </p>

<blockquote>
  <p>""The call is ambiguous between the following methods or properties""</p>
</blockquote>

<p>and then a list of the <code>ReturnsAsync</code> methods which have different parameters.  I understand that this is due to the <code>ReturnsAsync</code> function being overloaded.  However, when I run the same unit test on my colleague's computer, it runs without any errors.  Does anyone know why this would happen?  Does anyone know how to fix this?</p>

<p>Also, when I build, I get warnings that:</p>

<blockquote>
  <p>all packages referencing ******** must install nuget package Microsoft.Bcl.Build.  </p>
</blockquote>

<p>Could that have any effect?</p>
",https://stackoverflow.com/questions/41636077/returnsasyncnull-creates-a-build-error-when-using-moq-for-unit-testing-in-vs15,"['c#', 'unit-testing', 'asynchronous', 'moq']",22228,TRUE,43,3
Unit testing Retrofit api call with Mockito - ArgumentCaptor,"<p>Pardon me if my question looks duplicated but I am not getting how to test retrofit API call.
<strong>build.gradle</strong> at application level</p>

<pre><code>dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile(""com.android.support.test.espresso:espresso-core:$rootProject.ext.expressoVersion"", {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile ""com.android.support:appcompat-v7:$rootProject.ext.supportLibraryVersion""
    compile ""com.jakewharton:butterknife:$rootProject.ext.butterKnifeVersion""
    annotationProcessor ""com.jakewharton:butterknife-compiler:$rootProject.ext.butterKnifeVersion""

    // Dependencies for local unit tests
    testCompile ""junit:junit:$rootProject.ext.junitVersion""
    testCompile ""org.mockito:mockito-all:$rootProject.ext.mockitoVersion""
    testCompile ""org.hamcrest:hamcrest-all:$rootProject.ext.hamcrestVersion""
    testCompile ""org.powermock:powermock-module-junit4:$rootProject.ext.powerMockito""
    testCompile ""org.powermock:powermock-api-mockito:$rootProject.ext.powerMockito""
    compile ""com.android.support.test.espresso:espresso-idling-resource:$rootProject.ext.espressoVersion""

    // retrofit, gson
    compile ""com.google.code.gson:gson:$rootProject.ext.gsonVersion""
    compile ""com.squareup.retrofit2:retrofit:$rootProject.ext.retrofitVersion""
    compile ""com.squareup.retrofit2:converter-gson:$rootProject.ext.retrofitVersion""
}
</code></pre>

<p><strong>build.gradle</strong> at project level has this extra content</p>

<p>// Define versions in a single place</p>

<pre><code>ext {
    // Sdk and tools
    minSdkVersion = 15
    targetSdkVersion = 25
    compileSdkVersion = 25
    buildToolsVersion = '25.0.2'

    supportLibraryVersion = '23.4.0'
    junitVersion = '4.12'
    mockitoVersion = '1.10.19'
    powerMockito = '1.6.2'
    hamcrestVersion = '1.3'
    runnerVersion = '0.5'
    rulesVersion = '0.5'
    espressoVersion = '2.2.2'
    gsonVersion = '2.6.2'
    retrofitVersion = '2.0.2'
    butterKnifeVersion = '8.5.1'
    expressoVersion = '2.2.2'
}
</code></pre>

<p><strong>MainActivity</strong></p>

<pre><code>public class MainActivity extends AppCompatActivity implements MainView {

    @BindView(R.id.textViewApiData)
    TextView mTextViewApiData;
    @BindView(R.id.progressBarLoading)
    ProgressBar mProgressBarLoading;

    private MainPresenter mMainPresenter;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initializeComponents();
    }

    private void initializeComponents() {
        mMainPresenter = new MainPresenter(this);
        mMainPresenter.presentDataFromApi();
    }

    @Override
    public void onResponseReceived(final String response) {
        mTextViewApiData.setText(response);
    }

    @Override
    public void onErrorReceived(final String message) {
        mTextViewApiData.setText(message);
    }

    @Override
    public void showProgressDialog(final boolean enableProgressDialog) {
        mProgressBarLoading.setVisibility(enableProgressDialog ? View.VISIBLE : View.GONE);
    }
}
</code></pre>

<p><strong>MainView</strong></p>

<pre><code>public interface MainView {

    void onResponseReceived(String response);

    void onErrorReceived(String message);

    void showProgressDialog(boolean enableProgressDialog);
}
</code></pre>

<p><strong>ApiClient</strong></p>

<pre><code>public class ApiClient {

    private static Retrofit sRetrofit;
    public static Retrofit getInstance() {
        if (sRetrofit == null) {
            sRetrofit = new Retrofit.Builder()
                    .baseUrl(Constants.Urls.BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return sRetrofit;
    }
}
</code></pre>

<p><strong>Presenter</strong></p>

<pre><code>public class MainPresenter {
    private final MainView mMainView;
    private final Call&lt;List&lt;UserResponse&gt;&gt; mCallListUserResponse;

    public MainPresenter(final MainView mainView) {
        this.mMainView = mainView;
        final ApiInterface apiInterface = ApiClient.getInstance().create(ApiInterface.class);
        mCallListUserResponse = apiInterface.getUsers();
    }

    public void presentDataFromApi() {
        mMainView.showProgressDialog(true);
        mCallListUserResponse.enqueue(new Callback&lt;List&lt;UserResponse&gt;&gt;() {
            @Override
            public void onResponse(final Call&lt;List&lt;UserResponse&gt;&gt; call,
                                   final Response&lt;List&lt;UserResponse&gt;&gt; response) {
                mMainView.onResponseReceived(Constants.DummyData.SUCCESS);
                mMainView.showProgressDialog(false);
            }

            @Override
            public void onFailure(final Call&lt;List&lt;UserResponse&gt;&gt; call, final Throwable t) {
                mMainView.onErrorReceived(Constants.DummyData.ERROR);
                mMainView.showProgressDialog(false);
            }
        });
    }
}
</code></pre>

<p><strong>ApiInterface</strong></p>

<pre><code>public interface ApiInterface {
    @GET(Constants.Urls.USERS)
    Call&lt;List&lt;UserResponse&gt;&gt; getUsers();
}
</code></pre>

<p><strong>Constants</strong></p>

<pre><code>public class Constants {
    public class Urls {
        public static final String BASE_URL = ""https://jsonplaceholder.typicode.com"";
        public static final String USERS = ""/users"";
    }
}
</code></pre>

<p>This is what I am trying to do and it's not working. Test case will pass for now as i have commented 3 of the last lines. You can view the error once you un-comment those lines.<br/>
<strong>TestCase</strong></p>

<pre><code>public class MainPresenterTest {

    @InjectMocks
    private MainPresenter mMainPresenter;
    @Mock
    private MainView mMockMainView;
    @Mock
    private Call&lt;List&lt;UserResponse&gt;&gt; mUserResponseCall;
    @Captor
    private ArgumentCaptor&lt;Callback&lt;List&lt;UserResponse&gt;&gt;&gt; mArgumentCaptorUserResponse;

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

    @Test
    public void presentDataFromApiTest() throws Exception {
        mMainPresenter.presentDataFromApi();
        verify(mMockMainView).showProgressDialog(true);
//        verify(mUserResponseCall).enqueue(mArgumentCaptorUserResponse.capture());
//        verify(mMockMainView).onResponseReceived(Constants.DummyData.SUCCESS);
//        verify(mMockMainView).showProgressDialog(false);
    }
}
</code></pre>

<p><strong>Log</strong></p>

<pre><code>Wanted but not invoked:
mUserResponseCall.enqueue(
    &lt;Capturing argument&gt;
);
-&gt; at com.example.ranaranvijaysingh.testingdemo.presenters.MainPresenterTest.presentDataFromApiTest(MainPresenterTest.java:69)
Actually, there were zero interactions with this mock.
</code></pre>
",https://stackoverflow.com/questions/42299029/unit-testing-retrofit-api-call-with-mockito-argumentcaptor,"['android', 'mockito', 'retrofit2']",7489,TRUE,5,2
Unit Testing Exceptions thrown by Entity Framework Core,"<p>I am using the in Memory database in order to unit test methods that use the Entity Framework Core.</p>

<p>I set up the database context as follows:</p>

<pre><code>var builder = new DbContextOptionsBuilder&lt;DatabaseContext&gt;().UseInMemoryDatabase();

var context = new DatabaseContext(builder.Options);
var databaseElements = Enumerable.Range(1, 10)
    .Select(i =&gt; new DatabaseElement
    {
        Id = i,
        Name = ""Name of Element""
    });
    context.DatabaseElements.AddRange(databaseElements);
    context.SaveChanges();
    _databaseContext = context;
...
</code></pre>

<p>I use this database context for the tests.
This worked fine.</p>

<p>Is it possible to use this in order to throw Entity Framework exceptions?</p>

<p>It would for example be great if I could test if my method handels those exceptions as excpected (e.g. there is no Connection to the database).</p>
",https://stackoverflow.com/questions/42625751/unit-testing-exceptions-thrown-by-entity-framework-core,"['entity-framework', 'unit-testing', 'exception', 'in-memory-database']",684,FALSE,4,0
Unit testing with an Active Record based framework,"<p>I'm using a framework which based its ORM on the <a href=""https://en.wikipedia.org/wiki/Active_record_pattern"" rel=""nofollow noreferrer"">Active Record pattern</a>. Every table I have in my database is bound to a model in my code.</p>

<p>I want to unit test these models, so I started by extracting every <code>save()</code> and <code>update()</code> call from models, so that changes are made only on objects, and they only get persisted once needed.</p>

<p>I don't know how I can apply this strategy in this case though. I have a <code>Chat</code> model, which a <code>User</code> is part of, and the <code>User</code> can add a <code>ChatNote</code> to the <code>Chat</code>.</p>

<p>Here's the current implementation :</p>

<pre><code>// User.php
public function addChatNote($chatNoteContent, Chat $chat)
{
    $chatNote = new ChatNote();
    $chatNote-&gt;content = $chatNoteContent;
    $chatNote-&gt;save();

    $chat-&gt;note()-&gt;associate($chatNote);
    $chat-&gt;save();
}
</code></pre>

<p>Now to my eyes there are tons of problems here, but the <code>save()</code> calls are really ruining my chance to do proper unit testing here.</p>

<p>I thought about creating the <code>ChatNote</code> before using that method, but what class should be responsible for creating it ? I could also save it elsewhere, and save the <code>Chat</code> elsewhere but then is the <code>User</code> really responsible for anything else than associating the <code>ChatNote</code> to the <code>Chat</code> ? And where should the <code>save()</code> be made ?</p>
",https://stackoverflow.com/questions/43689828/unit-testing-with-an-active-record-based-framework,"['php', 'laravel']",1358,TRUE,4,3
unit testing in python - creating dataframes within tests,"<p>I am writing unit tests for methods - often manipulating DataFrames.</p>

<p>My data is coming from API calls and I have fallen into the trap of using the API calls within the tests - I feel like this does not accurately test the specific components as there could be a problem with the API call. </p>

<p>Would it be better practice to create a dummy dataframe in each test, and separately test that the API calls return DataFrames of the expected format? </p>

<p>It's a pain making DataFrames manually, is there a utility that can convert a DataFrame object in an active console into the code string required to build it?</p>
",https://stackoverflow.com/questions/46081529/unit-testing-in-python-creating-dataframes-within-tests,"['python-3.x', 'unit-testing', 'pandas']",530,TRUE,4,2
Unit testing and mocking a service with DI,"<p>I have been struggling with this for a while, and I'm hoping someone can help. I have a component that uses a service to get data. I am attempting to add unit tests to it. My problem is that the tests always fail with ""Error: No provider for Http"". Here is my code:</p>

<p>Service:</p>

<pre><code>import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';

import { Contact } from './contact.model';

@Injectable()
export class ContactsService {
    constructor(private http: Http) { }

    public getContacts(): Observable&lt;Array&lt;Contact&gt;&gt; {
        return this.http.get('assets/contacts.json').map(res =&gt; {
            let r = res.json().Contacts;
            return r;
        });
    }
}
</code></pre>

<p>Component:</p>

<pre><code>import { Component, OnInit, NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Contact } from '../contact.model'; 
import { ContactsService } from '../contacts.service';

@Component({
    selector: 'app-contacts',
    templateUrl: './contacts.component.html',
    styleUrls: ['./contacts.component.css'],
    providers: [ContactsService]
})
export class ContactsComponent implements OnInit {

    contactsAll: Array&lt;Contact&gt;;
    contacts: Array&lt;Contact&gt;;

    constructor(private contactsService: ContactsService) { }

    ngOnInit() {
        this.contactsService.getContacts().subscribe((x) =&gt; {
            this.contactsAll = x;
            this.contacts = this.contactsAll;
        });
    }
</code></pre>

<p>}</p>

<p>Tests:</p>

<pre><code>import { async, ComponentFixture, TestBed, inject } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { By } from '@angular/platform-browser';
import { Observable } from 'rxjs/Rx';

import { ContactsComponent } from './contacts.component';
import { ContactsService } from '../contacts.service';
import { Contact } from '../contact.model';

class MockContactsService extends ContactsService {

    constructor() {
        super(null);
    }

    testContacts: Array&lt;Contact&gt; = [
        new Contact(""test1 mock"", 12345, 10000),
        new Contact(""test2 mock"", 23456, 20000)
    ];

    public getContacts(): Observable&lt;Array&lt;Contact&gt;&gt; {
        return Observable.of(this.testContacts);
    }
}

describe('ContactsComponent', () =&gt; {
    let component: ContactsComponent;
    let fixture: ComponentFixture&lt;ContactsComponent&gt;;

    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            imports: [FormsModule],
            declarations: [ContactsComponent],
           // providers: [{ provide: ContactsService, useClass: MockContactsService }] // this is needed for the service mock
        }).overrideComponent(ContactsService, {// The following is to override the provider in the @Component(...) metadata
            set: {
                providers: [
                    { provide: ContactsService, useClass: MockContactsService },
                ]
            }
        }).compileComponents();
    }));

    beforeEach(() =&gt; {
        fixture = TestBed.createComponent(ContactsComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create', () =&gt; {
        expect(component).toBeTruthy();
    });

    describe('1st test', () =&gt; {
        it('true is true', () =&gt; expect(true).toBe(true));
    })
});
</code></pre>
",https://stackoverflow.com/questions/43549861/unit-testing-and-mocking-a-service-with-di,"['unit-testing', 'angular', 'dependency-injection', 'karma-jasmine']",5122,TRUE,5,3
Unit testing a method that takes a ResultSet as parameter,"<p>How does one go about unit testing an object that can't be instantiated? Because currently I have a method that converts a ResultSet to an object but I'm unsure if this violates any programming principles.</p>

<pre><code>public CItem convert(ResultSet rs) {
    CItem ci = new CItem ();

    try {
        ci.setHinumber(rs.getString(""id""));
        ci.setHostname(rs.getString(""sysname""));
        ci.setOs(rs.getString(""zos""));
        ci.setTenant(rs.getString(""customer_name""));
        //ci.setInstallation(rs.getField(""installation_name""));
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return ci;
}
</code></pre>

<p>Do I need to look for a different way to approach this solely because it can't be unit tested? Or can I somehow fake a ResultSet object.</p>

<p>Any help would be appreciated.</p>
",https://stackoverflow.com/questions/41856442/unit-testing-a-method-that-takes-a-resultset-as-parameter,"['java', 'unit-testing', 'junit', 'resultset']",23573,TRUE,17,2
Angular 2 - Unit testing service with Window dependency,"<p>I'm trying to test a service in Angular2. In the service, I'm using window.location and window.location.hash several times. After reading some other questions on Stackoverflow, I've decided to inject window in the service rather than using the global window directly.</p>

<pre><code>@Injectable()
export class AuthService {
    constructor(private router: Router, private window: Window) { }
}
</code></pre>

<p>For that I've registered window in <code>app.module.ts</code>:</p>

<pre><code>providers: [
           AuthService,
           {
               provide: Window,
               useValue: window
           },
           OtherService
 ]
</code></pre>

<p>Now in my test, I'm trying to mock window in a similar way to this answer: <a href=""https://stackoverflow.com/a/37176904"">https://stackoverflow.com/a/37176904</a></p>

<pre><code>beforeEach(() =&gt; {
routerStub = {
  navigate: jasmine.createSpy('navigate')
};
mockWindow = &lt;any&gt; { location: &lt;any&gt; {hash: 'testhash'}};
TestBed.configureTestingModule({
  providers: [
    AuthService,
    { provide: Router, useValue: routerStub },
    { provide: Window, useValue: mockWindow }
  ]
});

authService = TestBed.get(AuthService);
});
</code></pre>

<p>The error I get is the following: 'Error: Can't resolve all parameters for AuthService: ([object Object], ?)'</p>

<p>So while injecting a mock router works perfectly fine, injecting a mock window doesn't seem to work. Can anyone help me with this? Is there anything I'm doing wrong? I haven't been able to find a solution that works for me.</p>
",https://stackoverflow.com/questions/44780428/angular-2-unit-testing-service-with-window-dependency,"['angular', 'unit-testing', 'dependency-injection', 'karma-jasmine']",3116,TRUE,4,1
CATCH unit testing for C++ compare std::array,"<p>I like to use <a href=""https://github.com/philsquared/Catch"" rel=""nofollow noreferrer"">catch</a> for my c++ unit tests.
My goal is to compare <code>std::array</code> and <code>std::vector</code>.  I created the this failing example. </p>

<pre><code>#define CATCH_CONFIG_MAIN
#include ""catch.hpp""

TEST_CASE(""Vector"") {
    std::vector&lt;double&gt; direction = {0.1, 0.3, 0.4};
    std::vector&lt;double&gt; false_direction = {0.1, 0.0, 0.4};
    REQUIRE(direction == false_direction);
}

TEST_CASE(""Array"") {
    std::array&lt;double, 3&gt; direction = {0.1, 0.3, 0.4};
    std::array&lt;double, 3&gt; false_direction = {0.1, 0.0, 0.4};
    REQUIRE(direction == false_direction);
}
</code></pre>

<p>The output of this test is for the check of <code>std::vector</code></p>

<p>REQUIRE( direction == false_direction )
with expansion:
  <strong>{ 0.1, 0.3, 0.4 } == { 0.1, 0.0, 0.4 }</strong></p>

<p>and for <code>std::array</code></p>

<p>REQUIRE( direction == false_direction )
with expansion:
  <strong>{?} == {?}</strong></p>

<p>What can I do to display the actual and expected value? I like to have the very same display in a violated <code>REQUIRE</code> condition for <code>std::array</code> as for <code>std::vector</code>.</p>

<p>I use the latest version of catch (v1.10.0).</p>
",https://stackoverflow.com/questions/46788722/catch-unit-testing-for-c-compare-stdarray,"['c++', 'unit-testing', 'stdvector', 'stdarray', 'catch-unit-test']",3376,TRUE,4,3
Unit Testing Angular 1.5 component that requires ngModel,"<p>To test angular 1.5 components, the docs recommend you use ngMock's $componentController instead of using $compile if you don't need to test any of the DOM.</p>

<p>However, my component uses ngModel which I need to pass into the <code>locals</code> for $componentController, but there is no way to programmatically get the ngModelController; the only way to test it is to actually $compile an element with it on it, as this issue is still open: <a href=""https://github.com/angular/angular.js/issues/7720"" rel=""nofollow noreferrer"">https://github.com/angular/angular.js/issues/7720</a>.</p>

<p>Is there any way to test my components controller without resorting to $compiling it? I also don't want to have to mock the ngModelController myself as its behavior is somewhat extensive and if my tests rely on a fake one rather than the real thing there is a chance newer versions of Angular could break it (though that probably isn't an issue given Angular 1 is being phased out).</p>
",https://stackoverflow.com/questions/43005861/unit-testing-angular-1-5-component-that-requires-ngmodel,"['javascript', 'angularjs', 'unit-testing']",680,TRUE,4,1
Unit Testing Custom Password Validators in ASP.NET Core,"<p>I have a CustomPasswordValidator.cs file that overrides PasswordValidator</p>

<pre><code> public class CustomPasswordValidator : PasswordValidator&lt;AppUser&gt;
    {   //override the PasswordValidator functionality with the custom definitions
        public override async Task&lt;IdentityResult&gt; ValidateAsync(UserManager&lt;AppUser&gt; manager, AppUser user, string password)
        {
            IdentityResult result = await base.ValidateAsync(manager, user, password);

            List&lt;IdentityError&gt; errors = result.Succeeded ? new List&lt;IdentityError&gt;() : result.Errors.ToList();

            //check that the username is not in the password
            if (password.ToLower().Contains(user.UserName.ToLower()))
            {
                errors.Add(new IdentityError
                {
                    Code = ""PasswordContainsUserName"",
                    Description = ""Password cannot contain username""
                });
            }

            //check that the password doesn't contain '12345'
            if (password.Contains(""12345""))
            {
                errors.Add(new IdentityError
                {
                    Code = ""PasswordContainsSequence"",
                    Description = ""Password cannot contain numeric sequence""
                });
            }
            //return Task.FromResult(errors.Count == 0 ? IdentityResult.Success : IdentityResult.Failed(errors.ToArray()));
            return errors.Count == 0 ? IdentityResult.Success : IdentityResult.Failed(errors.ToArray());
        }
    }
</code></pre>

<p>I am new to using Moq and xUnit. I am trying to create a unit test to ensure that the correct number of errors are produced (showing working code, with code that produced errors in comments):</p>

<pre><code>//test the ability to validate new passwords with Infrastructure/CustomPasswordValidator.cs 
        [Fact]
        public async void Validate_Password()
        {
            //Arrange
            &lt;Mock&gt;&lt;UserManager&lt;AppUser&gt;&gt; userManager = new &lt;Mock&gt;&lt;UserManager&lt;AppUser&gt;&gt;(); //caused null exception, use GetMockUserManager() instead
            &lt;Mock&gt;&lt;CustomPasswordValidator&gt; customVal = new &lt;Mock&gt;&lt;CustomPasswordValidator&gt;(); //caused null result object use customVal = new &lt;CustomPasswordValidator&gt;() instead
            &lt;AppUser&gt; user = new &lt;AppUser&gt;
            user.Name = ""user"" 
            //set the test password to get flagged by the custom validator
            string testPwd = ""Thi$user12345"";

            //Act
            //try to validate the user password
            IdentityResult result = await customVal.ValidateAsync(userManager, user, testPwd);

            //Assert
            //demonstrate that there are two errors present
            List&lt;IdentityError&gt; errors = result.Succeeded ? new List&lt;IdentityError&gt;() : result.Errors.ToList();
            Assert.Equal(errors.Count, 2);
        }

//create a mock UserManager class
        private Mock&lt;UserManager&lt;AppUser&gt;&gt; GetMockUserManager()
        {
            var userStoreMock = new Mock&lt;IUserStore&lt;AppUser&gt;&gt;();
            return new Mock&lt;UserManager&lt;AppUser&gt;&gt;(
                userStoreMock.Object, null, null, null, null, null, null, null, null);
        }
</code></pre>

<p>The error occurs on the IdentityResult line, indicating that I cannot convert a Mock to UserManager and cannot convert Mock to AppUser class.</p>

<p>EDIT: changed to include GetMockUserManager() needed to mock a UserManagerClass in ASP.NET core (<a href=""https://stackoverflow.com/questions/21194324/mocking-new-microsoft-entity-framework-identity-usermanager-and-rolemanager"">Mocking new Microsoft Entity Framework Identity UserManager and RoleManager</a>)</p>
",https://stackoverflow.com/questions/47984050/unit-testing-custom-password-validators-in-asp-net-core,"['c#', 'asp.net', 'unit-testing', 'asp.net-core', 'moq']",1921,TRUE,4,1
Unit testing http handlers in golang mocking dependencies,"<p>At the moment I try to establish best practices for unit testing go handlers.
I need to mock dependencies, but therefore I have to be able to access / mock these dependencies.</p>

<p>There I some solutions I do not want to consider like for example global variables / application state. Or having all handlers as functions of a struct holding the dependencies member variables.</p>

<p>I was kind of satisfied with a solution where I injected the needed dependencies of a handler in the following way:</p>



<pre class=""lang-golang prettyprint-override""><code>func helloHandler(db *DbService) http.HandlerFunc {
  return func(w http.ResponseWriter, r *httpRequest) {
    // handler code goes here
  }
}
</code></pre>

<p>Then I am able to provide this handler for routing:</p>

<pre class=""lang-golang prettyprint-override""><code>http.HandleFunc(""/hello"", helloHander(myDbService))
</code></pre>

<p>I can also test it easily:</p>

<pre class=""lang-golang prettyprint-override""><code>helloHandler(myDbService)(req, respRecorder)
</code></pre>

<p>But when I use for example gorilla mux (what I haven't considered from the beginning) I get another problem.</p>

<p>Gorilla/mux adds extra semantics like filtering by Method (GET / POST), providing path parameters etc.</p>

<p>So I should need to test the resulting gorilla router.
But then I am again not able to inject my mock dependencies anymore.</p>

<p>When I get the router back everything (dependencies) is already set up.</p>

<p>But I also don't want to rebuild my Router in my tests because of DRY!</p>

<p>So for now I don't really have a good solution for the problem of conveniently setting up my routes but also being able to mock the dependencies.</p>

<p>Any idea?</p>
",https://stackoverflow.com/questions/44249410/unit-testing-http-handlers-in-golang-mocking-dependencies,"['unit-testing', 'go', 'dependency-injection']",3116,TRUE,4,1
setUp/tearDown fixtures when unit testing in Laravel,"<p>I'm trying to write a unit test that checks attribute method that uses <code>base_path()</code> helper, however, I'm getting an exception: <code>Call to undefined method Illuminate\Container\Container::basePath()</code>.</p>

<p>The full stacktrace is below:</p>

<pre><code>\vendor\laravel\framework\src\Illuminate\Foundation\helpers.php:179
\app\Message.php:47
\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasAttributes.php:432
\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasAttributes.php:333
\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasAttributes.php:306
\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php:1279
\tests\Unit\MessageTest.php:59
</code></pre>

<p>I've tracked it down to using <code>setUp</code> and <code>tearDown</code> fixtures - even if I've got:</p>

<pre><code>public function setUp()
{
    //$_SERVER['DOCUMENT_ROOT'] = dirname(__FILE__) . ""/../.."";
}

public function tearDown()
{
    //unset($_SERVER['DOCUMENT_ROOT']);
}
</code></pre>

<p>I'm getting the abovementioned error. If I remove the fixtures entirely, the error goes away.</p>

<p>After I've replaced the given methods with <code>setUpBeforeClass</code> and <code>tearDownAfterClass</code> the error goes away, but I'd like to know what is causing it.</p>

<p>As far as I'm aware of this is vanilla Laravel 5.4 installation (5.4.36 exactly), but it has additional libraries installed (and I'm not really able to say what libraries). I've not setup the <code>phpunit.xml</code> file, but to be fair I'd not know what to look for.</p>

<p>I've tested it with fresh installation of Laravel (same version) and it does happen straight out of the box (with untouched phpunit.xml file); on version 5.5 it doesn't.</p>
",https://stackoverflow.com/questions/46973932/setup-teardown-fixtures-when-unit-testing-in-laravel,"['laravel', 'unit-testing', 'phpunit', 'laravel-5.4']",9862,TRUE,3,2
Mockmvc unit testing with String[] as request body,"<p>I'm trying to create a unit test for the PUT api, as seen below, with a String[] as the request body.</p>

<pre><code>@RequestMapping(value = ""/test/id"", method = RequestMethod.PUT)
public ResponseEntity&lt;?&gt; updateStatus(@RequestBody String[] IdList,.........){
}
</code></pre>

<p>and my test is shown below</p>

<pre><code>@Test
public void updateStatus() throws Exception {
    when(serviceFactory.getService()).thenReturn(service);        
    mockMvc.perform(put(baseUrl + ""/test/id)
        .param(""IdList"",new String[]{""1""}))
        .andExpect(status().isOk());

}
</code></pre>

<p>The test is failing with this exception:</p>

<pre><code>java.lang.AssertionError: Status expected:&lt;200&gt; but was:&lt;400&gt;
</code></pre>

<p>What could be the best way to pass a string array param from mockmvc?</p>
",https://stackoverflow.com/questions/46306792/mockmvc-unit-testing-with-string-as-request-body,"['spring-boot', 'mockmvc']",3370,TRUE,3,1
Unit Testing events in karma angular 2 application,"<p>I'm trying to unit test the method abc(Event) using karma. I have a dropdown in my view page which has 4 options  which up on change will trigger abc(Event) method.</p>

<p>Here is my view page:</p>

<pre><code>&lt;div class=""myClass""&gt;
&lt;select (change)=""abc($event)"" id=""my""&gt;
    &lt;option value=""one""&gt;One&lt;/option&gt;
    &lt;option value=""two""&gt;Two&lt;/option&gt;
    &lt;option value=""three""&gt;Three&lt;/option&gt;
    &lt;option value=""four""&gt;Four&lt;/option&gt;
&lt;/select&gt;
</code></pre>

<p>
my component.ts file contains the definition of method abc.</p>

<pre><code>import {Component,OnInit} from '@angular/core';
import { LocaleService } from '../../../services/locale.service';
@Component({
selector: 'app-localeselector',
templateUrl: './localeselector.component.html',
styleUrls: ['./localeselector.component.scss']
})


export class LocaleselectorComponent implements OnInit{

 private localeService: any;
 private language;
 constructor() { }

 ngOnInit() { }

}

abc(ev: Event) {
    //something...
}
}
</code></pre>

<p>How can I test method abc? Also how to mock $event?
Thanks in advance.</p>
",https://stackoverflow.com/questions/44067775/unit-testing-events-in-karma-angular-2-application,"['angular', 'events', 'mocking', 'karma-jasmine']",1791,TRUE,3,1
unit testing with moq generic repository and UnitOfWork,"<p>I have a specific and generic repository like that :</p>

<p><strong>Generic repository:</strong> </p>

<pre><code>public class Repository&lt;TEntity&gt; : IRepository&lt;TEntity&gt; where TEntity : class
{
    protected readonly DbContext Context;
    private DbSet&lt;TEntity&gt; _entities;

    public Repository(DbContext context)
    {
        Context = context;
        _entities = Context.Set&lt;TEntity&gt;();
    }

    public IEnumerable&lt;TEntity&gt; Find(Expression&lt;Func&lt;TEntity, bool&gt;&gt; predicate)
    {
        return _entities.Where(predicate);
    }
}
</code></pre>

<p><strong>Specific Repository:</strong></p>

<pre><code>public class HolidayCalendarRepository : Repository&lt;HolidayCalendar&gt;, IHolidayCalendarRepository
{
    public HolidayCalendarRepository(ApplicationDbContext context)
        : base(context)
    {
    }

    public ApplicationDbContext ApplicationDbContext
    {
        get { return Context as ApplicationDbContext; }
    }

    public bool IsHoliday(DateTime date)
    {
        return Find(h =&gt; h.Date == date.Date).Any();
    }
}
</code></pre>

<p><strong><em>IRepository</em></strong></p>

<pre><code>public interface IRepository&lt;TEntity&gt; where TEntity : class
{       
    IEnumerable&lt;TEntity&gt; Find(Expression&lt;Func&lt;TEntity, bool&gt;&gt; predicate);
}
</code></pre>

<p><strong><em>IHolidayCalendarRepository</em></strong> </p>

<pre><code>public interface IHolidayCalendarRepository : IRepository&lt;HolidayCalendar&gt;
{
    bool IsHoliday(DateTime date);                     
}
</code></pre>

<p><strong>UnitOfWork</strong></p>

<pre><code>public class UnitOfWork : IUnitOfWork
{
    private readonly ApplicationDbContext _context;

    public UnitOfWork(ApplicationDbContext context)
    {
        _context = context;          
        HolidayCalendars = new HolidayCalendarRepository(_context);
    }

    public IHolidayCalendarRepository HolidayCalendars { get; private set; }

    public int Complete()
    {
        return _context.SaveChanges();
    }

    public void Dispose()
    {
        _context.Dispose();
    }
}
</code></pre>

<p>How to test the method <em>IsHoliday(DateTime date)</em> on my respository.
I'm beginner on unit test. this is what i try but it's not working.</p>

<pre><code>[TestFixture]
public class HolidayCalendarRepositoryTests
{
    private HolidayCalendarRepository _holidayCalendarRepository;
    private Mock&lt;DbSet&lt;HolidayCalendar&gt;&gt; _mockHolidayCalendar;

    [SetUp]
    public void TestInitialize()
    {          
        var mockContext = new Mock&lt;ApplicationDbContext&gt;();
        _mockHolidayCalendar = new Mock&lt;DbSet&lt;HolidayCalendar&gt;&gt;();


        mockContext.Setup(hc =&gt; hc.HolidayCalendar).Returns(_mockHolidayCalendar.Object);
        _holidayCalendarRepository = new HolidayCalendarRepository(mockContext.Object);

    }

    [Test]
    public void IsHoliday_CurrentDateIsHoliday_ShouldBeTrue()
    {
        var holidays = new List&lt;HolidayCalendar&gt;() { new HolidayCalendar { ID = 1, Date = DateTime.Today } };

        _mockHolidayCalendar.SetSource(holidays);

        var result = _holidayCalendarRepository.IsHoliday(DateTime.Today);

        Assert.IsTrue(result);
    }
}
</code></pre>

<p><em>SetSource methode</em></p>

<pre><code>    public static void SetSource&lt;T&gt;(this Mock&lt;DbSet&lt;T&gt;&gt; mockSet, IList&lt;T&gt; source) where T : class
    {
        var data = source.AsQueryable();

        mockSet.As&lt;IQueryable&lt;T&gt;&gt;().Setup(m =&gt; m.Provider).Returns(data.Provider);
        mockSet.As&lt;IQueryable&lt;T&gt;&gt;().Setup(m =&gt; m.Expression).Returns(data.Expression);
        mockSet.As&lt;IQueryable&lt;T&gt;&gt;().Setup(m =&gt; m.ElementType).Returns(data.ElementType);
        mockSet.As&lt;IQueryable&lt;T&gt;&gt;().Setup(m =&gt; m.GetEnumerator()).Returns(data.GetEnumerator());
    }
</code></pre>
",https://stackoverflow.com/questions/44099573/unit-testing-with-moq-generic-repository-and-unitofwork,"['c#', 'moq', 'repository-pattern', 'unit-of-work', 'nunit-3.0']",1517,TRUE,3,1
HTTP post request unit testing in Angular 4,"<p>THIS TEST IS WORKING NOW</p>

<p>I would like to test an HTTP request in Angular 2, but it is not working.
Here is the error message:
    <code>ERROR in .../loginservice.service.spec.ts (45,11): ';' expected.</code>
    <code>ERROR in .../loginservice.service.spec.ts (45,12): ')' expected.</code></p>

<p>and here is the code:
It is a post request, and it working properly. </p>

<pre><code>import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';  

@Injectable()
export class LoginService {

    constructor(private http: Http) { }

    postLoginDetails(loginDetails): Observable&lt;Comment[]&gt; {
        const endpoint = 'http://localhost:8080/api/login';
        const bodyString = loginDetails;
        const headers = new Headers({ 'Content-Type': 'application/json'});
        const options = new RequestOptions({headers: headers});

        return this.http.post(endpoint, bodyString, options)
            .map((res: Response) =&gt; res.json())
            .catch((error: any) =&gt;  Observable.throw(error.json().error || 'server error'));
    }
}
</code></pre>

<p>and here is the test for it:
This is the test for the post request. I used different articles to write it and perhaps that is why it is not working.</p>

<pre><code>import { TestBed, inject } from '@angular/core/testing';
import {
    HttpModule,
    Http,
    XHRBackend,
    ResponseOptions,
    Response,
    Headers
} from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';

import { LoginService } from './loginservice.service';

describe('LoginService', () =&gt; {

    beforeEach(() =&gt; {

        TestBed.configureTestingModule({
            imports: [HttpModule],
            providers: [
                LoginService,
                { provide: XHRBackend, useClass: MockBackend },
            ]
        });
    });

    describe('postLoginDetails()', () =&gt; {
        it('should return an Observable&lt;Comment[]&gt; with ok status', 
inject([LoginService, XHRBackend], (LoginService, MockBackend) =&gt; {
            const mockResponse = {
                    status: 'ok',
                    token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IlRlc3RBZG1pbiIsImFkbWluIjp0cnVlfQ.nhC1EDI5xLGM4yZL2VMZyvHcbcWiXM2RVS7Y8Pt0Zuk'
                }

            const loginDetails = {
                email: 'test@example.com',
                password: '1234'
                };
            MockBackend.connections.subscribe((connection) =&gt; {
                connection.mockRespond(new Response(new ResponseOptions({
                    body: JSON.stringify(mockResponse)
                })));
            });
            LoginService.postLoginDetails(loginDetails).subscribe((mockResponse) =&gt; {
                expect(mockResponse.status).toEqual('ok');
            });
        }));
    });
});
</code></pre>
",https://stackoverflow.com/questions/44654047/http-post-request-unit-testing-in-angular-4,"['javascript', 'angular', 'unit-testing', 'testing', 'karma-jasmine']",4018,TRUE,3,2
"Angular 2 rc5 , unit testing issue with services","<pre><code>@Injectable()
export class Service1 {
    constructor( private s2 : Service2 ) { 
        console.log( s2.name );
     }
}

@Injectable()
export class Service2 {
    public name: string = 'Hi';
}


//------------Test-------------

let service1: MockService1;  // MockService1 extends Service1
let service2: MockService2;  // MockService2 extends Service2

beforeEach(() =&gt; {
    TestBed.configureTestingModule({
        providers: [
            { provide: Service1, useClass: MockService1 },
            { provide: Service2, useClass: MockService2 }
        ]
    })
});  

beforeEach(inject( [ Service1 , Service2 ], ( s1: MokcService1 , s2: MockService2  ) =&gt; { 
    service1 = s1;
    service2 = s2; 
}));

it('should be defined ', () =&gt; {
    expect( service1 ).toBeDefined(); 
    expect( service2 ).toBeDefined();
});
</code></pre>

<p>I'm getting </p>

<p>TypeError: undefined is not an object (evaluating 's2.name')  </p>

<p>because Service2 is undefined.</p>

<p>The same code worked earlier with addProviders and provide  </p>

<pre><code>beforeEach(() =&gt; {
    addProviders([
        provide(Service1, {useClass: MockService1 } ),
        provide(Service2, {useClass: MockService2 } ),
    ]);
});         
</code></pre>

<p>Those 2 tests are passing when console.log( s2.name ) is removed</p>

<p>Any Idea?</p>
",https://stackoverflow.com/questions/41484380/angular-2-rc5-unit-testing-issue-with-services,"['angular', 'jasmine']",50,TRUE,3,1
Unit testing code that relies on keyboard interrupt,"<p>I want to test a part of the code that has an infinite loop and break out when a keyboard interrupt is issued. I am using watchdog module to watch for new files created in a directory.
Here is the relevant code : </p>

<pre><code>class EventHandler(PatternMatchingEventHandler):
    """"""
        Inherits from PatternMatchingEventHandler
        Calls on_create when a new file is added to the output
        folder
    """"""

    def process(self, event):
        """"""
            For debugging
        """"""
        return (event.src_path, event.event_type)

    def on_created(self, event):
        self.process(event)

class Watcher(object):
    """"""
        Waits for events in the directory being watched
    """"""

    def __init__(self, outpath):
        """"""
            Initialize a watcher object. outpath is the absolute path of
            the output csv folder usually provided by the config module
        """"""
        self.path = outpath

    def run(self):
        event_handler = EventHandler(ignore_directories=True, patterns=['*.csv'])
        observer = Observer()
        observer.schedule(event_handler, self.path)
        observer.start()
        try:
            while True:
                time.sleep(1)

        except KeyboardInterrupt:
            observer.stop()

        observer.join()
</code></pre>

<p>My testing code looks something like this : </p>

<pre><code>def test_watcher(self):
    """"""
        Test the watcher code
    """"""
    self.watcher.run()
    out_file = ""somefile.csv""
    with open(out_file, 'w+') as fname:
        fname.write('')

    # How to stop the watcher from code?

    self.assertTrue(""somefile.csv was created"")
</code></pre>

<p>I am using built-in unittest</p>
",https://stackoverflow.com/questions/46786290/unit-testing-code-that-relies-on-keyboard-interrupt,"['python', 'watchdog']",473,FALSE,3,0
Should we use Angular TestBed while unit testing?,"<p>Should we use Angular TestBed while unit testing? or is it reserved for E2E/Component testing?</p>
",https://stackoverflow.com/questions/47215273/should-we-use-angular-testbed-while-unit-testing,"['javascript', 'angular', 'typescript', 'jasmine', 'karma-runner']",1856,TRUE,3,1
Unit Testing with Moq sometimes fails on ToListAsync(),"<p>I'm fairly new to testing with moq and I'm having a strange issue (at least it seems strange to me), but I'm probably just not setting up the mock object correctly. I have a repository layer that uses EntityFrameworkCore to work with my DbContext. One particular function in the repository allows me to return a sorted list without exposing the Linq or EFCore functions to the service layer calling the function.</p>

<p>Say I have a Model class like this:</p>

<pre class=""lang-cs prettyprint-override""><code>public class SomeClass {
    public string Foo { get; set; }
}
</code></pre>

<p>and I have a DbSet in my DbContext called someClasses. The three functions in my repository that I'm using to sort someClasses are these:</p>

<pre class=""lang-cs prettyprint-override""><code>public async Task&lt;List&lt;SomeClass&gt;&gt; GetSomeClassesAsync(string orderBy = """", bool descending = false) {
    var returnVals = _context.someClasses.AsQueryable();

    returnVals = SortQueryableCollectionByProperty(returnVals, orderBy, descending);

    return await returnVals.ToListAsync();
}

private IQueryable&lt;T&gt; SortQueryableCollectionByProperty&lt;T&gt;(IQueryable&lt;T&gt; queryable, string propertyName, bool descending) where T : class {
    if (typeof(T).GetProperty(propertyName) != null) {
        if (descending) {
            queryable = queryable.OrderByDescending(q =&gt; GetPropertyValue(propertyName, q));
        } else {
            queryable = queryable.OrderBy(q =&gt; GetPropertyValue(propertyName, q));
        }
    }

    return queryable;
}

private object GetPropertyValue&lt;T&gt;(string propertyName, T obj) {
    return obj.GetType().GetProperty(propertyName).GetAccessors()[0].Invoke(obj, null);
}
</code></pre>

<p>So I have 2 unit tests for GetSomeClassesAsync(). The first unit test makes sure that the list returned is ordered by Foo, the second checks that an unordered list is returned when attempting to sort by Bar (a non-existent property). Here's how my tests are setup:</p>

<pre class=""lang-cs prettyprint-override""><code>private Mock&lt;DbContext&gt; mockContext;
private MyRepository repo;

[TestInitialize]
public void InitializeTestData() {
    mockContext = new Mock&lt;DbContext&gt;();

    repo = new MyRepository(mockContext.Object);
}

[TestMethod]
public async Task GetSomeClassesAsync_returns_ordered_list() {
    var data = new List&lt;SomeClass&gt; {
        new SomeClass { Foo = ""ZZZ"" },
        new SomeClass { Foo = ""AAA"" },
        new SomeClass { Foo = ""CCC"" }
    };
    var mockSomeClassDbSet = DbSetMocking.CreateMockSet(new TestAsyncEnumerable&lt;SomeClass&gt;(data));
    mockContext.Setup(m =&gt; m.someClasses).Returns(mockSomeClassDbSet.Object);

    var sortedResults = await repo.GetSomeClassesAsync(nameof(SomeClass.Foo));

    Assert.AreEqual(""AAA"", sortedResults[0].Foo);
    Assert.AreEqual(""CCC"", sortedResults[1].Foo);
    Assert.AreEqual(""ZZZ"", sortedResults[2].Foo);
}

[TestMethod]
public async Task GetSomeClassesAsync_returns_unordered_list() {
    var data = new List&lt;SomeClass&gt; {
        new SomeClass { Foo = ""ZZZ"" },
        new SomeClass { Foo = ""AAA"" },
        new SomeClass { Foo = ""CCC"" }
    };
    var mockSomeClassDbSet = DbSetMocking.CreateMockSet(new TestAsyncEnumerable&lt;SomeClass&gt;(data));
    mockContext.Setup(m =&gt; m.someClasses).Returns(mockSomeClassDbSet.Object);

    var unsortedResults = await repo.GetSomeClassesAsync(""Bar"");

    Assert.AreEqual(""ZZZ"", unsortedResults[0].Foo);
    Assert.AreEqual(""AAA"", unsortedResults[1].Foo);
    Assert.AreEqual(""CCC"", unsortedResults[2].Foo);
}
</code></pre>

<p>DbSetMocking.CreateMockSet() was taken from <a href=""http://codethug.com/2015/03/20/mocking-dbset/"" rel=""nofollow noreferrer"">here</a> and TestAsyncEnumerable was taken from <a href=""https://stackoverflow.com/questions/40476233/how-to-mock-an-async-repository-with-entity-framework-core/40491640#40491640"">here</a></p>

<p>What I'm stumped on is the first test that returns an ordered list passes. Everything works fine. The second test fails and I get this error message:</p>

<blockquote>
  <p>System.NotImplementedException: The method or operation is not implemented.</p>
</blockquote>

<p>This exception gets thrown when the code gets to ToListAsync(). What I don't get is why no error occurs when it goes through the work of sorting and then calling ToListAsync(), but when the sorting gets skipped and ToListAsync() is called, that exception is thrown. Am I not setting up my mock objects correctly?</p>
",https://stackoverflow.com/questions/47965574/unit-testing-with-moq-sometimes-fails-on-tolistasync,"['linq', 'unit-testing', 'asp.net-core', 'moq', 'entity-framework-core']",3285,TRUE,3,3
Unit-testing a Flux.take(Duration duration) with StepVerifier,"<p>I am using Spring Reactor Core 3.0.6 and I have a method returning a Flux:</p>

<pre><code>public Flux&lt;Foo&gt; createFlux(){
    return Flux.&lt;List&lt;Foo&gt;,String&gt;generate(/* generator omitted for clarity's sake */ )
        .take(Duration.ofSeconds(10)
        .flatMap(Flux::fromIterable);
}
</code></pre>

<p>The generator function calls a paginated REST api to get the results, and if the API continue to return data, I want the Flux to just run for 10 seconds.</p>

<p>It works fine, but I'd like to create some unit-testing and I have trouble in creating a test to verify that the Flux run only for 10 seconds at maximum. </p>

<p>I mocked the rest service so that it always return data and wrote this:</p>

<pre><code>StepVerifier.withVirtualTime(() -&gt; createFlux())
    .thenAwait(Duration.ofSeconds(10))
    .verifyComplete();
</code></pre>

<p>but it fails:</p>

<pre><code>java.lang.AssertionError: expectation ""expectComplete"" failed (expected: onComplete(); actual: onNext([my toString() Foo bean]))
</code></pre>

<p>I guess that I should consume the generated items in some way, but I am unable to find the right StepVerifier method to do so.</p>

<p><strong>EDIT</strong></p>

<p>I try to skip every items with <code>thenConsumeWhile</code>:</p>

<pre><code>StepVerifier.withVirtualTime(() -&gt; createFlux())
    .thenAwait(Duration.ofSeconds(10))
    .thenConsumeWhile(t -&gt; true)
    .verifyComplete();
</code></pre>

<p>but now the test just runs indefinitely and never ends.</p>
",https://stackoverflow.com/questions/44657525/unit-testing-a-flux-takeduration-duration-with-stepverifier,"['java', 'spring', 'unit-testing', 'project-reactor']",3171,TRUE,3,2
Unit testing in Django with flexible url patterns,"<p>I was using the following test to check whether page resolves to correct template: </p>

<pre><code>from django.test import TestCase
class HomePageTest(TestCase):
    def test_landing_page_returns_correct_html(self):
        response = self.client.get('/')
        self.assertIn(member='Go to the', container=response.content.decode())

    def test_uses_test_home_template(self):
        response = self.client.get('/test/')
        self.assertTemplateUsed(response=response,
                                template_name='myapp/home.html')
</code></pre>

<p>I used many variations of <code>self.client.get('/test/')</code> or <code>self.client.get('/test/dashboard/')</code> etc. in many many tests. All of which are in my <code>myapp.urlpatterns</code>. </p>

<p>Then one day I decided to get rid of <code>/test/</code>. Or simply change the URL pattern. All of the tests failed because, well, I hardcoded the URLs. </p>

<p>I would like to use flexible URL's in my tests. I assume it involves something like: </p>

<pre><code>from myapp.urls import urlpatterns as myapp_urls
</code></pre>

<p>and using <code>myapp_urls</code> throughout the tests.</p>

<p>I have two questions:</p>

<ol>
<li>How can I implement it? </li>
<li>Will there be any (negative) side effects of this approach that I don't foresee?</li>
</ol>
",https://stackoverflow.com/questions/46593222/unit-testing-in-django-with-flexible-url-patterns,"['django', 'unit-testing', 'django-urls', 'dry', 'django-tests']",838,TRUE,3,1
Unit testing select element&#39;s `onChange` function with Enzyme,"<p>I have a dropdown component in React that renders a select element with some options. Here is what my test looks like:</p>

<pre><code>import React from 'react';
import { shallow, mount } from 'enzyme';
import expect from 'expect';
import Dropdown from './Dropdown';

fdescribe('Dropdown', () =&gt; {
  it('should trigger onChange', () =&gt; {
    const handleChange = jasmine.createSpy('handleChange');
    const dropdown = mount(
      &lt;div&gt;
        &lt;Dropdown
          options={[
            { key: '', display: 'Please select a value' },
            { key: 'NJ', display: 'New Jersey' },
            { key: 'NY', display: 'New York' },
          ]}
          onChange={handleChange}
        /&gt;
      &lt;/div&gt;,
     );
    dropdown.find('select').simulate('change', { target: { value: 'New Jersey' } });
    expect(handleChange).toHaveBeenCalled();
  });
});
</code></pre>

<p>I get the following error in the console: <code>The ""actual"" argument in expect(actual).toHaveBeenCalled() must be a spy</code></p>

<p>Any ideas on how to test the <code>onchange()</code> on the dropdown? Thanks!</p>
",https://stackoverflow.com/questions/45217049/unit-testing-select-elements-onchange-function-with-enzyme,"['javascript', 'unit-testing', 'reactjs', 'testing', 'enzyme']",1050,TRUE,2,1
Unit testing singleton without using PowerMock or PowerMockito,"<p>I am writing unit tests (using JUnit and Mockito) for a singleton Java class. I cannot change the class implementation itself.</p>

<p>With PowerMockito, it was like this (and works):</p>

<pre><code>@Mock
    private TheSingleton theSingleton;

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

        PowerMockito.mockStatic( TheSingleton.class );
        when( TheSingleton.getInstance() ).thenReturn( theSingleton );
        ...
    }
</code></pre>

<p>The ask is to rewrite the test <strong><em>without</em></strong> using PowerMock or PowerMockito or any other static mocking API. Since I cannot change the singleton class to instead use dependency injection, I am not sure what would be a good way of doing this.</p>

<p>Any help will be greatly appreciated.</p>
",https://stackoverflow.com/questions/47321041/unit-testing-singleton-without-using-powermock-or-powermockito,"['java', 'unit-testing', 'singleton', 'mockito', 'powermock']",448,TRUE,2,2
Unit testing methods using Principal from Spring Secucrity,"<p>Could someone tell me how should I test those two methods:</p>

<pre><code>public boolean deleteUser(Principal principal) {
    if (findLoggedInUser(principal) != null) {
        userRepository.delete(findLoggedInUser(principal));
        return true;
    }
    return false;
}

public User findLoggedInUser(Principal principal) {
    return findUserbyUsername(principal.getName());
}
</code></pre>

<p>The problem is that I'm using currently logged in user with basic authentication and don't know how, and if I can mock those Principals. Is there a way to do that? Those methods are in my Service layer so maybe I can't do unit tests and I'm left with integration tests because those methods heavily use DB?</p>

<p>EDIT 1:
<strong>My changed test class:</strong></p>

<pre><code>public class UserServiceBeanTest {

@Spy
@InjectMocks
private UserServiceBean userServiceBean;

@Mock
private UserRepository userRepository;

@Mock
private Principal principal;

@Mock
private PasswordEncoder passwordEncoder;

@Mock
private User userStub;

private String defaultName = ""user"";
private  String defaultPassword = ""password"";
private String defaultEmail = ""example@example.com"";

@Before
public void init() {
    MockitoAnnotations.initMocks(this);
}


@Test
public void shouldReturnTrue_whenUserDeleted() {
    //given
    when(principal.getName()).thenReturn(defaultName);
    when(userServiceBean.findLoggedInUser(principal)).thenReturn(userStub);

    // when
    boolean removed = userServiceBean.deleteUser(principal);

    //then
    assertTrue(removed);
    verify(userRepository, times(1));
}

@Test
public void shouldReturnFalse_whenUserNotFound() {
    //given
    when(principal.getName()).thenReturn(defaultName);
    when(userServiceBean.findLoggedInUser(principal)).thenReturn(null);

    //when
    boolean removed = userServiceBean.deleteUser(principal);

    //then
    assertFalse(removed);
    verify(userRepository, times(0));
}

}
</code></pre>

<p>I'm getting those errors now:</p>

<pre><code>org.mockito.exceptions.misusing.UnfinishedVerificationException: 
</code></pre>

<p>Missin</p>

<pre><code>g method call for verify(mock) here:
-&gt; at com.doublemc.services.UserServiceBeanTest.shouldReturnTrue_whenUserDeleted(UserServiceBeanTest.java:63)

Example of correct verification:
    verify(mock).doSomething()

Also, this error might show up because you verify either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.


    at com.doublemc.services.UserServiceBeanTest.init(UserServiceBeanTest.java:48)
</code></pre>

<p>EDIT 2:
<strong>Here is my UserServiceBean class:</strong></p>

<pre><code>package com.doublemc.services;

import com.doublemc.domain.ToDoItem;
import com.doublemc.domain.User;
import com.doublemc.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.security.Principal;

@Service
@Transactional
public class UserServiceBean {

private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;

@Autowired
UserServiceBean(UserRepository userRepository, PasswordEncoder passwordEncoder) {
    this.userRepository = userRepository;
    this.passwordEncoder = passwordEncoder;
}

public User saveUser(User user) {
    User newUser = new User();
    newUser.setUsername(user.getUsername());
    newUser.setEmail(user.getEmail());
    newUser.setPassword(passwordEncoder.encode(user.getPassword()));
    return userRepository.save(newUser);
}

public boolean userExists(User user) {
    return userRepository.findByUsername(user.getUsername()) != null;
}

public Iterable&lt;ToDoItem&gt; getAllToDoItems(User user) {
    return user.getToDoItems();
}

public boolean deleteUser(Principal principal) {
    if (findLoggedInUser(principal) != null) {
        userRepository.delete(findLoggedInUser(principal));
        return true;
    }
    return false;
}

public User findLoggedInUser(Principal principal) {
    return userRepository.findByUsername(principal.getName());
}
</code></pre>

<p>}</p>

<p><strong>Here is my UserRepository:</strong></p>

<pre><code>public interface UserRepository extends CrudRepository&lt;User, Long&gt; {
User findByUsername(String username);
}
</code></pre>

<p>EDIT 6: I created myself three more tests:</p>

<pre><code>@Test
public void shouldReturnUser_whenPassedUser() {
    // given
    when(userRepository.save(any(User.class))).thenReturn(new User(defaultName, defaultPassword, defaultEmail));

    // when
    User savedUser = userServiceBean.saveUser(userStub);

    // then
    assertNotNull(savedUser);
    verify(userRepository, times(1)).save(any(User.class));
}

@Test
public void shouldReturnTrue_whenUserExists() {
    // given
    when(userStub.getUsername()).thenReturn(defaultName);
    when(userRepository.findByUsername(userStub.getUsername())).thenReturn(userStub);

    // when
    boolean exists = userServiceBean.userExists(userStub);

    // then
    assertTrue(exists);
    verify(userRepository, times(1)).findByUsername(defaultName);
}

@Test
public void shouldReturnFalse_whenUserNotFoundByUsername() {
    // given
    when(userStub.getUsername()).thenReturn(defaultName);
    when(userRepository.findByUsername(userStub.getUsername())).thenReturn(null);

    // when
    boolean exists = userServiceBean.userExists(userStub);

    // then
    assertFalse(exists);
    verify(userRepository, times(1)).findByUsername(defaultName);
}
</code></pre>

<p>And here are tested methods:
<strong>UserServiceBean.saveUser</strong>:</p>

<pre><code>public User saveUser(User user) {
    User newUser = new User(user.getUsername(), user.getEmail(), passwordEncoder.encode(user.getPassword()));
    return userRepository.save(newUser);
}
</code></pre>

<p><strong>UserServiceBean.userExists</strong>:</p>

<pre><code>public boolean userExists(User user) {
    return userRepository.findByUsername(user.getUsername()) != null;
}
</code></pre>
",https://stackoverflow.com/questions/42148257/unit-testing-methods-using-principal-from-spring-secucrity,"['java', 'spring', 'unit-testing', 'spring-security', 'mockito']",6424,TRUE,2,1
Test folder structure for angular 4 unit testing,"<p>I am using angular-cli for my app, In my unit testing i have 4 different type of files.</p>

<ol>
<li><p>file which contains all the test</p></li>
<li><p>test helpers </p></li>
<li><p>TestHostComponent to test components with input and output</p></li>
<li><p>stubs for services</p></li>
</ol>

<p>Which extensions i should use for above files(like <em>.spec.ts,</em>.test.ts, *.stub.ts). And should i create a different module to declare my TestHostComponent as it gives error when not declared in any module.
I tried to exclude all these files by adding them to tsconfig.app.json, but still these files were compiled during build, how can i exclude them?   </p>
",https://stackoverflow.com/questions/47028458/test-folder-structure-for-angular-4-unit-testing,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",628,FALSE,2,0
Unit testing for POST request using Mockido error,"<p>The status I expect when testing is 200, but I get 404 instead right now.</p>

<p>I am fairly new to Mockido, so if there is something simple that I am missing.  Please let me know.</p>

<p>I have created a POST request in my controller that takes a List of Long objects.  If no exception happens, returns OK for status:</p>

<pre><code>@PostMapping(path = ""/postlist"")
public ResponseEntity&lt;Void&gt; updateAllInList(@RequestBody List&lt;Long&gt; ids) {
    try {
        // method from ControllerService.java here using ids 
        return ResponseEntity.status(HttpStatus.OK).body(null);
    } catch (InvalidContentException e) {
        return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(null);
    }
</code></pre>

<p>When I POST using a REST client, I am getting the correct results.  The raw payloads I POST are like this:</p>

<pre><code>[
     2, 1
]
</code></pre>

<p>However, the unit test is giving me a 404.</p>

<p>The way I created the Test class is like this:</p>

<pre><code>    @RunWith(SpringJUnit4ClassRunner.class)
    @WebAppConfiguration
    @ContextHierarchy({ @ContextConfiguration(classes = RootConfiguration.class), @ContextConfiguration(classes = WebConfiguration.class) })
    @Category(UnitTest.class)
    public class ControllerTest {

         private static final String POST_REQUEST = ""[ 2, 1 ]"";

         @Autowired private WebApplicationContext webApplicationContext;
         @Autowired private ControllerService controllerService;

         private MockMvc mockMvc;


         @Before
         public void setUp() throws Exception {

              this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();

              doNothing().when(this.controllerService).updateAllInList(anyList());
             doThrow(InvalidContentException.class).when(this.controllerService).updateAllInList(null);
        }

        @Test
        public void updateList() throws Exception {
            this.mockMvc.perform(post(""http://testhost/api/configuration/postlist"").contentType(MediaType.APPLICATION_JSON_UTF8).content(POST_REQUEST))
                    .andExpect(status().isOk());
        }


        @Configuration
        static class RootConfiguration {


            @Bean
            public ControllerService ControllerService() {
                return Mockito.mock(ControllerService.class);
            }
        }


        @Configuration
        @EnableWebMvc
        static class WebConfiguration extends WebMvcConfigurerAdapter {

             @Autowired
             private ControllerService controllerService;


             @Bean
             public Controller controller() {
                  return new Controller(controllerService);
             }
         }
    }
</code></pre>

<p>My theory is that in my test class I am plugging in the wrong content.  But why can't we plug in the same content as the one we use from real POST raw payload?</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/44597754/unit-testing-for-post-request-using-mockido-error,"['java', 'spring', 'unit-testing', 'jpa', 'mockito']",905,FALSE,2,1
SQL Server Database Unit Testing and Continuous Integration,"<p>I have a suite of SQL Server Database Unit Tests built in Visual Studio 2013 to test stored procedures and functions. The tests run fine against my local database but I also want them to be run against a DEV server's DB as part of a CI process.</p>

<p>To achieve this I am building the test DLL and copying both the DLL and config file to the DEV server and then running the command line vstest.console.exe to test.  This works fine on my local machine but when I try to run it on DEV I get the following exception for each test:</p>

<blockquote>
  <p>An error occurred while SQL Server unit testing settings were being read from the configuration file. Click the test project, open the SQL Server Test Configuration dialog box from the SQL menu, add the settings to the dialog box, and rebuild the project.</p>
</blockquote>

<p>I have tried using slow cheetah to ensure that an App.Config transform is applied before the solution is built and I can see that the transform is being applied in the config file, but still my tests fail.</p>

<p>Has anyone figured out a way to do this? It seems strange that the DLL has to be rebuilt to consume connection string changes in a config file.</p>

<p>I also tried following the suggestions in this <a href=""http://sqlblogcasts.com/blogs/sqlandthelike/archive/2013/01/07/ssdt-tsql-unit-testing-in-multiple-environments.aspx"" rel=""nofollow noreferrer"">post</a> but without success.</p>
",https://stackoverflow.com/questions/42105033/sql-server-database-unit-testing-and-continuous-integration,"['c#', 'sql-server', 'visual-studio', 'unit-testing', 'sql-server-data-tools']",1088,TRUE,3,2
Creating object with dummy values for unit testing,"<p>I am unit testing native c++ code with Visual studio 2013.</p>

<p>To unit test a method that gets a large data input as object, is there any tool available to create the object with dummy values for the fields in the class?  </p>

<p>I checked <a href=""https://github.com/google/googlemock"" rel=""nofollow noreferrer"">Google Mock</a> which checks if a method is getting called, in which order methods are getting called, how many times a method is getting called, etc., But I haven't found any package or tool that helps to create object with dummy values to the fields.</p>
",https://stackoverflow.com/questions/46579665/creating-object-with-dummy-values-for-unit-testing,"['c++', 'unit-testing', 'visual-c++', 'visual-studio-2013']",271,FALSE,3,0
Unit testing and mocking mySQL database in Node.js,"<p>In my Node.js API I'm connecting to a mySQL database using <a href=""https://www.npmjs.com/package/promise-mysql"" rel=""nofollow noreferrer"">promise-mysql</a>. I'm using <a href=""https://www.npmjs.com/package/sequelize"" rel=""nofollow noreferrer"">Sequelize</a> as ORM. I want to unit test each micro service interacting with the database.</p>

<p>Obviously during the tests, I don't want to create a real database connection since unit tests should not rely on dependencies like database connections. Rather I want to mock it, using either an in-memory or on-disc database like <a href=""https://www.npmjs.com/package/sqlite3"" rel=""nofollow noreferrer"">sqlite3</a>.</p>

<p>I've tried migrating the SQL dump to <a href=""https://www.npmjs.com/package/sqlite3"" rel=""nofollow noreferrer"">sqlite3</a> but I get errors since the dump is not compatible with <a href=""https://www.npmjs.com/package/sqlite3"" rel=""nofollow noreferrer"">sqlite3</a>. The data set is modest in size.</p>

<p>Can you recommend an approach?</p>
",https://stackoverflow.com/questions/43382636/unit-testing-and-mocking-mysql-database-in-node-js,"['mysql', 'node.js', 'unit-testing', 'sqlite', 'sequelize.js']",4717,TRUE,3,1
Implementing unit testing in Nodejs express - unexpected failure,"<p><strong>Unable to perform unit testing</strong></p>

<p>The problem is that the test is not passing, although the request and response data is added to the database when I perform the test. Kindly suggest some way to pass this test. The expected status code 200 is not happening with this test. The integration test is working on my app but i am unable to debug this unit testing error.</p>

<pre><code>//testfile
var db = require('../mongodb'),
mongoose = require('mongoose'),
posts = require('../api/addTodo'),
should = require('should'),
testUtils = require('./utils');

describe(""Add Api"", function () {
    var dummyPost, id;
    before(function (done) {
        mongoose.connect('mongodb://localhost:27017/todosdb_test', function() {
            console.log('Connected To:'+'mongodb://localhost:27017/todosdb_test');
            done();
        });

        dummyPost = new db.Todos({
            'admin': 'Dumm_admin',
            'text': 'Dummy',
            'completed': true 
        });

        dummyPost.save(function (err, post) {
            if(err) {
                console.log(err);
            }
            id = post._id;
        });
     });

     describe(""Create Post"", function () {
         it(""should create a new todo"", function (done) {
             var req = {
                 body: {
                     'text': 'Blah blah',
                     'completed': false
                 },
                session: {
                    'email': 'abc'
                }
             };

             var res = testUtils.responseValidator(200, function (post) {
                 post.should.have.property('admin');
                 post.admin.should.equal('abc');
                 post.should.have.property('text');
                 post.text.should.equal('Blah blah');
                 post.should.have.property('completed');
                 post.completed.should.equal(false);
                 done();
             });
                console.log(req);
                console.log(res);
                posts.add(req, res);

         });
     });
        after(function(done){
            db.remove({}, function (err) {
                if(err) {console.log(err);}
            });
            mongoose.disconnect(done);


           });
     });
</code></pre>



<pre><code>// utils file
var responseValidator = function (expectedStatusCode, validationFunction) {
    return{
        json: function (statusCode, data) {
            statusCode.should.equal(expectedStatusCode);
            validationFunction(data);
        },
        send: function (statusCode, data) {
            statusCode.should.equal(expectedStatusCode);
            validationFunction(data);
        }
    }
                         };

         module.exports = {
          responseValidator
                          }
</code></pre>



<pre><code>    //mongodb file
    var mongoose = require('mongoose')
    mongoose.Promise= require('bluebird')

    var schema1 = new mongoose.Schema({
     admin : String,
     text : String,
     completed : Boolean 
     });

    var schema2 = new mongoose.Schema({
    password : String,
    email: String
      });

     var Todos = mongoose.model('Todos', schema1);
     var Accounts = mongoose.model('Accounts', schema2);

    module.exports = {
    Todos,
    Accounts
    }

     //add api file
     var db = require('../mongodb');

       add = (req, res, next) =&gt; {
        todoRes = {
        text: req.body.text,
        completed: req.body.completed
    }

    console.log(req.session.email);
    db.Todos.findOne({ admin: req.session.email, text: todoRes.text })
        .then(function (response) {
            if (!response) {
                var todo = new db.Todos({
                    ""admin"": req.session.email,
                    ""text"": todoRes.text,
                    ""completed"": false
                });
                todo.save()
                    .then(function (response) {
                        res.send({ 'status': 'Todo is added' })
                    })
                    .catch(function (e) {
                        res.send({ 'status': 'failure', Error: e });
                    });
            }
            else {
                res.send({ 'status': 'todo already exist' });
                status:'todo already exist';
            }
        })
        .catch(function (e) {
            res.send({ 'status': e })
        })
     };

     module.exports = {
      add
     }
</code></pre>

<p><strong>Error message at terminal</strong></p>

<pre><code>&gt; mytodos-app@0.0.0 test /Users/sumitkumarsahu/Desktop/mytodos-app
&gt; mocha --recursive ./test/unit.test.js



      Add Api
    Connected To:mongodb://localhost:27017/todosdb_test
        Create Post
    { body: { text: 'Blah blah', completed: false },
      session: { email: 'abc' } }
    { json: [Function: json], send: [Function: send] }
    abc
    Unhandled rejection AssertionError: expected Object {
      status: Error {
        operator: 'to be',
        expected: 200,
        showDiff: false,
        actual: Object { status: 'todo already exist' },
        stackStartFunction: Function { name: 'assert' },
        negate: false,
        assertion: Assertion {
          obj: Object { status: 'todo already exist' },
          anyOne: false,
          negate: false,
          params: Object {
            operator: 'to be',
            expected: 200,
            message: undefined,
            showDiff: false,
            actual: Object { status: 'todo already exist' },
            stackStartFunction: Function { name: 'assert' },
            negate: false,
            assertion: [Circular]
          },
          onlyThis: undefined,
          light: false
        }
      }
    } to be 200
        at Assertion.fail (/Users/sumitkumarsahu/Desktop/mytodos-app/node_modules/should/cjs/should.js:258:17)
        at Assertion.value (/Users/sumitkumarsahu/Desktop/mytodos-app/node_modules/should/cjs/should.js:335:19)
        at Object.send (/Users/sumitkumarsahu/Desktop/mytodos-app/test/utils.js:8:31)
        at /Users/sumitkumarsahu/Desktop/mytodos-app/api/addTodo.js:33:8
        at tryCatcher (/Users/sumitkumarsahu/Desktop/mytodos-app/node_modules/bluebird/js/main/util.js:26:23)
        at Promise._settlePromiseFromHandler (/Users/sumitkumarsahu/Desktop/mytodos-app/node_modules/bluebird/js/main/promise.js:507:31)
        at Promise._settlePromiseAt (/Users/sumitkumarsahu/Desktop/mytodos-app/node_modules/bluebird/js/main/promise.js:581:18)
        at Promise._settlePromises (/Users/sumitkumarsahu/Desktop/mytodos-app/node_modules/bluebird/js/main/promise.js:697:14)
        at Async._drainQueue (/Users/sumitkumarsahu/Desktop/mytodos-app/node_modules/bluebird/js/main/async.js:123:16)
        at Async._drainQueues (/Users/sumitkumarsahu/Desktop/mytodos-app/node_modules/bluebird/js/main/async.js:133:10)
        at Immediate.Async.drainQueues (/Users/sumitkumarsahu/Desktop/mytodos-app/node_modules/bluebird/js/main/async.js:15:14)
        at runCallback (timers.js:672:20)
        at tryOnImmediate (timers.js:645:5)
        at processImmediate [as _immediateCallback] (timers.js:617:5)
          1) should create a new todo
        2) ""after all"" hook


      0 passing (3s)
      2 failing

      1) Add Api Create Post should create a new todo:
         Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure ""done()"" is called; if returning a Promise, ensure it resolves.


      2) Add Api ""after all"" hook:
         TypeError: db.remove is not a function
          at Context.&lt;anonymous&gt; (test/unit.test.js:57:20)



    npm ERR! Test failed.  See above for more details.
</code></pre>
",https://stackoverflow.com/questions/45649534/implementing-unit-testing-in-nodejs-express-unexpected-failure,"['node.js', 'mongodb', 'unit-testing', 'express', 'mocha.js']",123,FALSE,2,1
Angular Material warnings shown when unit testing component,"<p>I am currently writing some units test for some Angular components that make use of <a href=""https://material.angular.io/components"" rel=""nofollow noreferrer"">Angular Material</a>. The issue I am having now is I keep getting the following warnings when running the unit tests.</p>

<pre><code>console.warn node_modules\@angular\material\bundles\material.umd.js:183
Current document does not have a doctype. This may cause some Angular Material components not to behave as expected.

console.warn node_modules\@angular\material\bundles\material.umd.js:196
Could not find Angular Material core theme. Most Material components may not work as expected. For more info refer to the theming guide: https://material.ang
ular.io/guide/theming

console.warn node_modules\@angular\material\bundles\material.umd.js:3327
Could not find HammerJS. Certain Angular Material components may not work correctly.
</code></pre>

<p>Is it normal to see these warnings? Any ideas on how to suppress these warnings as I don't see them really relevant to unit testing?</p>
",https://stackoverflow.com/questions/45316894/angular-material-warnings-shown-when-unit-testing-component,"['angular', 'unit-testing', 'angular-material', 'jestjs']",1342,TRUE,2,2
Unit testing Javascript code with 3rd party libraries,"<p>I have a problem figuring out how to provide code coverage for some of my JS code where a function has within it a call to a 3rd party function that takes a callback as a parameter:</p>

<pre><code>  function handleAuthentication () {
    let path = auth.parseHash(window.location.hash, (err, authResult) =&gt; {
      if (authResult &amp;&amp; authResult.accessToken &amp;&amp; authResult.idToken) {
        // console.log('first it goes in here for new session')
        // pop toaster when use logs in
        logger.popToaster({
          title: 'Welcome!',
          desc: 'This is STRAP'
        }, 'success')

        setSession(authResult)
        return '/home'
      } else {
        // console.log('OR it goes in here for new session')
        if (err) {
          console.log('but never here!')
          // pop toaster if something goes wrong during login
          logger.popToaster({
            title: 'Something Went Wrong!',
            desc: `Error: ${err.error}. Check the console for further details.`
          }, 'error')

          console.log(`Error: ${err.error}. Check the console for further details.`)
        }

        return '/login'
      }
    })

    return path
  }
</code></pre>

<p>I'm using AVA along with Sinon for unit testing, and Auth0 for authentication. The <em>auth.parseHash</em> function call below is a call to an auth0.js library function which takes in a custom callback. But for the life of me I can't figure out how to stub the function in a way that covers all my code below. So for example, I can create a stub for <em>auth.parseHash</em> and a stub for my callback function. But code coverage doesn't cover the inner statements within the conditional logic as my callback is just a stub. And if I mock my callback to something close to the actual code, code coverage still doesn't care. </p>

<p>My overall question is, am I doing this all wrong? Is this bad code design? Are there any standard patterns to follow in cases like these?</p>

<p>Really appreciate any help I can get.
Thank you in advance.</p>
",https://stackoverflow.com/questions/46432741/unit-testing-javascript-code-with-3rd-party-libraries,"['javascript', 'unit-testing', 'sinon', 'ava']",224,FALSE,2,0
Hiding dependency injection while unit testing shared library,"<p>After learning the importance of having automated testing in a codebase, I'm currently trying to add unit testing to my own fairly large C++ codebase.</p>

<p>The codebase I'm working on is a shared library. I think I understand how to deal with the numerous system calls I need to make; hide a lot of them behind interfaces and use dependency injection. The problem is, I don't want client code that is using the library to see the dependency injection, since that's only a requirement to make the library code unit testable.</p>

<p>For example, take this line of code:</p>

<pre><code>TextBox* textBox = new TextBox();
</code></pre>

<p>The <code>TextBox</code> class contains code that makes multiple calls to Win32 API functions, such as the Clipboard. If I understand correctly, I need to do this in order to have the appropriate unit tests for the <code>TextBox</code> class:</p>

<pre><code>TextBox* textbox = new TextBox(IClipboardApi* clipboard);
</code></pre>

<p>The problem is, if someone is using this library, I don't think they should have to provide a real clipboard instance. I could take advantage of default values:</p>

<pre><code>TextBox* textbox = new TextBox(IClipobardApi* clipboard = CreateClipboardInstance());
</code></pre>

<p>But I don't know if this is the right way to go about it either.</p>

<p>I'm still very new to unit testing, and much of my library code was written before I learned about unit testing. It's completely possible this class is just not written well. If the class is written well enough, how could I go about hiding implementation details like this from clients? If the class isn't written properly, what might be a better design?</p>
",https://stackoverflow.com/questions/46987710/hiding-dependency-injection-while-unit-testing-shared-library,"['c++', 'unit-testing', 'winapi', 'dependency-injection', 'information-hiding']",210,FALSE,2,0
Unit Testing BelongsToMany relations in Sequelize using Jasmine,"<p>I'm building a simple blog style application for practice using Node and Sequelize (with the Yeoman angular-fullstack generator). I'm trying to write out some tests for my article model, but I'm unable to figure out the right way to structure my tests. The articles and users are connected by a two-way belongsToMany relationship. </p>

<p>I'm able to verify that the setter and getter methods exist for my objects, but am unable to verify that they work. The code I'm trying to get to work is the code commented out at the end of the file. I'd appreciate any help in getting that unit test to work correctly, thanks!</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>'use strict';

/* globals describe, expect, it, beforeEach, afterEach */

var app = require('../..');
import request from 'supertest';
import {User, Article} from '../../sqldb';

var user = [];
var article = [];

var genArticles = function(i) {
  for(var i = 0; i &lt; 3; i++) {
    article[i] = genArticle(i);
  }
  return article;
}

var genUsers = function(i) {
  for(var i = 0; i &lt; 3; i++) {
    user[i] = genUser(i);
  }
  return user;
}

var genUser = function(i) {
  return User.build({
    provider: 'local',
    name: `Fake User ${i}`,
    email: `test${i}@example.com`,
    password: 'password'
  });
};

var genArticle = function(i) {
  return Article.build({
    title: `Fake Article ${i}`,
    body: `test${i}`
  });
};

describe(""Article-User relations"", function() {
  before(function() {
    return User.sync().then(function() {
      return User.destroy({ where: {} }).then(function() {
        return Article.sync().then(function() {
          return Article.destroy({ where: {} }).then(function() {
          });
        });
      });
    });
  });

  beforeEach(function(done) {
    genArticles();
    genUsers();
    done();
  });

  afterEach(function() {
    return User.sync().then(function() {
      return User.destroy({ where: {} }).then(function() {
        return Article.sync().then(function() {
          return Article.destroy({ where: {} }).then(function() {
          });
        });
      });
    });
  });

  it('should begin with no data', function() {
    expect(User.findAll()).to
      .eventually.have.length(0);
    return expect(Article.findAll()).to
      .eventually.have.length(0);
  });


  describe(""Check methods exist and"", function(done) {
    before(function(done) {
      article.forEach((a) =&gt;  {a.save()});
      user.forEach((a) =&gt;  {a.save()});
      done();
    });
    it(""should have setter methods"", function() {
      expect(typeof article[0].setUsers).to.equal(""function"");
      expect(typeof user[0].setArticles).to.equal(""function"");
    });
    it(""should have getter methods"", function() {
      expect(typeof article[0].getUsers).to.equal(""function"");
      expect(typeof user[0].getArticles).to.equal(""function"");
    });

    /* THIS IS THE TEST THAT ISN'T WORKING */

    /*
    it(""setter and getter methods for article objects should work"", function() {
      return article[0].setUsers(user).then(() =&gt; {
        return article[0].hasUsers(user).then( result =&gt; { 
          expect(result).should.eventually.equal.true;
        })
      }).catch( e =&gt; { console.log(e) });
      //expect(typeof user[0].setArticles).to.equal(""function"");
    });
    */

  });
});</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/44125380/unit-testing-belongstomany-relations-in-sequelize-using-jasmine,"['javascript', 'node.js', 'unit-testing', 'sequelize.js', 'has-and-belongs-to-many']",379,FALSE,2,0
Unit testing with mockito and spy causing error,"<p>I am using <code>Mockito</code> and Spy to unit test a function.</p>

<p>This is the class under test:</p>

<pre><code>public class RecipeListModelImp
        implements RecipeListModelContract {

    private Subscription subscription;
    private RecipesAPI recipesAPI;

    @Inject
    public RecipeListModelImp(@NonNull RecipesAPI recipesAPI) {
        this.recipesAPI = Preconditions.checkNotNull(recipesAPI);
    }

    @Override
    public void getRecipesFromAPI(final RecipeGetAllListener recipeGetAllListener) {
        subscription = recipesAPI.getAllRecipes()
               .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber&lt;List&lt;Recipe&gt;&gt;() {
                    @Override
                    public void onCompleted() {
                              }
                    @Override

                    public void onError(Throwable e) {
                                  recipeGetAllListener.onRecipeGetAllFailure(e.getMessage());

                    }


                    @Override

                    public void onNext(List&lt;Recipe&gt; recipe) {                       recipeGetAllListener.onRecipeGetAllSuccess(recipe);
                    }
                });
    }

    @Override
    public void shutdown() {
        if(subscription != null &amp;&amp; !subscription.isUnsubscribed()) {
            subscription.unsubscribe();
        }
    }
}
</code></pre>

<p>I am trying to test using Mockito and spy as I don’t want to call the real function <code>recipesAPI.getAllRecipes()</code> just verify it.The test is called <code>testGetRecipesFromAPI()</code></p>

<pre><code>public class RecipeListModelImpTest {
    @Mock Subscription subscription;
    @Mock RecipesAPI recipesAPI;
    @Mock RecipeListModelContract.RecipeGetAllListener recipeGetAllListener;

    private RecipeListModelContract recipeListModel;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(RecipeListModelImpTest.this);
        recipeListModel = new RecipeListModelImp(recipesAPI);
    }

    @Test
    public void testGetRecipesFromAPI() {
        RecipeListModelContract recipeListModelSpy = spy(recipeListModel);
        RecipesAPI recipeApiSpy = spy(recipesAPI);
        doNothing().when(recipeApiSpy).getAllRecipes();

        recipeListModelSpy.getRecipesFromAPI(recipeGetAllListener);

        verify(recipesAPI, times(1)).getAllRecipes();

    }

    @Test
    public void testShouldShutdown() {
        recipeListModel.shutdown();
        verify(subscription, times(1)).unsubscribe();
    }
}
</code></pre>

<p>This is the error:</p>

<pre><code>org.mockito.exceptions.base.MockitoException: 
Only void methods can doNothing()!
Example of correct use of doNothing():
    doNothing().
    doThrow(new RuntimeException())
    .when(mock).someVoidMethod();
Above means:
someVoidMethod() does nothing the 1st time but throws an exception the 2nd time is called
</code></pre>

<p>I have also tried this which causes a null pointer:</p>

<pre><code>  @Test
    public void testGetRecipesFromAPI() {
        RecipeListModelContract recipeListModelSpy = spy(recipeListModel);
        RecipesAPI recipeApiSpy = spy(recipesAPI);

        doReturn(Observable.just(Subscription.class)).when(recipeApiSpy).getAllRecipes();

        recipeListModelSpy.getRecipesFromAPI(recipeGetAllListener);

        verify(recipesAPI, times(1)).getAllRecipes();
    }
</code></pre>
",https://stackoverflow.com/questions/44719675/unit-testing-with-mockito-and-spy-causing-error,"['java', 'android', 'unit-testing', 'mockito', 'tdd']",1568,TRUE,2,3
CakePHP 3: Set $_SERVER variable for unit testing,"<p>I need to be able to set a <code>$_SERVER[]</code> variable in my unit test to several different values. I have seen <a href=""https://stackoverflow.com/q/6934951/1743903"">this answer</a>, but that only allows me to have 1 value, and I need to test multiple values.</p>

<p>I get the sense from the CakePHP documentation that it has something to do with <code>$this-&gt;configRequest()</code>, but that's just a hunch at this point.</p>
",https://stackoverflow.com/questions/43125542/cakephp-3-set-server-variable-for-unit-testing,"['php', 'unit-testing', 'cakephp', 'phpunit']",1062,TRUE,2,2
Angular 4 Unit Testing the code using window,"<p>I would like to test a code</p>

<pre><code>public openAttachment(attachment: Attachment) {
    if (window.navigator &amp;&amp; window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(attachment.getFile());
    }
    else {
        let objectUrl = URL.createObjectURL(attachment.getFile());
        window.open(objectUrl);
    }
}
</code></pre>

<p>I don't know how to get access to window or mock window in order to test it. I'm new to angular testing so it would be great if you could explain me in a detail please!</p>
",https://stackoverflow.com/questions/46670551/angular-4-unit-testing-the-code-using-window,"['angular', 'testing', 'jasmine', 'window', 'karma-jasmine']",8951,TRUE,2,2
Unit testing Angular2 component template with sortby pipe,"<p>I have a component that contains an ngFor loop in it's template. I'm using an order by pipe called 'ngx-order-pipe' in order to be able to sort my objects by a property called 'orderNum'. The sorting works perfectly when I run it but I'm having difficulty unit testing this.</p>

<pre><code>&lt;ng-container *ngFor=""let group of fieldGroups | orderBy : orderNumber""&gt;
    &lt;div id=""field-groups""&gt;
        &lt;h3&gt;{{ group.groupName }}&lt;/h3&gt;
        &lt;app-dt-field-render [fields]=""group.fields""&gt;&lt;/app-dt-field-render&gt;
    &lt;/div&gt;
    &lt;hr&gt;
&lt;/ng-container&gt;
</code></pre>

<p>My component is simple and simply has an input field that accepts an array.</p>

<pre><code>import { Component, Input } from '@angular/core';
import { FieldGroup } from '../../../models/dynamic-template/render';

@Component({
  moduleId: module.id,
  selector: 'app-dt-field-group-render',
  templateUrl: 'field-group-render.component.html'
})

export class FieldGroupRenderComponent {

  @Input() fieldGroups: FieldGroup[];

  constructor() { }

}
</code></pre>

<p>I've attempted to unit test this by creating 2 objects in my array and adding them in reverse sort order. I would expect that my template output would have my objects sorted correctly. Here is the test:</p>

<pre><code>it('should order primitive fields but does not for some reason', () =&gt; {
    testPrimitiveField = new PrimitiveField();
    testPrimitiveField.dataType = 1;
    testPrimitiveField.fieldType = 0;
    testPrimitiveField.orderNum = 2;
    testPrimitiveField.fieldName = 'two';

    testSecondPrimitiveField = new PrimitiveField();
    testSecondPrimitiveField.dataType = 1;
    testSecondPrimitiveField.fieldType = 0;
    testSecondPrimitiveField.orderNum = 1;
    testSecondPrimitiveField.fieldName = 'one';

    fixture.componentInstance.fields.push(testPrimitiveField, testSecondPrimitiveField);
    fixture.detectChanges();

    const compiled = fixture.debugElement.nativeElement;
    const output = compiled.querySelector('#dynamic-fields');
    const elements = output.getElementsByTagName('app-dt-primitive-text-render');

    expect(output.childElementCount).toEqual(2);
    expect(elements.length).toEqual(2);

    // This should be object with OrderNum == 1 but it isn't
    console.log(fixture.componentInstance.fields[0])
    console.log(output.firstElementChild)

    // This should be object with OrderNum == 2 but it isn't
    console.log(fixture.componentInstance.fields[1])
    console.log(output.lastElementChild)
});
</code></pre>

<p>Neither my output nor my array are being sorted. I suspect it has something to do with the pipe either not being injected into my test or that I have some sort of async issue. Any advice or direction is appreciated.</p>
",https://stackoverflow.com/questions/44594391/unit-testing-angular2-component-template-with-sortby-pipe,"['angular', 'unit-testing', 'sorting', 'pipe', 'karma-runner']",624,FALSE,2,0
Unit testing an application with CDI and ServletContextListener,"<p>I've got a CDI web application which has a ServletContextListener to initialise a few things on startup.</p>

<p>In that ServletContextListener, this (among other things) happens:</p>

<pre><code>@Inject
Config config;

public void contextInitialized(ServletContextEvent event) {
    ....

    config.init(....)
}
</code></pre>

<p>This works well enough, as this makes sure that the init is performed before other CDI beans are instantiated (such as App, which injects Config itself too)</p>

<p>However, I'm unable to work out how to realise this logic for unit testing. With CDI-Unit from jglue, I can do this in my test class:</p>

<pre><code>@Inject
Config config;

@Inject
App application;
</code></pre>

<p>But when I run my test, I keep on getting issues, as the @PostConstruct in App needs Config to be inited already. So, how can I possibly call the Config.init() method in time?</p>
",https://stackoverflow.com/questions/46302798/unit-testing-an-application-with-cdi-and-servletcontextlistener,"['unit-testing', 'junit', 'cdi', 'cdi-unit']",337,FALSE,2,0
Android Unit Testing - method to test returning null,"<p>Method to test:</p>

<pre><code>public static String getDeviceName() {
    String manufacturer = Build.MANUFACTURER;
    String model = Build.MODEL;
    if (model.startsWith(manufacturer)) {
        return WordUtils.capitalize(model);
    } else {
        return WordUtils.capitalize(manufacturer) + "" "" + model;
    }
}
</code></pre>

<p>test case:</p>

<pre><code>@Test
public void testGetDeviceName() throws Exception {
    String deviceNameTest = ""device name"";
    assertEquals(deviceNameTest, DeviceUtil.getDeviceName());
}
</code></pre>

<p>Error</p>

<blockquote>
  <p>java.lang.NullPointerException</p>
  
  <p>getDeviceName(DeviceUtil.java:15)
  DeviceUtilTest.testGetDeviceName(DeviceUtilTest.java:18)</p>
  
  <p>DeviceUtil.getDeviceName() -> returns null</p>
</blockquote>
",https://stackoverflow.com/questions/46823382/android-unit-testing-method-to-test-returning-null,"['java', 'android', 'unit-testing', 'junit', 'mockito']",2072,TRUE,2,2
Unit testing with mock that has mock inside,"<p>I need to unit test a certain method that works on an object of type X. The X object has few normal fields like String, int etc. but it also has a List of types Y. This Y type is also quite complex. And to make my problem even more difficult, let's say that the type Y has another list of type Z.</p>

<p>Ideally, I need to mock object X, but tell it to inject another mock of type Y inside, which should also inject another mock Z to itself (to Y). How should I do that?</p>

<p>And if I have so many few-levels mocks how should I avoid writing 20 specifications of what these mocks should actually return upon calling their methods?</p>

<p>Or is this a type of problem where I should use Builders and actually build a real object?</p>

<p>Thanks alot,
Bob.</p>

<p>Edit:
just an example usage code on top from my head:</p>

<pre><code>public String produceImportantStringOfImportantData(ObjectX x) throws ParseException {
    StringBuilder textResult = new StringBuilder();

    List&lt;ObjectY&gt; listOfY = x.getListOfY();

    if (listOfY.isValid()) {
        for (ObjectY y : listOfY) {
            for (ObjectZ z : y.getListOfZ()) {
                textResult.append(""&lt;font color='green'&gt;"").append(z.getField2).append(""&lt;/font&gt;"").append("": "").append(z.getSomething())
                        .append("" Label : "").append(z.getParentComponent.getField()))
                        .append("" some important labels: "").append(z.getField()))
                        .append("" some important labels "").append(y.getAnotherField))
                        .append("" different, important label: "").append(y.getField()))
                        .append(""&lt;br/&gt;"");
            }
        }
    } 
    return textResult.toString();
}
</code></pre>
",https://stackoverflow.com/questions/42859892/unit-testing-with-mock-that-has-mock-inside,"['java', 'unit-testing']",3365,TRUE,2,2
Is Jest a react native unit testing tool?,"<p>Is <code>Jest</code> a unit testing tool for <code>React-Native</code>? I need to perform functional validation on the UI layer of a <code>React Native</code> based app. Currently we use <code>Appium</code> for testing a <code>Native app</code> but since we are migrating our apps to <code>React Native</code> I was wondering if I can use <code>Jest</code>. But the more I read about <code>Jest</code> I'm starting to feel that it's a <code>unit testing</code> tool. Should I continue to use <code>Appium</code> or should I move to <code>Jest</code> if I want to perform functional validation on the UI of the native application?</p>
",https://stackoverflow.com/questions/46550856/is-jest-a-react-native-unit-testing-tool,"['android', 'ios', 'react-native', 'jestjs']",240,TRUE,2,2
"unit testing angular service, beforeEach inject doesn&#39;t execute","<p>I'm trying to write unit tests for an angular service with jasmine/karma. I have a similar service test, which works just fine. But this one has some additional dependencies, is in a different module and just doesn't find the service with the inject. </p>

<p>The service looks something like this. <code>bService</code> is in the same module, but <code>commonFactory</code> and <code>commonService</code> are in another module, say <code>commonModule</code>. </p>

<pre><code>(function () {
    'use strict';
     angular
         .module('myService')
         .service('aService', aService);

     aService.$inject = [
         'commonFactory',
         'commonService'
         'bService'
     ];

     function aService (
         commonFactory,
         commonService,
         bService
     ) {

     };

     return {
         codeIWantToTest: CodeIWantToTest;
     }

     function CodeIWantToTest () {
          console.log('surprise!');
     }
})();
</code></pre>

<p>My jasmine test looks like: </p>

<pre><code>describe('myService.aService', function () {
    'use strict';
    var aService;
    // I tried adding beforeEach(module('commonModule')); too, but that didn't do anything
    beforeEach(module('myService'));

    beforeEach(function() {
        inject(function(_aService_) {
            console.log('getting aService');
            aService = _aService_;
        });
    }); 

    it('tests my service is defined', function() {
        expect(myService).toBeDefined();
    });
});
</code></pre>

<p>This test fails. <code>myService</code> isn't defined and the <code>console.log</code> in the inject function doesn't ever fire. My <code>karma.conf.js</code> basically lists the dependencies in the order that they're injected into the service, then adds the service then the test. </p>

<p>What would cause the inject to not grab the service? What am I missing? I mentioned I have a similar test for <code>commonService</code> and it works just fine. So I'm baffled. </p>
",https://stackoverflow.com/questions/41896782/unit-testing-angular-service-beforeeach-inject-doesnt-execute,"['angularjs', 'unit-testing', 'jasmine', 'karma-runner']",3114,TRUE,2,1
"Unit testing HTTP request with Vue, Axios, and Mocha","<p>I'm really struggling trying to test a request in VueJS using Mocha/Chai-Sinon, with Axios as the request library and having tried a mixture of Moxios and <code>axios-mock-adaptor</code>. The below examples are with the latter.</p>

<p>What I'm trying to do is make a request when the component is created, which is simple enough.</p>

<p>But the tests either complain about the <code>results</code> variable being undefined or an <code>async timout</code>.</p>

<p>Am I doing it right by assigning the variable of the <code>getData() function? Or should I</code>return` the values? Any help would be appreciated.</p>

<p><strong>Component</strong></p>

<pre><code>  // Third-party imports
  import axios from 'axios'
  // Component imports
  import VideoCard from './components/VideoCard'

  export default {
    name: 'app',
    components: {
      VideoCard
    },
    data () {
      return {
        API: '/static/data.json',
        results: null
      }
    },
    created () {
      this.getData()
    },
    methods: {
      getData: function () {
        // I've even tried return instead of assigning to a variable
        this.results = axios.get(this.API)
          .then(function (response) {
            console.log('then()')
            return response.data.data
          })
          .catch(function (error) {
            console.log(error)
            return error
          })
      }
    }
  }
</code></pre>

<p><strong>Test</strong></p>

<pre><code>import Vue from 'vue'
import App from 'src/App'

import axios from 'axios'
import MockAdapter from 'axios-mock-adapter'

let mock = new MockAdapter(axios)

describe('try and load some data from somewhere', () =&gt; {
  it('should update the results variable with results', (done) =&gt; {
    console.log('test top')
    mock.onGet('/static/data.json').reply(200, {
      data: {
        data: [
          { id: 1, name: 'Mexican keyboard cat' },
          { id: 2, name: 'Will it blend?' }
        ]
      }
    })

    const VM = new Vue(App).$mount

    setTimeout(() =&gt; {
      expect(VM.results).to.be.null
      done()
    }, 1000)
  })
})
</code></pre>
",https://stackoverflow.com/questions/41772956/unit-testing-http-request-with-vue-axios-and-mocha,"['vue.js', 'axios', 'karma-mocha']",11989,TRUE,8,2
relay modern: how to mock relay for unit testing,"<p>Am trying to test react relay modern container, but am having this issue.</p>

<pre><code>TypeError: Cannot read property 'environment' of undefined
</code></pre>

<p>Here is the test code:</p>

<pre><code>test('render component', () =&gt; {
  const tree = renderer.create(
    &lt;User /&gt;,
  ).toJSON();

  expect(tree).toMatchSnapshot();
});
</code></pre>
",https://stackoverflow.com/questions/45897457/relay-modern-how-to-mock-relay-for-unit-testing,"['react-native', 'relaymodern']",1173,FALSE,8,2
Unit testing classes that implement a collection Interface?,"<p>I've written a storage interface that can use different storage backends. As a demonstration I've written an implementation that stores objects as a key/value pair in a standard Python dictionary.</p>

<pre><code>class MyStorageInterface(object):
    def store(self, key, value):
        raise NotImplementedError(""Class must be subclassed"")

    def get(self, key):
        raise NotImplementedError(""Class must be subclassed"")

# Example implementation
class DictStorage(MyStorageInterface):
    def __init__(self):
        self._cache = dict()

    def store(self, key, value):
        self._cache[key] = value

    def get(self, key):
        return self._cache[key]
</code></pre>

<p>Now, I want to write some unit tests for my <code>DictStorage</code> implementation. My question is whether or not something like:</p>

<pre><code>storage = DictStorage()
value = 8
key = 'foo'
storage.store(key, value)
actual = storage.get(key)
assert actual == 8, ""cache value for %s is %s, expected %s"" % (key, str(actual), str(value))
</code></pre>

<p>is a suitable unit test for the get method or whether or not there is a Pythonic pattern for testing classes that implement collection type objects.</p>
",https://stackoverflow.com/questions/41708364/unit-testing-classes-that-implement-a-collection-interface,"['python', 'unit-testing']",80,TRUE,1,1
How to include go templates when unit testing,"<p>I'm trying to test an implementation of a simple web server in Go using the <a href=""https://github.com/gin-gonic/gin"" rel=""nofollow noreferrer"">Gin</a>.</p>

<p>The service has a single endpoint rendering HTML.</p>

<p><code>server.go</code></p>

<pre><code>// Serve triggers the server initialization
func Serve(addr string) {
    if err := serverEngine().Run(addr); err != nil {
        log.Fatalf(""could not serve on %s: %s"", addr, err)
    }
}

func serverEngine() *gin.Engine {
    eng := gin.Default()

    // Register resource handlers
    eng.LoadHTMLGlob(""tmpl/*"")
    eng.GET(""/"", indexHandler)
    return eng
}

func indexHandler(c *gin.Context) {
    c.HTML(http.StatusOK, ""index.tmpl"", gin.H{
        ""title"": ""foo"",
    })
}
</code></pre>

<p><code>server_test.go</code></p>

<pre><code>func TestServe(t *testing.T) {
    timeOut := time.Duration(3) * time.Second
    server := httptest.NewServer(serverEngine())
    defer server.Close()

    // fixes weird double ':' problem
    port := server.URL[len(server.URL)-5:]

    _, err := net.DialTimeout(""tcp"", ""localhost:""+port, timeOut)
    if err != nil {
        t.Errorf(""failed to dial server: %s"", err)
    }
}
</code></pre>

<p>When I run the code everything works fine. But when running the unit tests it panics with the following message:</p>

<pre><code>--- FAIL: TestServe (0.00s)
panic: html/template: pattern matches no files: `tmpl/*` [recovered]
    panic: html/template: pattern matches no files: `tmpl/*`
</code></pre>

<p>Project structure:</p>

<pre><code>.
├── main.go
└── server
    ├── server.go
    ├── server_test.go
    └── tmpl
        └── index.tmpl
</code></pre>

<p>How can I ensure that the <code>go test</code> know about the template location at runtime so I can perform this test?</p>
",https://stackoverflow.com/questions/45001750/how-to-include-go-templates-when-unit-testing,"['go', 'go-templates', 'go-gin']",1680,FALSE,1,1
Unit testing custom attribute value in OnActionExecuting event,"<p>I have following implementation in my base controller from which I am deriving most of my controllers. It accounts for setting the page title, meta description and keywords for each page if the values are not set via decorator on the controller actions.</p>

<p><strong>BaseController</strong></p>

<pre><code>public class BaseController : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //Page title
        var title = filterContext.ActionDescriptor.GetCustomAttributes(typeof(PageTitleAttribute), false);
        if (title.Length == 1)
            ViewBag.Title = ((PageTitleAttribute)(title[0])).Parameter;
        else
            ViewBag.Title = ""My website title"";

        //Page keywords
        var keywords = filterContext.ActionDescriptor.GetCustomAttributes(typeof(MetaKeywordsAttribute), false);
        if (keywords.Length == 1)
            ViewBag.MetaKeywords = ((MetaKeywordsAttribute)(keywords[0])).Parameter;
        else 
            ViewBag.MetaKeywords = ""targeted SEO keywords"";

        //Page description
        var description = filterContext.ActionDescriptor.GetCustomAttributes(typeof(MetaDescriptionAttribute), false);
        if (description.Length == 1)
            ViewBag.MetaDescription = ((MetaDescriptionAttribute)(description[0])).Parameter;
        else 
            ViewBag.MetaDescription = ""My custom description"";

        base.OnActionExecuting(filterContext);
    }
}
</code></pre>

<p>The custom attributes are fairly simple:</p>

<pre><code>public class PageTitleAttribute : Attribute
{
    private readonly string _parameter;

    public PageTitleAttribute(string parameter)
    {
        _parameter = parameter;
    }

    public string Parameter { get { return _parameter; } }
}

public class MetaDescriptionAttribute : Attribute
{
    private readonly string _parameter;

    public MetaDescriptionAttribute(string parameter)
    {
        _parameter = parameter;
    }

    public string Parameter { get { return _parameter; } }
}

public class MetaKeywordsAttribute : Attribute
{
    private readonly string _parameter;

    public MetaKeywordsAttribute(string parameter)
    {
        _parameter = parameter;
    }

    public string Parameter { get { return _parameter; } }
}
</code></pre>

<p>And this is how make use of the attributes on appropirate action methods in controller:</p>

<pre><code>public class HomeController : BaseController
{
    [PageTitle(""My new website"")]
    [MetaKeywords(""Explicitly set keywords"")]
    [MetaDescription(""description goes here"")]
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Error()
    {            
        return View();
    }
}
</code></pre>

<p>This all seems to work just fine. Now I would like to create unit test to validate that if the values are not set via attribute on action methods, the default values will be rendered as set from base controller. How can I do that? I have some tests written but I don't think they are targeting the filterContext on the basecontroller. Specifically I am looking for test for Error action method which does not have anything attribute value set. Just for reference this is what I have setup now:</p>

<pre><code>[TestMethod]
    public void Attribute_when_set_should_return_attribute_values() 
    {
        var method = typeof(HomeController).GetMethod(""Index"");
        var pageTitle = method.GetCustomAttributes(typeof(PageTitleAttribute), false)
                     .Cast&lt;PageTitleAttribute&gt;()
                     .SingleOrDefault();
        var keywords = method.GetCustomAttributes(typeof(MetaKeywordsAttribute), false)
                     .Cast&lt;MetaKeywordsAttribute&gt;()
                     .SingleOrDefault();
        var description = method.GetCustomAttributes(typeof(MetaDescriptionAttribute), false)
                     .Cast&lt;MetaDescriptionAttribute&gt;()
                     .SingleOrDefault();

        Assert.IsNotNull(pageTitle);
        Assert.IsNotNull(keywords);
        Assert.IsNotNull(description);

        Assert.AreEqual(""My new website"", pageTitle.Parameter);
        Assert.AreEqual(""Explicitly set keywords"", keywords.Parameter);
        Assert.AreEqual(""description goes here"", description.Parameter);
    }
</code></pre>
",https://stackoverflow.com/questions/41488962/unit-testing-custom-attribute-value-in-onactionexecuting-event,"['asp.net-mvc', 'unit-testing', 'moq']",483,FALSE,1,0
Issue in unit testing and using Moq .Returns,"<p>I am new to write Unit Tests. Therefore, I have been struggling with.</p>

<p>I need to insert product via an external WebService. Then the WebService will return a string that is necessary to update the product afterwards.</p>

<p>This is my <code>ApiController</code>:</p>

<pre><code>public class ProductController : ApiController
{
    private IProductRepository _ProductRepository;
    private IWebService _WebService;

    public ProductController(IProductRepository productRepository, IWebService webService)
    {
        _ProductRepository = productRepository;
        _WebService = webService;
    }

    public HttpResponseMessage Add(string title)
    {
        using (TransactionScope scope = new TransactionScope())
        {
            Product product = new Product
            {
                Title = title
            };

            this._ProductRepository.Add(product);

            // WebService will return a string
            string result = this._WebService.Add(product.ID, DateTime.Now); 

            product.ServiceResult = result;

            this._ProductRepository.Update(product);

            scope.Complete();
        }

        return Request.CreateResponse(HttpStatusCode.Created);
    }
}
</code></pre>

<p>I was wondering how should I write a unit test for this code? </p>

<p>I've tried to write it as follows: (with NUnit, Moq)</p>

<pre><code>[TestFixture]
public class ProductControllerShould : AssertionHelper
{
    private Mock&lt;IWebService&gt; _WebService;
    private Mock&lt;IProductRepository&gt; _ProductRepository;

    [SetUp]
    public void Setup()
    {
        _WebService = new Mock&lt;IWebService&gt;();
        _ProductRepository = new Mock&lt;IProductRepository&gt;();
    }

    [Test]
    public void ReturnCreatedOnAdd()
    {
        _WebService.Setup(b =&gt; b.Add(1, DateTime.Now))
            .Returns(""0"");

        var controller = new ProductController(_ProductRepository.Object, 
                         _WebService.Object);

        var result = controller.Add(""Lumia"");

        Expect(result, Is.EqualTo(HttpStatusCode.Created));
    }
}
</code></pre>

<p>but when I debug the test, result in this line is null that is not correct.</p>

<pre><code>string result = this._WebService.Add(product.ID, DateTime.Now);
</code></pre>

<p>Shouldn't this line handle the behaviour of _WebService.Add() and return ""0""?</p>

<pre><code>_WebService.Setup(b =&gt; b.Add(1, DateTime.Now))
                .Returns(""0"");
</code></pre>

<p>I know I write the test incorrectly but I don't know what should I do.</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/41790480/issue-in-unit-testing-and-using-moq-returns,"['c#', '.net', 'unit-testing', 'nunit', 'moq']",476,TRUE,1,1
Avoid side effect when unit testing with Jasmine,"<p>I'm trying to unit test the function below with the testing library node-jasmine:</p>

<pre><code>joinGame(participant) {
    console.log('Joining game', participant);

    if (this.getParticipants().length &gt;= MAX_NUMBER_OF_PARTICIPANTS) {
        throw new Error(`The game with id ${this.getId()} has reached the maximum amount of participants, ${MAX_NUMBER_OF_PARTICIPANTS}`);
    }

    this.addParticipant(participant);
    this.incrementPlayerCount();

    this.emit(actions.GAME_JOINED, participant);

    // Is the game ready to start?
    if (this.playerCount &gt;= REQUIRED_NUMBER_OF_PARTICIPANTS) {
        // Start game loop by initializing the first round
        this.createRound();
    }
}
</code></pre>

<p>However, when unit testing the function, a couple of code paths lead me toward calling 'this.createRound()' located at the end of the function. createRound() basically initializes the game loop, start timers, and other side effects completely unrelated to the function I'm unit testing. Look at the test below:</p>

<pre><code>it('should throw an error if a user tries to join a game with the maximum amount of participants has been reached', () =&gt; {
    game = new Game();

    // To test whenever there are two participants in the game
    game.joinGame(hostParticipant);
    game.joinGame(clientParticipant);

    function testJoin() {
        game.joinGame(joiningParticipant);
    }

    expect(testJoin).toThrow();
});
</code></pre>

<p>Now when I run the test the test will against my will invoke 'createRound()'. 'createRound()' instantiates a Round instance and starts a countdown timer, which makes the 'npm test' call in my commandline to never finish. Since the test thinks it's apart of the test.</p>

<p>Below is a number of approaches I've thought of and implemented. Although, I don't feel like any of them are ""clean"", that's why I'm looking for your input.</p>

<p><strong>Approach 1:</strong> Stub 'createRound()' inside of the test to replace its functionality. This works fine, but is it the correct way to avoid invoking side effects?</p>

<p><strong>Approach 2:</strong> Try setting up/tearing down the Game instance on beforeEach/afterEach. I've tried this approach to no success. By setting the game instance to null on 'afterEach()', however, the instantiated round instance keeps going along with its timer.</p>

<p><strong>Approach 3:</strong> Use dependency injection when invoking 'joinGame()' and supply a Round instance. This doesn't make much sense though, because it shouldn't be the client's responsibility of supplying a fresh round instance when invoking 'joinGame()'. Furthermore, not every call to 'joinGame()' invokes 'createRound()'; only when the player counts exceeds the required amount of players.</p>
",https://stackoverflow.com/questions/47872811/avoid-side-effect-when-unit-testing-with-jasmine,"['node.js', 'unit-testing', 'jasmine']",584,TRUE,1,1
unit testing with generated protobuf code in Java,"<p>I have a general question regarding unit testing with generated code.  So I have a method like:</p>

<pre><code>public Proto.MyResponse generateCert(String id) throws Exception {
      Proto.MyResponse.Builder builder = Proto.MyResponse.newBuilder();

      // do some logic and set properties on the builder like
      builder.setResponse(SUCCESS);

      return builder.build();
}
</code></pre>

<p>So if I try to unit test this method, it'll fail right away with a NPE.  Do I need to put the builder logic into some other class that implements that this class injects so I can mock out the call to create the builder?  Just curious if that is the best approach since I can imagine that I will have to build out various messages and have logic similar to this where within a method I</p>

<p>1) do logic 
2) set properties on builder based on (1)
3) return the built message</p>
",https://stackoverflow.com/questions/46189441/unit-testing-with-generated-protobuf-code-in-java,"['java', 'unit-testing']",1523,FALSE,1,0
C# exception handling under unit testing doesn&#39;t work,"<p>I'm new in VisualStudio, so I haven't got much experience with the unit testing in it. 
I try to write a basic file reader class, wich has two variables: path and lines string list.</p>

<p>The path can be given to the constructor, or also can be set with a setter method.
There is a readIn function, which load up the list with the lines of the text file can be found on the path.
The function should chek if the path is not null or is it valid (is the path pointing to an existing file). If not, it throws a System.ArgumentNullException or a throw new System.ArgumentException.</p>

<p>When I try to test that the exceptions are thrown in case of the path is null or not valid, the VisualStudio always stuck and says that I have an unhadnled exception, however, I defined the expected exception before the test method.</p>

<p>Have you got any idea how should I do this in correct way? 
Or if it is the correct way (I read about it also here and on the msdn page too, so it should work), what should I do to get it work?</p>

<p>The reader class:</p>

<pre><code>using System;
using System.Collections.Generic;
using System.IO;

namespace LogParserConsole
{
    public class FileReader
    {
        private string path;
        private List&lt;string&gt; lines;

        public FileReader()
        {
            path = null;
            lines = null;
        }

        public FileReader(string path)
        {
            this.path = path;
            if (isFileExists())
            {
                lines = new List&lt;string&gt;();
            }
            else
            {
                lines = null;
            }
        }

        public void readIn()
        {
            if(path == null)
            {
                throw new System.ArgumentNullException(""The path is not set. Please set a path first!"");
            }
            else if(!isFileExists())
            {
                throw new System.ArgumentException(""The given path is invalid, please chek it!"");
            }
            string line;
            System.IO.StreamReader file = new System.IO.StreamReader(path);
            while ((line = file.ReadLine()) != null)
            {
                lines.Add(line);
                Console.WriteLine(line);
            }

            file.Close();
        }

        public bool isFileExists()
        {
            return File.Exists(path);
        }

        public string getPath()
        {
            return this.path;
        }

        public List&lt;string&gt; getLines()
        {
            return this.lines;
        }

        public void setPath(string path)
        {
            this.path = path;
        }
    }
}
</code></pre>

<p>The unit test method for the exception:</p>

<pre><code>[TestMethod]
[ExpectedException(typeof(System.ArgumentNullException))]
public void ReadInTest()
{
    FileReader fr = new FileReader();
    fr.readIn();
}
</code></pre>

<p>I also tried an example from the msdn blog page about the expected exceptions (<a href=""https://blogs.msdn.microsoft.com/csell/2006/01/14/expectedexception-might-not-be-what-youve-expected/"" rel=""nofollow noreferrer"">https://blogs.msdn.microsoft.com/csell/2006/01/14/expectedexception-might-not-be-what-youve-expected/</a>), but it also stopped at the exception and after the test failed.
It happened with this simple example code: </p>

<pre><code>[TestMethod, ExpectedException( typeof ( ApplicationException ) ) ]
public void ut1()
{
   throw new ApplicationException();
}
</code></pre>

<p>I think I should check my preferencies, but have no idea what should I search for.</p>

<p>Thanks for any advice!</p>
",https://stackoverflow.com/questions/41894530/c-exception-handling-under-unit-testing-doesnt-work,"['c#', 'unit-testing', 'visual-studio-2015', 'exception']",582,FALSE,1,0
How to make material components work with Karma in unit testing Angular,"<p>I have an angular CLI project set up. I've made a form that uses angular material components, like <code>&lt;md-card&gt;</code>.</p>

<p>I'm just starting out with writing my first Karma/Jasmine unit test, following the steps in the <a href=""https://angular.io/docs/ts/latest/guide/testing.html#!#simple-component-test"" rel=""noreferrer"">angular docs</a>.</p>

<p>This is my component template:</p>

<pre><code>&lt;md-card [ngClass]=""'dialog-card'""&gt;
&lt;md-card-title [ngClass]=""'dialog-title'""&gt;
    {{title}}
&lt;/md-card-title&gt;
&lt;md-card-content&gt;

    &lt;form (ngSubmit)=""login()"" #loginForm=""ngForm""&gt;

        &lt;md-input-container class=""md-block""&gt;
            &lt;input md-input [(ngModel)]=""user.email"" 
                name=""userEmail"" type=""email"" placeholder=""Email"" 
                ngControl=""userEmail"" 
            required&gt;
        &lt;/md-input-container&gt;
        &lt;br&gt;

        &lt;md-input-container class=""md-block""&gt;
            &lt;input md-input [(ngModel)]=""user.password"" 
                name=""userPassword"" type=""password"" placeholder=""Password"" 
                ngControl=""userPassword"" 
            required&gt;
        &lt;/md-input-container&gt;
        &lt;br&gt;

        &lt;tm-message msgText=""Wrong username or password"" *ngIf=""showError""&gt;&lt;/tm-message&gt;
        &lt;br&gt;


        &lt;button md-button type=""submit"" [disabled]=""!loginForm.form.valid""&gt;Login&lt;/button&gt;

        &lt;p (click)=""openForgotPasswordModal()""&gt;Forgot Password?&lt;/p&gt;

    &lt;/form&gt;

&lt;/md-card-content&gt;
</code></pre>

<p></p>

<p>This is my karma spec:</p>

<pre><code>import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By }              from '@angular/platform-browser';
import { DebugElement }    from '@angular/core';
import { MaterialModule, MdDialogRef, MdDialog  } from '@angular/material';
import { FormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';

import { TmLoginComponent } from './tm-login.component';
import { TmMessageComponent } from '../../shared/components/tm-message.component';
import { UserAuthenticationService } from '../login/user-authentication.service';

describe('TmLoginComponent (inline template)', () =&gt; {

let comp: TmLoginComponent;
let fixture: ComponentFixture &lt; TmLoginComponent &gt; ;
let de: DebugElement;
let el: HTMLElement;

beforeEach(() =&gt; {
    TestBed.configureTestingModule({
        declarations: [TmLoginComponent, TmMessageComponent], // declare the test component
        imports: [MaterialModule, FormsModule,
            RouterTestingModule.withRoutes(
                [{
                    path: 'login',
                    component: TmLoginComponent
                }, ])
        ],
        providers: [UserAuthenticationService],

    });

    fixture = TestBed.createComponent(TmLoginComponent);

    comp = fixture.componentInstance; // TmLoginComponent test instance

    // query for the title &lt;h1&gt; by CSS element selector
    de = fixture.debugElement.query(By.css('.title'));
    el = de.nativeElement;
});

    it('should display original title', () =&gt; {
        fixture.detectChanges();
        expect(el.textContent).toContain(comp.title);
    });
});
</code></pre>

<p>At this point, I'm just trying to run the basic unit test that the title is being displayed properly.</p>

<p>However, I'm getting a lot of material specific errors. Like</p>

<blockquote>
  <p>No provider for MdDialog.</p>
</blockquote>

<p>I'm opening an md Dialog on clicking a link. THe code is in the (fairly long) .ts file, but that's not the issue here.</p>

<p>Where would I add MdDialog in the testbed? If I add it to providers, I get the error: ""no provider for overlay"". I don't know how to fix that.</p>

<p>Is there any way I can configure karma to include all material components at start?</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/41484008/how-to-make-material-components-work-with-karma-in-unit-testing-angular,"['javascript', 'angular', 'angular-material', 'karma-jasmine', 'angular-cli']",28407,TRUE,27,3
Deadlock when unit testing with Algolia Android client,"<p>I am trying to use <code>searchAsync</code> from algolia in a JUnit test, but it ends in a deadlock as the search results are not coming back. Here is my code:</p>

<pre><code>    final Index index = AlgoClient.initIndex(""contacts"");

    Query query = new Query();

    query.setHitsPerPage(100);

    CountDownLatch signal = new CountDownLatch(1);

    index.searchAsync(query, new CompletionHandler() {

        @Override
        public void requestCompleted(JSONObject content, AlgoliaException e) {

           signal.countDown();
        });

    signal.await();
</code></pre>
",https://stackoverflow.com/questions/42543288/deadlock-when-unit-testing-with-algolia-android-client,"['android', 'unit-testing', 'testing', 'junit', 'algolia']",107,FALSE,2,1
Angular (Typescript) Unit Testing - ASP.Net Core MVC SPA,"<p>I am developing a project which started life as an ASP.Net Core MVC SPA Template in Visual Studio 2015. I used the Visual Studio Karma Test Adapter with no problems for my Angular (Typescript) unit testing, but no matter what I tried I could not get NUnit to recognise my C# unit tests for the Web API and early Domain Model code. I tried to add a separate Test Project with no success and I also created unit test files within the same, single, project with no success.</p>

<p>At some point I knew I should migrate the code to Visual Studio 2017, as I feel that the new IDE will prove to be beneficial as the project develops, so I thought I would do it now and see if it solves my unit testing problems. Visual Studio's migration process didn't go well so I decided to start from scratch again.</p>

<p>I ran <code>dotnet new angular</code> to create a clean solution which I opened in VS 2017. It appears that the Visual Studio Karma Test Adapter does not work with VS 2017 yet, so for the Typescript (Jasmine) testing that left me with Chutzpah. No matter what I try I cannot write the simplest of Jasmine tests and have the Visual Studio Test Explorer recognise it (let alone run the test). I haven't even begun to look at the C# Unit Testing yet.</p>

<p>Can anyone else get a Jasmine Unit Test to be recognised and run in the VS Test Explorer from a clean <code>dotnet new angular</code> solution, I would be very grateful for some advise.</p>
",https://stackoverflow.com/questions/45075663/angular-typescript-unit-testing-asp-net-core-mvc-spa,"['unit-testing', 'visual-studio-2017', 'chutzpah']",895,FALSE,1,0
Vue unit testing - textContent doesn&#39;t contain expected propsData,"<p>Here is my component:</p>

<pre><code>&lt;template&gt;
  &lt;div&gt;
    {{serviceConfig.name}}
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
  props: ['serviceConfig']
}
&lt;/script&gt;
</code></pre>

<p>In my test, I am setting serviceConfig like this:</p>

<pre><code>    it(`should render serviceConfig`, () =&gt; {
    const Constructor = Vue.extend(TestMe2);
    const comp = new Constructor({
        propsData: {
            serviceConfig: '{ ""name"": ""Apple"" }'
        }
    }).$mount();

    expect(comp.serviceConfig).to.equal('{ ""name"": ""Apple"" }'); // successfull
    expect(comp.$el.textContent).to.contain('Apple'); // unsuccessfull

});
</code></pre>

<p>However, if I change my template so that I am rendering {{serviceConfig}} instead of serviceConfig.name, it works, but not what I want (since I just want the name, i.e. 'Apple'). </p>
",https://stackoverflow.com/questions/45486452/vue-unit-testing-textcontent-doesnt-contain-expected-propsdata,"['javascript', 'vue.js', 'vuejs2', 'karma-mocha']",274,TRUE,1,1
"Unit Testing Hibernate with DB, test returns nullpointerexception","<p>I wrote Rest Api with ORM (Hibernate) and now I want to test that service logic.
I am trying to Mock entity of my DB but I don't have spectacular results. 
My choice was to get this with Mockito, but now I've got doubts about that.
Generally I get NullPointerException from test I wrote. Should I wrote Junit tests in another way (different way to 'mock' that DB) or I don't understand Hibernate?</p>

<p>Here is my code:
Test class</p>

<pre><code>public class ItemServiceImplTest {

@Spy
private ItemServiceImplementation itemServImpl;

@Mock
private BasketRepository basketRepository;
@Mock
private ItemRepository itemRepository;
@Mock
private Basket basket;
@Spy
private Item item;

@Before
public void setupMock() {

    MockitoAnnotations.initMocks(this);
    itemServImpl = new ItemServiceImplementation();
    itemServImpl.setItemRepository(itemRepository);
    itemServImpl.setBasketRepository(basketRepository);

}


@Test
public void testShowBasket() {
    Iterable&lt;Basket&gt; element = basketRepository.findAll();

    when(itemServImpl.showBasket()).thenReturn(element);

    Iterable&lt;Basket&gt; elementOne = itemServImpl.showBasket();

    assertThat(elementOne, is(equalTo(element)));
}


@Test
public void testAddToBasketStringInt() {
    Item a = new Item(""A"", 40, 70, 3);
    Basket testObjOne = new Basket(3, 70, a);

    when(itemServImpl.addToBasket(""A"", 3)).thenReturn((Iterable&lt;Basket&gt;) basketRepository.save(testObjOne));

    Iterable&lt;Basket&gt; zzz = itemServImpl.addToBasket(""A"", 3);

    assertThat(zzz, is(equalTo(testObjOne)));
}
</code></pre>

<p>Models</p>

<pre><code>@Entity
public class Item {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;
private String name;
private int price;
private int specialPrice;
private int qtyToDiscount;

public Item(){};



public Item(String name, int price, int specialPrice, int qtyToDiscount) {

    this.name = name;
    this.price = price;
    this.specialPrice = specialPrice;
    this.qtyToDiscount = qtyToDiscount;
}

@Entity
public class Basket {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long orderId;
private int quantity;
private int cost;



@OneToOne
@JoinTable(name = ""BASKET_ORDERS"", joinColumns = { @JoinColumn(name = ""ORDER_ID"") }, inverseJoinColumns = { @JoinColumn(name = ""ID"") })
private Item item;

public Basket() {
}

public Basket(int quantity, int cost,Item items) {

    this.quantity = quantity;
    this.cost = cost;
    this.item = items;
}
</code></pre>

<p>Service</p>

<pre><code>@Service(""itemService"")
@Transactional
public class ItemServiceImplementation implements ItemCRUDService, ItemCostService, ItemFindService {



public static final Logger logger = LoggerFactory.getLogger(ItemServiceImplementation.class);

@Autowired
public void setItemRepository(ItemRepository itemRepository) {
    this.itemRepository = itemRepository;
}
@Autowired
public void setBasketRepository(BasketRepository basketRepository) {
    this.basketRepository = basketRepository;
}

private BasketRepository basketRepository;

private ItemRepository itemRepository;


public Iterable&lt;Basket&gt; showBasket() {

    return basketRepository.findAll();
}


public Iterable&lt;Basket&gt; addToBasket(String name, int qty) {

        if (basketRepository.exists(itemRepository.findOne(findItem(name).getId()).getId())==false) { 

        logger.info(""add to empty list"");
        basketRepository.save(new Basket(qty, itemCost(name, qty), findItem(name)));
        logger.info(""adding"");
    }

    modifyOrder(findItem(name).getId(), qty);
    itemCost(name, qty);
    logger.info(""modify"");

    return showBasket();

}
public Item findItem(String name) {

    for (Item item : itemRepository.findAll()) {
        if (item.getName().equals(name)) {
            return item;
        }
    }
    return null;
}
public int itemCost(String name, int qty) {

    int price = 0;

    int modulo = qty % findItem(name).getSpecialPrice();

    price = findItem(name).getPrice() * modulo
            + findItem(name).getSpecialPrice() * ((qty - modulo) / `findItem(name).getSpecialPrice());`

    return price;

}
</code></pre>
",https://stackoverflow.com/questions/46778265/unit-testing-hibernate-with-db-test-returns-nullpointerexception,"['java', 'hibernate', 'unit-testing', 'spring-boot', 'mockito']",272,FALSE,1,1
Unit Testing Components that Uses an Akka Actor,"<p>First of all, I am not asking how to unit test an Akka Actor. I know the techniques to do that. My problem is slightly different.</p>

<p>I am developing a Scala program, let's call it the <code>client</code>, that does not use Akka Actors. However, the program uses a library, let's call it the <code>server</code>, whose interface is implemented using an Akka Actor. </p>

<p>Then, through the <em>ask pattern</em>, the <code>client</code> interacts with the <code>server</code>.</p>

<pre><code>// This is the client program
class Client(uri: String) {
  implicit val context: ActorSystem = ActorSystem(""client-actor-system"")
  private val mainActor = context.actorSelection(uri)

  def connect: Future[SomeClass] = {
    implicit val timeout: Timeout = Timeout(5 seconds)
    (mainActor ? Connect()).mapTo[CreationResponse]
  }
}
</code></pre>

<p>Now, I want to write down some unit tests for <code>Client</code> class. Unit testing means to test a class in isolation. Every external dependency should be mocked.</p>

<p>How can I mock the reference to <code>mainActor</code> inside <code>Client</code> class? How can I inject in the actor system a mock actor for <code>mainActor</code>?</p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/46482716/unit-testing-components-that-uses-an-akka-actor,"['scala', 'unit-testing', 'akka', 'akka-testkit']",706,TRUE,1,1
How to perform Unit Testing on complicated functions,"<p>I have a class XYZ which has some function whivh I need to test using Catch Unit-testing. I am in a state of confusion what can be the possibility to test the function. Can anyone help on this?</p>

<p>Test code is below:</p>

<pre><code>UaStatus XYZ::encodeVariantAsBinary(UaVariant variant, UaByteString *dst)
    {
        UaStatus status;
        status = m_encoder.create();
    if (status.isGood())
    {
        status = m_encoder.writeVariant(""value"", variant);
        if (status.isGood())
        {
            status = m_encoder.getBuffer(*dst);
        }
    }

    return status;
}
</code></pre>

<p>Br/RG</p>
",https://stackoverflow.com/questions/43347642/how-to-perform-unit-testing-on-complicated-functions,"['c++', 'unit-testing', 'testing', 'catch-unit-test']",77,FALSE,1,0
Unit Testing a Client-Server Application in Java,"<p>I'm working on a simple client-server application, and I'm supposed to initialize my client and server objects in separate threads. The server contains a database of all of the courses in some specific departments at my university, and the GET request gets all of the classes in the requested department and sends it back to the client. While I was able to test everything perfectly fine in a main method, unit testing was just not working. Below is my code for the unit test:</p>

<pre><code>import client.Client;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import server.Server;


public class ClientServerTest {
    private static String file = """";

    @BeforeClass
    public static void setFile(){
        file = System.getProperty(""file"");
    }

    @Before
    public void startServerTest(){
        Thread serverThread = new Thread(() -&gt; {
            new Server(file);
        });
        serverThread.start();
    }

   @Test
   public void getTest(){
        Client client = new Client();
        Assert.assertTrue(client.submitRequest(""GET COM""));
        Assert.assertTrue(client.submitRequest(""GET MAT""));
        Assert.assertTrue(client.submitRequest(""GET BIO""))
    }
}
</code></pre>

<p>When I run the test, the server test passes, I get the following output for the getTest() test:</p>

<pre><code>java.net.ConnectException: Connection refused: connect
</code></pre>

<p>I've been looking around trying to find the best way to get unit tests to work with threads, but I can't seem to figure it out. Any help would be most appreciated.</p>
",https://stackoverflow.com/questions/46521297/unit-testing-a-client-server-application-in-java,"['java', 'multithreading', 'sockets', 'junit']",5218,TRUE,1,2
Avoid Unit Testing in Unchanged Modules in Maven,"<p>I have a multi-module maven project and inside each module, there are some unit tests.</p>

<p>If I change the source code in one module and do a ""mvn package"", the tests in other modules are also executed.</p>

<p>I know that mvn ""package"" life cycle performs all the life cycles before ""package""(compile, test, etc.).</p>

<p>But is there a smart way, that this can be avoided?</p>
",https://stackoverflow.com/questions/43916601/avoid-unit-testing-in-unchanged-modules-in-maven,"['java', 'maven', 'unit-testing']",118,FALSE,1,2
Not able to use moq in unit testing,"<p>i just started with unit testing with moq object, i am not sure if i am doing this right or not, please help !!</p>

<pre><code>Public Class Mrr: IMrr
{ 

   public int Delete(double obj)
   {
        int rtcode = somefunction(obj);// retreiving some code from function
        int DeleteMrr= DeleteFunction(rtcode);  // delete function executes here          
        return 0;
   }

}
</code></pre>

<p>here is the interface</p>

<pre><code>public interface IMrr
{
    int Delete(double obj);
}
</code></pre>

<p>and my test method is something like this.</p>

<pre><code>[TestMethod()] 
public void RetrieveSaveDeleteMRR()
{      
    var FakeObject = new Moq.Mock&lt;IMrr&gt;();
    FakeObject.Setup(x =&gt; x.Delete(It.IsAny&lt;int&gt;())).Returns(0);
    var Res = FakeObject.Object.Delete(10);
}
</code></pre>

<p>this is not going to the actual function to execute that method, it suppose to go there to the method or not. i am not sure. </p>
",https://stackoverflow.com/questions/42826046/not-able-to-use-moq-in-unit-testing,"['c#', 'asp.net', 'unit-testing', 'dependency-injection', 'moq']",79,TRUE,1,2
Unit testing user interaction in an angular2 component,"<p>I've recently started learning angular2, and I thought I'd try and write a combobox component similar to select2. Here's a simplified version of the component:</p>

<pre><code>@Component({
    selector: 'combobox',
    template: `
        &lt;div class=""combobox-wrapper""&gt;
            &lt;input type=""text""&gt;&lt;/input&gt;
            &lt;button class=""toggle-button""&gt;&lt;/button&gt;
        &lt;/div&gt;
        &lt;div *ngIf=""isDropdownOpen"" class=""dropdown""&gt;
            &lt;div *ngFor=""let option of options; let index = index;""
                class=""option""
                [class.focused]=""focusedIndex==index""&gt;
                {{option.label}}
            &lt;/div&gt;
        &lt;/div&gt;
    `
})
export class ComboboxComponent {
    @Input() options: any[] = [];
    isDropdownOpen: boolean = false;
    focusedIndex: number = 0;
}
</code></pre>

<p>I'm struggling when it comes to writing unit tests involving user interaction. For example, I want the user to be able to navigate the list of options by using the up and down keys on the keyboard. The way I see it, I have two options.</p>

<p><strong>Option 1:</strong></p>

<pre><code>describe('when the dropdown is open and the user presses the ""UP"" key', () =&gt; {
    it('should focus the first available preceeding option', () =&gt; {
        const button = fixture.debugElement.query(By.css('.toggle-button'));
        const input = fixture.debugElement.query(By.css('input'));

        button.triggerEventHandler('mousedown', {});
        input.triggerEventHandler('keydown', { key: 'ArrowDown' });
        input.triggerEventHandler('keydown', { key: 'ArrowDown' });
        input.triggerEventHandler('keydown', { key: 'ArrowUp' });
        fixture.detectChanges();

        const options = fixture.debugElement.queryAll(By.css('.option'));
        expect(options[1].nativeElement.className).toContain('focused');
    });
});
</code></pre>

<p><strong>Option 2:</strong></p>

<pre><code>describe('when the dropdown is open and the user presses the ""UP"" key', () =&gt; {
    it('should focus the first available preceeding option', () =&gt; {
        const combobox = fixture.componentInstance;
        combobox.isDropdownOpen = true;
        combobox.focusedIndex = 2;

        input.triggerEventHandler('keydown', { key: 'ArrowUp' });
        fixture.detectChanges();

        expect(combobox.focusedIndex).toBe(1);
    });
});
</code></pre>

<p>Neither option feels right. In the first case I'm making assumptions about behaviour that is not part of the test itself - namely that clicking the ""toggle"" button will open the dropdown, and that pressing the ""ArrowDown"" key will focus the next option on the list. </p>

<p>In the second case I'm accessing properties that are not part of the component's public interface (@Inputs and @Outputs), and the test itself requires detailed knowledge about the actual implementation.</p>

<p>How should I approach this?</p>
",https://stackoverflow.com/questions/42304133/unit-testing-user-interaction-in-an-angular2-component,"['unit-testing', 'angular', 'jasmine']",1716,FALSE,1,0
How does Unit Testing in functional languages work?,"<p>I am wondering how to write good unit tests in a functional language. Testing very basic functions is not that hard but I do not understand how I should test function that use other functions.</p>

<p>For example:<br>
In an object oriented world I test the very basic functionality on its own and just mock it when I test the more complex function</p>

<pre><code>class Example {
    internal var adder: Adder = AdderImpl()
    internal var multiplier: Multiplier = MultiplierImpl()

    fun execute(n: Int, m: Int): Int =
        if (n &lt; m) adder.add(n, m)
        else multiplier.multiply(n, m) 
}
</code></pre>

<p>if <code>Adder.add</code> and <code>Multiplier.multiply</code> are tested, I can test <code>Example.execute</code> by just mocking these and expect <code>adder</code> to be called for <code>n&lt;m</code> and <code>multiplier</code> to be called otherwise.</p>

<p>But how would I do this in a functional language? I could have easy to test <code>add</code> and <code>multiply</code> functions and compose my <code>execute</code> from them</p>

<pre><code>execute : Int -&gt; Int -&gt; Int
execute = 
    if n &lt; m then add n m
    else multiply n m
</code></pre>

<p>Now to test <code>execute</code> I cannot simply expect <code>add</code> or <code>multiply</code> to be called since I cannot mock them. I would actually have to do all tests I have written for <code>add</code> already and execute them if <code>n&lt;m</code> and do all tests for <code>multiply</code> otherwise. This means I tested these two functions two times.</p>

<p>So what is the correct functional way of testing the smaller functions and for the bigger function assume they work and just check if they were called if the correct conditions are met?</p>
",https://stackoverflow.com/questions/47975467/how-does-unit-testing-in-functional-languages-work,"['unit-testing', 'functional-programming']",643,TRUE,1,1
NativeScript - can&#39;t import mocking libraries when unit testing,"<p>I want to write some unit tests with mocks for an app I'm working on. </p>

<ul>
<li><code>tns create test_ns --tsc</code></li>
<li><code>npm install -D sinon # library for mocking; I can't import it</code></li>
<li><code>npm install -D underscore # a js lib that I can import, for reference</code></li>
<li><code>tns test init --framework=jasmine</code></li>
<li><code>tns test android</code></li>
</ul>

<p>And here's the <code>test/example.js</code>:</p>

<pre><code>var sinon = require('sinon')
describe(""A suite"", function() {
  it(""contains spec with an expectation"", function() {
    expect(true).toBe(true);
  });
});
</code></pre>

<p>That's my <code>karma.conf.js</code> <a href=""https://gist.github.com/jorotenev/d316a5425b8a937945cc9a4f741e9b10"" rel=""nofollow noreferrer"">link</a><br>
The </p>

<p>The <code>tns test</code> command fails with <code>Error: com.tns.NativeScriptException: Failed to find module: ""sinon"", relative to: app/tns_modules/</code></p>

<p>I installed the <code>karma-sinon</code> package too - no difference.</p>

<p>I came across this issue on the NativeScript repo <a href=""https://github.com/NativeScript/NativeScript/issues/1956"" rel=""nofollow noreferrer"">#1956</a> where they suggest to set up the problematic npm package in a different module and then import it. I tried this, but the <code>require('sinon')</code> still barks with the same error.</p>

<p>I don't insist on using sinon - I just need a mocking js library. I tried with <code>testdouble</code> - I got the same  ""Failed to find module"". </p>

<p>Suggestions?</p>
",https://stackoverflow.com/questions/46981311/nativescript-cant-import-mocking-libraries-when-unit-testing,"['unit-testing', 'nativescript', 'sinon']",236,FALSE,1,1
unit testing login Api controller with form authentication,"<p>I am writing unit test case for Web API application. where I have login API controller. Login controller use Form authentication. </p>

<pre><code>_tokenServices = (ITokenServices)_unityResolver.GetService(typeof(ITokenServices)); 

AccountsApiController accountsApiController = new 
AccountsApiController(_tokenServices);

LoginUser loginUser = new LoginUser();

loginUser.UserName = ""sampluser"";

loginUser.Password = ""samplePassword"";

controller.Request = new HttpRequestMessage();

controller.Configuration = new HttpConfiguration();

accountsApiController.ControllerContext = new System.Web.Http.Controllers.HttpControllerContext();

HttpResponseMessage accountApiControllerResponse = accountsApiController.Login(loginUser);

Assert.IsTrue(accountApiControllerResponse.StatusCode == System.Net.HttpStatusCode.OK);
</code></pre>

<p>If i run the unit test case i am getting null exception in the following line</p>

<blockquote>
  <p>FormsAuthentication.SetAuthCookie(loginUser.UserName,
  createPersistentCookie: false);</p>
</blockquote>
",https://stackoverflow.com/questions/42228062/unit-testing-login-api-controller-with-form-authentication,"['unit-testing', 'asp.net-web-api', 'asp.net-membership']",594,FALSE,1,0
onNext not getting called unit testing RxCocoa Driver,"<p>I'm attempting to write a unit test for <code>Driver</code> from RxCocoa library. Here's my simplified implementation code:</p>

<pre><code>struct LoginViewModel {

    var username: Driver&lt;String?&gt;!
    var password: Driver&lt;String?&gt;!
    var loginTaps: Driver&lt;Void&gt;!

    func login() -&gt; Driver&lt;LoginResult&gt; {
        let credentials = Driver.combineLatest(username, password) { ($0, $1) }
        let latestCredentials = loginTaps.withLatestFrom(credentials)

        return latestCredentials.flatMapLatest { (username, password) in
            .just(.success)
        }
    }
}
</code></pre>

<p>And here's the Quick/Nimble unit test I'm attempting to pass:</p>

<pre><code>let disposeBag = DisposeBag()
var capturedLoginResult = LoginResult.failed

loginViewModel.username = Driver.just(""some username"")
loginViewModel.password = Driver.just(""some password"")
loginViewModel.loginTaps = Driver.just()

loginViewModel.login().drive(onNext: { loginResult in
    capturedLoginResult = loginResult
}).addDisposableTo(disposeBag)

expect(capturedLoginResult == .success)
</code></pre>

<p>Above <code>expect</code> says that <code>capturedLoginResult</code> is still <code>.failed</code>. It appears as though element from <code>return latestCredentials.flatMapLatest { (username, password) in .just(.success) }</code> is not getting received by the <code>.drive(onNext: )</code> in the test.</p>

<p>If the implementation of <code>login</code> is just:</p>

<pre><code>func login() -&gt; Driver&lt;LoginResult&gt; {
    return .just(.success)
}
</code></pre>

<p>The test passes.</p>

<p>Any thoughts on what's happening here? Thanks!</p>
",https://stackoverflow.com/questions/42538423/onnext-not-getting-called-unit-testing-rxcocoa-driver,"['swift', 'rx-swift', 'rx-cocoa']",917,TRUE,1,1
Python unit testing: assert on json is broken?,"<p>So I recently started to get into the topic of unit testing in the python world, and I got stuck on the following issue:</p>

<pre><code>def test_correct_object_on_queue(self):
    self.logger.log('Starting test for correct object state on queue')

    called_with_args = False

    icc = Icc(self.mock_io, '0', self.logger, Queue())

    icc.center_module()

    calls = icc.dxl_io.set_goal_position.mock_calls

    for c in calls:
        # print c
        if c == call({'0': 0}):
            called_with_args = True
            break

    assert called_with_args == True
</code></pre>

<p>Here is the definition of the center_module:</p>

<pre><code>def center_module(self):
    self.add_to_queue(self.dxl_io.set_goal_position, [{self.servo_ids[0]: 0}])
</code></pre>

<p>If I uncomment the <code># print c</code> line, this test will pass.
Here is what my calls contain:
<code>[call.__str__(), call.__str__(), call.__nonzero__(), call({'0': 0}), call.__str__()]</code></p>

<p>You might ask why don't I use something built in method related to my purpose, such as <code>assert_called_with</code> of the <code>Mock</code> (and thus, <code>MagicMock</code>) class. Well, during debugging I noticed how they can't work with complex data structures such as a dictionary (the <code>expected</code> variable in the assert method will be a tuple:
<code>&lt;type 'tuple'&gt;: (({'0': 0},), {})</code>
and it returns this as actual: <code>call({'0': 0})</code>, obviously their comparison will fail), and following the suggestion <a href=""https://stackoverflow.com/questions/28417805/assert-mocked-function-called-with-json-string-in-python"">here</a> I wanted to go with the approach described above.</p>

<p>My question (aside how to fix?) is why is the test only finding the call with the args if I ask it to print all the calls?</p>
",https://stackoverflow.com/questions/43684182/python-unit-testing-assert-on-json-is-broken,"['json', 'python-2.7', 'unit-testing']",197,FALSE,1,0
IOption pattern - unit testing and passing through layers,"<p>I have some code (C# .Net Core WebAPI) I wish to unit test but need some help as the dependencies looks a bit odd to me.</p>

<p>The code came from some sample code (I found on the web) for accessing MongoDb using .Net Core WebAPI, which initially looked ok, until now..  </p>

<p>Both the DbContext and the Repository have the same dependency - and the Repository just passes it through to the DbContext anyway - as the Repository instantiates the DbContext:</p>

<pre><code>  public class LogItemRepository : ILogItemRepository
  {
    private readonly DbContext _context = null;

    public LogItemRepository(IOptions&lt;DbSettings&gt; settings)
    {
      _context = new DbContext(settings);
    }
</code></pre>

<p>...</p>

<pre><code>  public class DbContext
  {
    private readonly IMongoDatabase _database = null;

    public DbContext(IOptions&lt;DbSettings&gt; settings)
    {
      var client = new MongoClient(settings.Value.ConnectionString);
      if (client != null)
        _database = client.GetDatabase(settings.Value.Database);
    }

    public IMongoCollection&lt;LogItem&gt; LogItemsCollection
    {
      get
      {
        return _database.GetCollection&lt;LogItem&gt;(""LogItem"");
      }
    }
  }
}
</code></pre>

<p>I'm not familiar with the <a href=""https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration#options-config-objects"" rel=""nofollow noreferrer"">Options pattern</a>, but from a quick read it looks good.  But I'm not convinced it's good practice to make child dependencies (the options), dependencies of the parent (as in the example above).</p>

<p>Instead should I be making an interface, IDbContext, and using that as the dependency for the repository?   That's what I would have done in the past - but not sure if this breaks the options pattern.</p>

<p>I suspect this is subjective, but I'd like some others input.</p>

<p>Thanks
Tim</p>
",https://stackoverflow.com/questions/45022964/ioption-pattern-unit-testing-and-passing-through-layers,"['c#', 'unit-testing', 'asp.net-core', '.net-core', 'repository-pattern']",620,TRUE,1,1
NServiceBus unit testing: ExpectSend not fulfilled when bus.Send(),"<p>I'm using NServiceBus5.2.21, NServiceBus.Testing5.2.1, Moq4.0.1, NUnit3.2.0</p>

<p>Problem: <code>ExpectSend&lt;&gt;</code> keeps failing with </p>

<blockquote>
  <p>""ExpectedSendInvocation not fulfilled"" </p>
</blockquote>

<p>when <code>_bus.Send()</code> is called correctly. Not sure what I'm missing here.</p>

<p>Test:</p>

<pre><code>[TestFixture]
public class GeneralLedgerHanlderTest
{
    private Mock&lt;ISendGeneralLedgerToSap&gt; _toSapMock;

    [SetUp]
    public void Setup()
    {
        _toSapMock = new Mock&lt;ISendGeneralLedgerToSap&gt;();
        _toSapMock.Setup(x =&gt; x.SendSoapMessageToSap(It.IsAny&lt;GeneralLedgerSapCommand&gt;()));
    }

    [Test]
    public void HandlerMustSendAuditLog()
    {
       NServiceBus.Testing.Test.Handler(bus =&gt; new GeneralLedgerToSapHandler(bus, _toSapMock.Object))
            .ExpectSend&lt;GeneralLedgerAuditCommand&gt;(command =&gt; command.SagaReferenceId == ""ab"")
            .OnMessage(new GeneralLedgerSapCommand { SagaReferenceId = ""ab"" });
    }
}
</code></pre>

<p>Handler:</p>

<pre><code>public class GeneralLedgerToSapHandler : IHandleMessages&lt;GeneralLedgerSapCommand&gt;
{
    private readonly IBus _bus;
    private readonly ISendGeneralLedgerToSap _sendSoapToSap;

    public GeneralLedgerToSapHandler(IBus bus, ISendGeneralLedgerToSap sendSoapToSap)
    {
        _bus = bus;
        _sendSoapToSap = sendSoapToSap;
    }

    public void Handle(GeneralLedgerSapCommand message)
    {
        _sendSoapToSap.SendSoapMessageToSap(message);

        var goodsReceiptAuditCommand = new GeneralLedgerAuditCommand
        {
            SagaReferenceId = message.SagaReferenceId,
        };

        _bus.Send(EndPointName.SpmAuditLogService, goodsReceiptAuditCommand);
    }
}
</code></pre>
",https://stackoverflow.com/questions/47170203/nservicebus-unit-testing-expectsend-not-fulfilled-when-bus-send,"['c#', 'unit-testing', 'nunit', 'moq', 'nservicebus5']",361,TRUE,1,1
Angular unit testing promise reject without a catch,"<p>We have the following test:</p>

<p><code>""should not call 'getCustomers' when 'getAvailableYears' throws""</code></p>

<p>This used to work if we had the <code>catch</code> in our <code>getAvailableYears</code>, but now we don't need the catch anymore as we have a global error handling.</p>

<p>This is how <code>getAvailableYears</code> looks like:</p>

<pre><code>this.service.getAvailableYears().then((availableYears) =&gt; {
    this.years = availableYears;
    this.loadCustomers();
});
</code></pre>

<p>That is the test, which used to work when we have the <code>catch</code>:</p>

<pre><code>it(""should not call 'getCustomers' when 'getAvailableYears' throws"", fakeAsync(() =&gt; {
    // Arrange
    getAvailableYearsSpy = spyOn(service, ""getAvailableYears"").and.returnValue(Promise.reject(""reason""));
    getCustomersSpy = spyOn(service, ""getCustomers"").and.returnValue(Promise.resolve(createCustomersTestData()));

    // Act
    fixture.detectChanges();

    tick();

    // Assert
    expect(getCustomersSpy).not.toHaveBeenCalled();
}));
</code></pre>

<p>Now I get the following error:</p>

<blockquote>
  <p>Error: Uncaught (in promise): reason</p>
</blockquote>

<p>How do I work with <code>reject</code> in case I don't have a <code>catch</code>? How do I test that something cannot be called if a promise has been rejected?</p>
",https://stackoverflow.com/questions/45222820/angular-unit-testing-promise-reject-without-a-catch,"['angular', 'jasmine']",894,TRUE,1,1
Android Studio: Gradle Build Unit Testing dependencies issue,"<p>I am a novice to Android development. I am looking into 'how to set up a test environment in Android Studio'. So, here is my question;</p>

<p>As per the official Android training source (<a href=""https://developer.android.com/training/testing/unit-testing/local-unit-tests.html"" rel=""nofollow noreferrer"">https://developer.android.com/training/testing/unit-testing/local-unit-tests.html</a>) says, In your app's top-level <em>build.gradle</em> file, you need to specify these libraries as dependencies:</p>

<p><a href=""https://i.stack.imgur.com/UdrLm.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/UdrLm.jpg"" alt=""enter image description here""></a>  </p>

<p>But in my case, am using Android Studio Version 2.2.3 and it shows two <em>build.gradle</em> files i.e., <em>build.gradle ( Project: name )</em> and <em>build.gradle ( Module: app )</em>, out of which one already had the dependencies mentioned by default and the other doesn't. Please look at following pictures for understanding.  </p>

<p><strong>build.gradle ( Project: name )</strong>
<a href=""https://i.stack.imgur.com/LG9s5.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/LG9s5.jpg"" alt=""enter image description here""></a></p>

<p><strong>build.gradle ( Module: app )</strong>
<a href=""https://i.stack.imgur.com/0vzxa.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/0vzxa.jpg"" alt=""enter image description here""></a></p>

<p><strong>Where should the dependencies be mentioned?</strong></p>
",https://stackoverflow.com/questions/41636095/android-studio-gradle-build-unit-testing-dependencies-issue,"['android', 'unit-testing', 'android-studio', 'android-gradle-plugin', 'junit4']",357,FALSE,1,0
Visual studio live unit testing not work properly,"<p>When I start live unit testing in Visual Studio 2015 (15.4.2) I have a message in the output window saying </p>

<blockquote>
  <p>Build completed(failed)</p>
</blockquote>

<p>But if I try to build the the unit test project separately it will build without any warnings and errors.</p>

<p>All in all it says ""Live unit tests started"". But i don't get ""blue"" lines which indicate missing unit testing.</p>
",https://stackoverflow.com/questions/47454421/visual-studio-live-unit-testing-not-work-properly,"['visual-studio', 'unit-testing', 'visual-studio-2015']",713,TRUE,1,3
unit testing a method called from another class,"<p>I am new to Android unit testing and I am using Mockito to do it.</p>

<p>I want to test my method which has a method from another class. I want to stub that method so that it should not be called. I am using <code>doReturn().when()</code> so that original method is not called but it is calling the original method.</p>

<p>Here is my code:</p>

<pre><code>doReturn(true).when(myclass1mock).methodofclass1();
boolean a = myclass1mock.methodofclass1(); //here it return true
class2spy.methodofclass2(anyvalue);
</code></pre>

<p>The method I am testing is:</p>

<pre><code>public class2 {
    public void methodofclass2(Value) {
        boolean value = class1.methodofclass1(); //here I don't want to call this method
    }
}
</code></pre>

<p>The problem is method of <code>class1</code> is called everytime. I want something so that <code>class1.methodofclass1()</code> is not called.</p>

<p>I am injecting using:</p>

<pre><code>@Mock
class1 myclass1mock;
@InjectMocks
class2 myclass2;
@Before
public void setUp() {
    myclass2 = new myclass2();
    class2spy = Mockito.spy(myclass2);
}
</code></pre>
",https://stackoverflow.com/questions/43933751/unit-testing-a-method-called-from-another-class,"['java', 'android', 'unit-testing', 'mocking', 'mockito']",542,TRUE,1,1
Identity Server 3 unit testing authorization code flow,"<p>I am using Identity Server 3 for implementing OAuth2 authentication.</p>

<p>I want to unit test the authorization code flow. </p>

<p>I am able to make a GET request to the authorize endpoint and get back a signin value.</p>

<p>I would like to authenticate the user to get the authorization code back and then use the code to get the access token.</p>

<p>I need some help with authenticating the user using the login link provided in a unit test.</p>
",https://stackoverflow.com/questions/45806616/identity-server-3-unit-testing-authorization-code-flow,"['unit-testing', 'oauth-2.0', 'identityserver3']",356,FALSE,1,1
AngularJS unit testing: using async/await with Jasmine,"<p>I'm trying to unit testing my Angular service using <code>async/await</code> keyword in the corresponding (Jasmine) unit tests below. The test for the native <code>Promise</code> works just fine, but I'm pretty much stuck in making the Angular <code>$q</code> counterpart work.</p>

<ul>
<li>Angular: 1.6.5</li>
<li>Jasmine: 2.7.0</li>
<li>(Headless) Chrome on MacOS: 60.x </li>
</ul>

<hr>

<pre><code>angular
  .module('asyncAwaitTest', [])
  .factory('xService', xServiceFactory);

function xServiceFactory(
  $q,
  $timeout
) {
  return {
    getXAfter1Sec() {
      return new Promise(resolve =&gt; setTimeout(() =&gt; resolve(43), 1000));
    },
    getXAfter1SecWithAngular$Q() {
      const deferred = $q.defer();

      $timeout(() =&gt; deferred.resolve(43), 1000);

      return deferred.promise;
    }
  };
}

jasmine.DEFAULT_TIMEOUT_INTERVAL = 2000;

describe('asyncAwaitTest: x service', () =&gt; {
  let $timeout;
  let xService;

  beforeEach(() =&gt; {
    module('asyncAwaitTest');

    inject(
      (
        _$timeout_,
        _xService_
      ) =&gt; {
        $timeout = _$timeout_;
        xService = _xService_;
      }
    );
  });

  it('should work', async (done) =&gt; {
    const x = await xService.getXAfter1Sec();

    expect(x).toEqual(43);

    done();
  });

  it('should work, too. but y not?!!', async (done) =&gt; {
    const xPromise = xService.getXAfter1SecWithAngular$Q();

    $timeout.flush();

    const x = await xPromise;

    expect(x).toEqual(43);

    done();
  });
});
</code></pre>

<p>Fiddle provided here: <a href=""https://jsfiddle.net/glenn/gaoh6bvc/"" rel=""nofollow noreferrer"">https://jsfiddle.net/glenn/gaoh6bvc/</a></p>

<p>I've tried Google but it doesn't give me a significant good lead 😞</p>
",https://stackoverflow.com/questions/45402943/angularjs-unit-testing-using-async-await-with-jasmine,"['javascript', 'angularjs', 'unit-testing', 'jasmine', 'async-await']",1889,TRUE,1,2
Validating Unique Keys for Unit Testing using Effort,"<p>I'm currently doing a POC for Unit Testing in an existing solution. I have been reading here and there and one library I saw that I found very interesting to do tests that involve Entity Framework is Effort (<a href=""https://effort.codeplex.com/"" rel=""nofollow noreferrer"">https://effort.codeplex.com/</a>).</p>

<p>During my first tests, Effort has been good to simulate my Database context, no weird errors were thrown, most of the operations were good, like adding a new record and incrementing my primary key when a table has identity, good at that moment, until I reached a situation that involved a table that has a Unique Key.</p>

<p>This is my current scenario:</p>

<ol>
<li><p>A Database first model.</p></li>
<li><p>The context nor the Entity doesn't have the unique key rule, so if Effort works ""In Memory"" the unique key must exist in the code so Effort takes it in the process, so I added the Unique Key in my entity manually just to test it, I added it in three attributes (fields) in my Class (Entity):</p>

<p>[Index(""UK_WhateverName"", IsUnique = true, Order = 1)]</p>

<p>[Index(""UK_WhateverName"", IsUnique = true, Order = 2)]</p>

<p>[Index(""UK_WhateverName"", IsUnique = true, Order = 3)]</p></li>
<li><p>The method has inside a try catch, inside the try is the dbcontext.SaveChanges(). In real conditions a DbUpdateException is captured when the Unique Key rule is infringed, so when that happens the method returns a -1.</p></li>
<li><p>I assumed that even if Effort is able to capture the unique key failure it probably won't throw a DbUpdateException, so I added an additional catch to capture Exception, any exception that could happen.</p></li>
<li><p>The code is working fine in real conditions, the -1 is being returned when the unique key is infringed.</p></li>
</ol>

<p>The current outcome using Effort is that the code passes without any problems, it doesn't capture the unique key failure, not even within the Exception catch, and the test saves it normally incrementing the primary key.</p>

<p>Is it possible in Effort to simulate Unique Key failures?, am I missing something?</p>

<p>Thanks in advance for any help. </p>
",https://stackoverflow.com/questions/44554908/validating-unique-keys-for-unit-testing-using-effort,"['c#', 'entity-framework', 'unit-testing', 'ef-database-first', 'effort']",485,FALSE,1,0
Angular Unit testing : this.router.myMethod is not a function,"<p>Am worrking on unit testing , under Angular 4.0.0</p>

<p>My test case is the following :</p>

<p><strong>test.spec.ts :</strong></p>

<pre><code>        // Test Suite of Que-Again features
            describe('QueueAgainComponent features', () =&gt; {

                it('should navigate', () =&gt; {
                    comp.goToPrevious(); // HERE IS THE PROBLEM
                    expect(mockRouter.navigate).toHaveBeenCalledWith(['/home/pilote'], {skipLocationChange: true});
                    sharedclientService.user.isAdviser = true;
                    comp.goToPrevious();
                    expect(mockRouter.navigate).toHaveBeenCalledWith(['/home/advisor'], {skipLocationChange: true}); 
       });
</code></pre>

<p>Under the config part i ve mocked my <strong>RouteNavigator</strong> service like the following :</p>

<pre><code>        let mockRouter = {
            navigate: jasmine.createSpy('navigate')
        };
    providers: [{provide: RouteNavigator, useValue: mockRouter}]
</code></pre>

<p>My test fails throwing tghis error :  </p>

<blockquote>
  <p>TypeError: this.router.myMethod is not a function</p>
</blockquote>

<p>The log file says that the problem points on 98:18 which is exactly this line :</p>

<p>comp.goToPrevious();</p>

<p>Therefore <strong>goToPrevious()</strong> is implemented in my component like this : </p>

<pre><code>      goToPrevious() {
        this.routeNavigator.myMethod();
      }
</code></pre>

<p>And <strong>routeNavigator</strong> refers to a custom service used to deal with custom redirection , like this :</p>

<pre><code>**Route-navigator.service.ts**
    import { LoginComponent } from '../../login/login.component';
    import { SharedclientService } from '../../service/sharedclient.service';
    import { Injectable } from '@angular/core';
    import { Router, ActivatedRoute } from '@angular/router';

    @Injectable()
    export class RouteNavigator {
      constructor(private router: Router, private sharedclientService: SharedclientService, private activatedRoute: ActivatedRoute) { }

      accessAdvancedSearchFromRegistration = false;
      accessSyntheseWhileGdfaShown = false;
      track360View = false;
      oldUrl: string;

      private rdvReferer: string;
      public navigateTo(url: string) {
        this.oldUrl = this.router.url;
        this.router.navigate([url], { skipLocationChange: true });
      }

      public myMethod()  // HERE IS MY METHOD
     {

        if(this.sharedclientService.user != null &amp;&amp; this.sharedclientService.user.isAdviser==null){
            this.navigateTo('/home/blank');
            this.sharedclientService.setCurrentRole('');
        }

        else  if (this.sharedclientService.user != null &amp;&amp; this.sharedclientService.user.isAdviser) {
          this.navigateTo('/home/advisor');
          this.sharedclientService.setCurrentRole('VENDEUR');
        } else {
          this.navigateTo('/home/pilote');
          this.sharedclientService.setCurrentRole('PILOTE');
        }
      }

      public goToNextAdvancedSearch() {
        if (this.accessAdvancedSearchFromRegistration || !this.sharedclientService.user.isAdviser) {
          this.navigateTo('/home/registration');
        }
        else {
          this.track360View = true;
          this.navigateTo('/home/view-360');
        }
      }

      public exitAdvancedSearch() {
        if (this.accessAdvancedSearchFromRegistration) {
          this.navigateTo('/home/registration');
        }
        else {
          this.goToHomeAccordingToProfile();
        }
      }

      goToRdv(url?:string) {
          if(!url)
        this.rdvReferer = this.router.url;
          else this.rdvReferer=url;
        this.navigateTo('/home/appointment');
      }

      exitRdv() {
        this.navigateTo(this.rdvReferer);
      }
      goToBlank() {
          this.navigateTo('/home/blank');
        }
      public url() {
        return this.router.url;
      }
     }
</code></pre>

<p><strong>Any ideas about what's the problem or how to deal whith it ??</strong></p>
",https://stackoverflow.com/questions/47158697/angular-unit-testing-this-router-mymethod-is-not-a-function,"['javascript', 'angular', 'unit-testing', 'typescript', 'jasmine']",3202,TRUE,1,1
Override class method behavior through unit testing iOS,"<p>I have class <code>ServerHandler</code> with one class method:</p>

<pre><code>+ (void) sendRequestEventToServer:(MyData*) requestDataForCaching                   
                        onSuccess:(void (^)(void))successBlock;
</code></pre>

<p>This method is responsible to send HTTP request to Server.
I call this method from dozen places in my program.</p>

<p>My goal is to get what data is sent to server therefore I need to write test where I override this method and instead to send <code>MyData</code> to server my program should send it to Test class.</p>

<p>I tried several approaches but none of them  works.</p>

<pre><code>@interface ServerHandler (TestSupport)
+ (void) mockSendRequestEventToServer:(MyData*) requestDataForCaching onSuccess:(void (^)(void))successBlock;
@end

@implementation ServerHandler (TestSupport)

+ (void) mockSendRequestEventToServer:(MyData*) requestDataForCaching  onSuccess:(void (^)(void))successBlock
{
    NSLog(@""mockSendRequestEventToServer"");
}

+ (void)load {
    Method original = class_getClassMethod([ServerHandler class], @selector(sendRequestEventToServer));
    Method mocked   = class_getClassMethod([ServerHandler class], @selector(mockSendRequestEventToServer));
    method_exchangeImplementations(original, mocked);
}
@end
</code></pre>

<p>Now I run the test:</p>

<pre><code>@implementation ServerTalkerTests

- (void)setUp {
    [super setUp];    
    [ServerHandler load];
}


- (void) test_serverTalker {

     __block BOOL isRunning = YES;

    [[MyProgram shared] start]; 

     // ...
    NSDate *timeout = [NSDate dateWithTimeIntervalSinceNow:10];
    do {
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
                                 beforeDate:timeout];
    } while (isRunning);

}

@end
</code></pre>

<p>When I run the program through <code>[[MyProgram shared] start];</code>  It should call mocked <code>[ServerHandler sendRequestEventToServer]</code> but it calls original method</p>

<p>What Im doing wrong?</p>

<p>I also tried with OCMock</p>
",https://stackoverflow.com/questions/42804330/override-class-method-behavior-through-unit-testing-ios,"['ios', 'unit-testing']",208,TRUE,1,1
Unit testing form submission which calls component method,"<p>I'm referring to this <a href=""https://plnkr.co/edit/9RQqbz4msxgagsipQDpl?p=preview"" rel=""nofollow noreferrer"">Plunker</a> which demonstrates unit testing form submission in Angular 2/4. If I understand the code correctly, the test validates that the form submits correctly and that the submission eventually (through a spy) calls <code>this.formSubmit.emit();</code>.</p>

<p>Why can't the test validate that the component's method of <code>doFormSubmit</code> was also called?</p>

<p>I would like the test (and my own form tests) to validate (in the same expectation) the form submission and the component method.</p>

<p>I see other people's tests that test for direct component's method is correctly called without the form AND I see tests like this which get the correct end result but doesn't validate the exact method called. But I don't see any tests that do both. </p>

<p>Is there some async/fakeasync/tick issue that I'm not seeing that would prevent that test? </p>

<pre class=""lang-html prettyprint-override""><code>&lt;form #form=""ngForm"" (ngSubmit)=""doFormSubmit()""&gt;
  &lt;div&gt;
    &lt;div class=""clearfix m-b-1""&gt;
      &lt;label class=""form-control-static"" for=""reviewContent"" i18n&gt;l.product.show.reviewForm.content&lt;/label&gt;
      &lt;div&gt;
        &lt;textarea
          class=""form-control""
          id=""reviewContent""
          name=""content""
          required
          [(ngModel)]=""model.content""
          #content=""ngModel""
        &gt;&lt;/textarea&gt; {{model.content}}
      &lt;/div&gt;
    &lt;/div&gt;

  &lt;/div&gt;
  &lt;div&gt;
    &lt;div class=""clearfix m-b-1""&gt;
      &lt;label class=""form-control-static"" for=""reviewRating"" i18n&gt;l.product.show.reviewForm.rating&lt;/label&gt;
      &lt;div&gt;
        &lt;input
          type=""number""
          class=""form-control l-number-input""
          id=""reviewRating""
          name=""rating""
          required
          [(ngModel)]=""model.rating""
          #rating=""ngModel""
        /&gt;{{model.rating}}
      &lt;/div&gt;
    &lt;/div&gt;

  &lt;/div&gt;
  &lt;div&gt;
    &lt;button
      type=""submit""
      class=""btn btn-primary btn-lg btn-block""
      [disabled]=""!form.form.valid""
      i18n
    &gt;l.product.show.reviewForm.submit&lt;/button&gt;
  &lt;/div&gt;
&lt;/form&gt;
{{doFormSubmitCalled}}
</code></pre>

<pre class=""lang-ts prettyprint-override""><code>import { Component, Input, ViewChild, Output, EventEmitter } from '@angular/core';
import { NgForm } from '@angular/forms'

@Component({
  selector: 'home-comp',
  templateUrl: `app/test.component.html`
})
export class TestComponent {
  @Input()
  public model: any;
  doFormSubmitCalled = false;

  @Output()
  public formSubmit = new EventEmitter&lt;any&gt;();

  public doFormSubmit() {
    //alert.log(""doFormSubmit called"");
    this.formSubmit.emit();
    this.doFormSubmitCalled = true;
  }
}
</code></pre>

<pre class=""lang-ts prettyprint-override""><code>import { FormsModule } from '@angular/forms';
import { DebugElement } from '@angular/core';
import { By } from '@angular/platform-browser';

import { ComponentFixture, TestBed, tick, async, fakeAsync } from '@angular/core/testing';

import { TestComponent } from './test.component';

function newEvent(eventName: string, bubbles = false, cancelable = false) {
    let evt = document.createEvent('CustomEvent');  // MUST be 'CustomEvent'
    evt.initCustomEvent(eventName, bubbles, cancelable, null);
    return evt;
}

describe('ProductShowReviewFormComponent', () =&gt; {
    let fixture: ComponentFixture&lt;TestComponent&gt;;
    let comp: TestComponent;
    let submitSpy: jasmine.Spy;

    // SO: spy on component's method
    let componentMethodSpy: jasmine.Spy;

    let contentInput: HTMLTextAreaElement;
    let ratingInput: HTMLInputElement;
    let form: DebugElement;

    beforeEach(async(() =&gt; {
        TestBed
            .configureTestingModule({
                imports: [FormsModule],
                declarations: [TestComponent],
            })
            .compileComponents()
            ;
    }));

    beforeEach(fakeAsync(() =&gt; {
        fixture = TestBed.createComponent(TestComponent);
        comp = fixture.componentInstance;
        submitSpy = spyOn(comp.formSubmit, 'emit');

        contentInput = fixture.debugElement.query(By.css('#reviewContent')).nativeElement;
        ratingInput = fixture.debugElement.query(By.css('#reviewRating')).nativeElement;
        form = fixture.debugElement.query(By.css('form'));

        // SO: component's method spy - EDIT: MUST CALL THROUGH
        componentMethodSpy = spyOn(component, 'doFormSubmit').and.callThrough();

        comp.model = { content: '', rating: '' };

        fixture.detectChanges();
        tick();
    }));

    it('should modify message', fakeAsync(() =&gt; {
        const expectedContent = 'The longest content.';
        const expectedRating = '4';

        contentInput.value = expectedContent;
        contentInput.dispatchEvent(newEvent('input'));

        ratingInput.value = expectedRating;
        ratingInput.dispatchEvent(newEvent('input'));

        fixture.detectChanges();
        tick();

        form.triggerEventHandler('submit', null);

        expect(submitSpy.calls.any()).toBe(true);
        expect(comp.model.content).toBe(expectedContent);
        expect(comp.model.rating.toString()).toBe(expectedRating);

        // SO: was the Component's method called
        expect(componentMethodSpy).toHaveBeenCalled();
    }));
});
</code></pre>
",https://stackoverflow.com/questions/43814080/unit-testing-form-submission-which-calls-component-method,"['forms', 'angular', 'unit-testing', 'validation']",784,FALSE,1,0
Unit testing communication between siblings in Angular 2,"<p>How does someone test communication between 2 sibling components in Angular 2? I don't seem to find any viable resource online.</p>

<p>app.component.html</p>

<pre><code>&lt;comp1 #a&gt;&lt;/comp1&gt;
&lt;comp2 [x]=""a.get()""&gt;&lt;/comp2&gt;
</code></pre>

<p>where <code>get()</code> is a function within the <code>comp1</code> component whose value I'm passing to one of the class variables of component <code>comp2</code>. How can I test this efficiently?</p>

<p><code>app.component</code> is the parent component of <code>comp1</code> and <code>comp2</code> and encloses them.</p>
",https://stackoverflow.com/questions/45895842/unit-testing-communication-between-siblings-in-angular-2,"['angular', 'unit-testing', 'components', 'testbed']",749,TRUE,1,1
Angular 4 reusing mock for components unit testing,"<p>I'm writing a test for all of our components. I was wondering how can I reuse the common mock service so I will not be declaring it every time on each component's unit test.</p>

<pre><code>class MockNavigateService {
  page: Page;
  constructor() {
    this.page= new Page();
  }
  navigateNext() {}
}

class TestQuestionsProvider extends QuestionService {
  getQuestions(key: string): QuestionBase&lt;any&gt;[] {
    return [];
  }

}

class MockModelService {
  createModel(): any {
    return {};
  }

  getModel(): any {
    return {};
  }

}
</code></pre>

<p><strong>UPDATE:</strong> How do I move these services to a separate file and import it to my unit test so that I will not be declaring it anymore</p>
",https://stackoverflow.com/questions/47649576/angular-4-reusing-mock-for-components-unit-testing,"['angular', 'unit-testing', 'jasmine', 'mocking']",363,FALSE,1,0
What is the point of unit testing redux-saga watchers?,"<p>In order to get 100% coverage of my Saga files I'm looking into how to test watchers.</p>

<p>I've been googling around, there are several answers as to HOW to test watchers. That is, saga's that do a <code>takeEvery</code> or <code>takeLatest</code>.</p>

<p>However, all methods of testing seem to basically copy the implementation. So what's the point of writing a test if it's the same?</p>

<p>Example:</p>

<pre class=""lang-js prettyprint-override""><code>// saga.js

import { delay } from 'redux-saga'
import { takeEvery, call, put } from 'redux-saga/effects'
import { FETCH_RESULTS, FETCH_COMPLETE } from './actions'

import mockResults from './tests/results.mock'

export function* fetchResults () {
  yield call(delay, 1000)
  yield put({ type: FETCH_COMPLETE, mockResults })
}

export function* watchFetchResults () {
  yield takeEvery(FETCH_RESULTS, fetchResults)
}
</code></pre>

<p>Test method 1:</p>

<pre class=""lang-js prettyprint-override""><code>import { takeEvery } from 'redux-saga/effects'
import { watchFetchResults, fetchResults } from '../sagas'
import { FETCH_RESULTS } from '../actions'

describe('watchFetchResults()', () =&gt; {
    const gen = watchFetchResults()
    // exactly the same as implementation
    const expected = takeEvery(FETCH_RESULTS, fetchResults)
    const actual = gen.next().value

    it('Should fire on FETCH_RESULTS', () =&gt; {
      expect(actual).toEqual(expected)
    })
  })
</code></pre>

<p>Test method 2: with a helper, like <a href=""https://www.npmjs.com/package/redux-saga-test-plan"" rel=""noreferrer"">Redux Saga Test Plan</a><br>
It's a different way of writing, but again we do basically the same as the implementation.</p>

<pre class=""lang-js prettyprint-override""><code>import testSaga from 'redux-saga-test-plan'
import { watchFetchResults, fetchResults } from '../sagas'
import { FETCH_RESULTS } from '../actions'

it('fire on FETCH_RESULTS', () =&gt; {
  testSaga(watchFetchResults)
    .next()
    .takeEvery(FETCH_RESULTS, fetchResults)
    .finish()
    .isDone()
})
</code></pre>

<p>Instead I'd like to simply know if <code>watchFestchResults</code> takes every FETCH_RESULTS. Or even only if it fires <code>takeEvery()</code>. No matter how it follows up.</p>

<p>Or is this really the way to do it?</p>
",https://stackoverflow.com/questions/42624587/what-is-the-point-of-unit-testing-redux-saga-watchers,"['unit-testing', 'redux-saga']",2551,TRUE,14,2
Can we mock finally block in unit testing,"<p>In my code I have a try-finally method.I don't want finally block for my unit testing.Can I mock the entire finally block in my class,because in my case it is just logging ?I am using PowerMockito for my unit testing.</p>

<pre><code>try {
    String foo = obj.myMethod();
} finally {
    logger.info(obj.webService());
}
</code></pre>
",https://stackoverflow.com/questions/44658348/can-we-mock-finally-block-in-unit-testing,"['java', 'unit-testing', 'junit', 'powermockito']",1416,TRUE,0,2
transactional unit testing with ObjectifyService - no rollback happening,"<p>We are trying to use google cloud datastore in our project and trying to use objectify as the ORM since google recommends it. I have carefully used and tried everything i could read about and think of but somehow the transactions don't seem to work. Following is my code and setup.</p>

<pre><code>@RunWith(SpringRunner.class)
@EnableAspectJAutoProxy(proxyTargetClass = true)
@ContextConfiguration(classes = { CoreTestConfiguration.class })
public class TestObjectifyTransactionAspect {

    private final LocalServiceTestHelper helper = new LocalServiceTestHelper(
            // Our tests assume strong consistency
            new LocalDatastoreServiceTestConfig().setApplyAllHighRepJobPolicy(),
            new LocalMemcacheServiceTestConfig(), new LocalTaskQueueTestConfig());

    private Closeable closeableSession;

    @Autowired
    private DummyService dummyService;

    @BeforeClass
    public static void setUpBeforeClass() {
        // Reset the Factory so that all translators work properly.
        ObjectifyService.setFactory(new ObjectifyFactory());
    }

    /**
     * @throws java.lang.Exception
     */
    @Before
    public void setUp() throws Exception {
        System.setProperty(""DATASTORE_EMULATOR_HOST"", ""localhost:8081"");
        ObjectifyService.register(UserEntity.class);
        this.closeableSession = ObjectifyService.begin();
        this.helper.setUp();
    }

    /**
     * @throws java.lang.Exception
     */
    @After
    public void tearDown() throws Exception {
        AsyncCacheFilter.complete();
        this.closeableSession.close();
        this.helper.tearDown();
    }

    @Test
    public void testTransactionMutationRollback() {
        // save initial list of users
        List&lt;UserEntity&gt; users = new ArrayList&lt;UserEntity&gt;();
        for (int i = 1; i &lt;= 10; i++) {
            UserEntity user = new UserEntity();
            user.setAge(i);
            user.setUsername(""username_"" + i);
            users.add(user);
        }
        ObjectifyService.ofy().save().entities(users).now();

        try {
             dummyService.mutateDataWithException(""username_1"", 6L);
        } catch (Exception e) {
            e.printStackTrace();
        }

        List&lt;UserEntity&gt; users2 = this.dummyService.findAllUsers();  

        Assert.assertEquals(""Size mismatch on rollback"", users2.size(), 10);

        boolean foundUserIdSix = false;
        for (UserEntity userEntity : users2) {
            if (userEntity.getUserId() == 1) {
                Assert.assertEquals(""Username update failed in transactional context rollback."", ""username_1"",
                        userEntity.getUsername());
            }
            if (userEntity.getUserId() == 6) {
                foundUserIdSix = true;
            }
        }

        if (!foundUserIdSix) {
            Assert.fail(""Deleted user with userId 6 but it is not rolledback."");
        }
    }
}
</code></pre>

<p>Since I am using spring, idea is to use an aspect with a custom annotation to weave <code>objectify.transact</code> around the spring service beans methods that are calling my daos.
But somehow the update due to <code>ObjectifyService.ofy().save().entities(users).now();</code> is not gettign rollbacked though the exception throws causes Objectify to run its rollback code. I tried printing the ObjectifyImpl instance hashcodes and they are all same but still its not rollbacking.</p>

<p>Can someone help me understand what am i doing wrong? Havent tried the actual web based setup yet...if it cant pass transnational test cases there is no point in actual transaction usage in a web request scenario. </p>

<p><strong>Update:</strong> Adding aspect, services, dao as well to make a complete picture. The code uses spring boot.</p>

<p>DAO class. Note i am not using any transactions here because as per code of <code>com.googlecode.objectify.impl.TransactorNo.transactOnce(ObjectifyImpl&lt;O&gt;, Work&lt;R&gt;)</code> a transnational <code>ObjectifyImpl</code> is flushed and committed in this method which i don't want. I want commit to happen once and rest all to join in on that transaction. Basically this is the wrong code in <code>com.googlecode.objectify.impl.TransactorNo</code> ..... i will try to explain my understanding a later in the question.</p>

<pre><code>@Component
public class DummyDaoImpl implements DummyDao {

    @Override
    public List&lt;UserEntity&gt; loadAll() {
        Query&lt;UserEntity&gt; query = ObjectifyService.ofy().transactionless().load().type(UserEntity.class);
        return query.list();
    }

    @Override
    public List&lt;UserEntity&gt; findByUserId(Long userId) {
        Query&lt;UserEntity&gt; query = ObjectifyService.ofy().transactionless().load().type(UserEntity.class);
        //query = query.filterKey(Key.create(UserEntity.class, userId));
        return query.list();
    }

    @Override
    public List&lt;UserEntity&gt; findByUsername(String username) {
        return ObjectifyService.ofy().transactionless().load().type(UserEntity.class).filter(""username"", username).list();
    }

    @Override
    public void update(UserEntity userEntity) {
        ObjectifyService.ofy().save().entity(userEntity);
    }

    @Override
    public void update(Iterable&lt;UserEntity&gt; userEntities) {
        ObjectifyService.ofy().save().entities(userEntities);
    }

    @Override
    public void delete(Long userId) {
        ObjectifyService.ofy().delete().key(Key.create(UserEntity.class, userId));
    }
}
</code></pre>

<p>Below is the Service class</p>

<pre><code>@Service
public class DummyServiceImpl implements DummyService {

    private static final Logger LOGGER = LoggerFactory.getLogger(DummyServiceImpl.class);

    @Autowired
    private DummyDao dummyDao;

    public void saveDummydata() {
        List&lt;UserEntity&gt; users = new ArrayList&lt;UserEntity&gt;();
        for (int i = 1; i &lt;= 10; i++) {
            UserEntity user = new UserEntity();
            user.setAge(i);
            user.setUsername(""username_"" + i);
            users.add(user);
        }
        this.dummyDao.update(users);
    }

    /* (non-Javadoc)
     * @see com.bbb.core.objectify.test.services.DummyService#mutateDataWithException(java.lang.String, java.lang.Long)
     */
    @Override
    @ObjectifyTransactional
    public void mutateDataWithException(String usernameToMutate, Long userIdToDelete) throws Exception {
        //update one
        LOGGER.info(""Attempting to update UserEntity with username={}"", ""username_1"");
        List&lt;UserEntity&gt; mutatedUsersList = new ArrayList&lt;UserEntity&gt;();
        List&lt;UserEntity&gt; users = dummyDao.findByUsername(usernameToMutate);
        for (UserEntity userEntity : users) {
            userEntity.setUsername(userEntity.getUsername() + ""_updated"");
            mutatedUsersList.add(userEntity);
        }
        dummyDao.update(mutatedUsersList);

        //delete another
        UserEntity user = dummyDao.findByUserId(userIdToDelete).get(0);
        LOGGER.info(""Attempting to delete UserEntity with userId={}"", user.getUserId());
        dummyDao.delete(user.getUserId());
        throw new RuntimeException(""Dummy Exception"");
    }

    /* (non-Javadoc)
     * @see com.bbb.core.objectify.test.services.DummyService#findAllUsers()
     */
    @Override
    public List&lt;UserEntity&gt; findAllUsers() {
        return dummyDao.loadAll();
    }
</code></pre>

<p>Aspect which wraps the method annoted with <code>ObjectifyTransactional</code> as a transact work.</p>

<pre><code>@Aspect
@Component
public class ObjectifyTransactionAspect {
    private static final Logger LOGGER = LoggerFactory.getLogger(ObjectifyTransactionAspect.class);

    @Around(value = ""execution(* *(..)) &amp;&amp; @annotation(objectifyTransactional)"")
    public Object objectifyTransactAdvise(final ProceedingJoinPoint pjp, ObjectifyTransactional objectifyTransactional) throws Throwable {
        try {
            Object result = null;
            Work&lt;Object&gt; work = new Work&lt;Object&gt;() {
                @Override
                public Object run() {
                    try {
                        return pjp.proceed();
                    } catch (Throwable throwable) {
                        throw new ObjectifyTransactionExceptionWrapper(throwable);
                    }
                }
            };

            switch (objectifyTransactional.propagation()) {
            case REQUIRES_NEW:
                int limitTries = objectifyTransactional.limitTries();
                if(limitTries &lt;= 0) {
                    Exception illegalStateException = new IllegalStateException(""limitTries must be more than 0."");
                    throw new ObjectifyTransactionExceptionWrapper(illegalStateException);
                } else {
                    if(limitTries == Integer.MAX_VALUE) {
                        result = ObjectifyService.ofy().transactNew(work);
                    } else {
                        result = ObjectifyService.ofy().transactNew(limitTries, work);
                    }
                }
                break;
            case NOT_SUPPORTED :
            case NEVER :
            case MANDATORY :
                result = ObjectifyService.ofy().execute(objectifyTransactional.propagation(), work);
                break;
            case REQUIRED :
            case SUPPORTS :
                ObjectifyService.ofy().transact(work);
                break;
            default:
                break;
            }
            return result;
        } catch (ObjectifyTransactionExceptionWrapper e) {
            String packageName = pjp.getSignature().getDeclaringTypeName();
            String methodName = pjp.getSignature().getName();
            LOGGER.error(""An exception occured while executing [{}.{}] in a transactional context.""
                                , packageName, methodName, e);
            throw e.getCause();
        } catch (Throwable ex) {
            String packageName = pjp.getSignature().getDeclaringTypeName();
            String methodName = pjp.getSignature().getName();
            String fullyQualifiedmethodName = packageName + ""."" + methodName;
            throw new RuntimeException(""Unexpected exception while executing ["" 
                                            + fullyQualifiedmethodName + ""] in a transactional context."", ex);
        }
    }
}
</code></pre>

<p>Now the problem code part that i see is as follows in <code>com.googlecode.objectify.impl.TransactorNo</code>:</p>

<pre><code>@Override
public &lt;R&gt; R transact(ObjectifyImpl&lt;O&gt; parent, Work&lt;R&gt; work) {
    return this.transactNew(parent, Integer.MAX_VALUE, work);
}

@Override
public &lt;R&gt; R transactNew(ObjectifyImpl&lt;O&gt; parent, int limitTries, Work&lt;R&gt; work) {
    Preconditions.checkArgument(limitTries &gt;= 1);

    while (true) {
        try {
            return transactOnce(parent, work);
        } catch (ConcurrentModificationException ex) {
            if (--limitTries &gt; 0) {
                if (log.isLoggable(Level.WARNING))
                    log.warning(""Optimistic concurrency failure for "" + work + "" (retrying): "" + ex);

                if (log.isLoggable(Level.FINEST))
                    log.log(Level.FINEST, ""Details of optimistic concurrency failure"", ex);
            } else {
                throw ex;
            }
        }
    }
}

private &lt;R&gt; R transactOnce(ObjectifyImpl&lt;O&gt; parent, Work&lt;R&gt; work) {
    ObjectifyImpl&lt;O&gt; txnOfy = startTransaction(parent);
    ObjectifyService.push(txnOfy);

    boolean committedSuccessfully = false;
    try {
        R result = work.run();
        txnOfy.flush();
        txnOfy.getTransaction().commit();
        committedSuccessfully = true;
        return result;
    }
    finally
    {
        if (txnOfy.getTransaction().isActive()) {
            try {
                txnOfy.getTransaction().rollback();
            } catch (RuntimeException ex) {
                log.log(Level.SEVERE, ""Rollback failed, suppressing error"", ex);
            }
        }

        ObjectifyService.pop();

        if (committedSuccessfully) {
            txnOfy.getTransaction().runCommitListeners();
        }
    }
}
</code></pre>

<p>transactOnce is by code / design always using a single transaction to do things. It will either commit or rollback the transaction. there is no provision to chain transactions like a normal enterprise app would want.... service -> calls multiple dao methods in a single transaction and commits or rollbacks depending on how things look. </p>

<p>keeping this in mind, i removed all annotations and transact method calls in my dao methods so that they don't start an explicit transaction and the aspect in service wraps the service method in transact and ultimately in transactOnce...so basically the service method is running in a transaction and no new transaction is getting fired again. This is a very basic scenario, in actual production apps services can call other service methods and they might have the annotation on them and we could still end up in a chained transaction..but anyway...that is a different problem to solve....</p>

<p>I know NoSQLs dont support write consistency at table or inter table levels so am I asking too much from google cloud datastore?</p>
",https://stackoverflow.com/questions/44118953/transactional-unit-testing-with-objectifyservice-no-rollback-happening,"['spring', 'google-app-engine', 'transactions', 'google-cloud-datastore', 'objectify']",207,FALSE,0,0
Unit testing my revocation of X509 checking code?,"<p>I have written some code for testing if a certificate has been revoked. It works, but now I have to write a unit test for it.</p>

<p>Is there a way for me to add a new line to my CRL on the client side, in order to break it on purpose to show that it would fail?</p>
",https://stackoverflow.com/questions/42209478/unit-testing-my-revocation-of-x509-checking-code,"['java', 'x509certificate']",366,FALSE,0,1
Grails Unit Testing a method with command object,"<p>I have a problem with my Unit Test. This is my Unit Test:</p>

<pre><code>void ""Test the update action performs an update on a valid domain instance""() {
    given:
        def aclServiceMock = mockFor(AclService)
        aclServiceMock.demand.updateRolePermissions { Role role, Map, roleMap, List permissions -&gt; return true }
        controller.aclService = aclServiceMock.createMock()

        def roleInstance = setupRoleController()

        mockCommandObject RoleCommand
        RoleCommand cmd = new RoleCommand(
            authority: roleInstance?.authority,
            description: roleInstance?.description
        )

    when:""A valid domain instance is passed to the update action""
        controller.update(roleInstance, cmd)

    then:""A redirect is issued to the show action""
        response.redirectedUrl == ""/role/index""
        flash.message != null
        flash.error == null
}
</code></pre>

<p>And this is the result that I get from the terminal:</p>

<pre><code>| Failure:  Test the update action performs an update on a valid domain instance(ph.gov.doe.core.acl.RoleControllerSpec)
|  Condition not satisfied:
flash.message != null
|     |       |
[:]   null    false
    at ph.gov.doe.core.acl.RoleControllerSpec.Test the update action performs an update on a valid domain instance(RoleControllerSpec.groovy:222)
</code></pre>

<p>I can't seem to figure out why my unit test on that particular method keeps failing. Maybe my Command Object mock is the key? Thanks in advance.</p>

<p>EDIT: condition should be 'response.redirectedUrl == ""/role/index""', I just copied the wrong message cause i was fiddling with the code at the time.</p>

<p>EDIT: This is the controller method:</p>

<pre><code>def update(Role roleInstance, RoleCommand roleCommand) {
    Map roleMap = [:]
    ArrayList collectPermission = [], getPermissions = [], roleList = []
    def savedRoleInstance

    /** collect selected permission into arraylist */
    collectPermission.addAll(params?.selectedPermission ?: [])
    getPermissions = Permission.findAllByIdInList(collectPermission)

    def roleEditInstance = Role.get(params?.roleId)

    /** Set data for validation of Role */
    roleCommand.with {
        id          = roleEditInstance?.id
        authority   = params?.authority
        description = params?.description
    }

    roleCommand.validate()        

    /** Check if the set of permission already exists */
    roleList = RolePermission.findAllByPermissionInListAndRoleNotEqual(getPermissions, Role.findByAuthority('ROLE_SUPERADMIN'))?.role

    def duplicateRolePermission = roleList.find { r -&gt; r.getAuthorities().sort { it?.id } == getPermissions.sort { it?.id }  &amp;&amp; r != roleEditInstance }

    if (collectPermission.isEmpty()) {
        flash.error = message(code: 'role.permissions.blank', args: [message(code: 'role.label', default: params?.authority)])
        respond roleInstance, model:[roleList: Role.list(), permissionList: Permission.findAllByAuthorityNotEqual('PERM_DASHBOARD_VIEW'), inheritPermission: params?.inheritPermission, selectedPermission: getPermissions], view: ""edit""            
    } else if (roleCommand.hasErrors() || duplicateRolePermission != null) {
        bindData(roleCommand, roleInstance)

        if(duplicateRolePermission != null){
            flash.error = message(code: 'role.permissions.unique', args: [message(code: 'role.label', default: getPermissions?.description)])
        }

        respond roleCommand.errors, model:[roleInstance: roleCommand,roleList: Role.list(), permissionList: Permission.findAllByAuthorityNotEqual('PERM_DASHBOARD_VIEW'), inheritPermission: params?.inheritPermission, selectedPermission: getPermissions, roleId: roleEditInstance?.id], view: ""edit""
    } else {
        /** Save the Role */
        roleMap = [authority: params?.authority, description: params?.description]
        def savedRole = aclService.updateRolePermissions(roleEditInstance, roleMap, getPermissions)

        if (currentAccount) {
           auditLogService.logEvent(currentAccount.emailAddress, ""UPDATE_ROLE_SUCCESS"", ""Successfully updated role details."", true) 
        }

        flash.message = message(code: 'role.updated.message', args: [message(code: 'role.label', default: savedRole?.authority)])
        flash.id = savedRole?.id
        redirect action: 'view', params:[id: savedRole?.id]
    }
}
</code></pre>
",https://stackoverflow.com/questions/42799886/grails-unit-testing-a-method-with-command-object,"['unit-testing', 'grails', 'spock', 'command-objects']",499,FALSE,0,1
Unit testing with core data in objective c,"<p>My coredata methods are here.  How to write unit test case to check this. </p>

<p>Method to save to coredata</p>

<pre><code>- (void)saveUserDetails:(Model *)userDetail {
if(userDetail != nil) {
    UserEntity *user = [NSEntityDescription insertNewObjectForEntityForName:@“EntityName” inManagedObjectContext:[self sharedContext]];

    NSArray *fetchArray = [self fetchUserWithUsername:userDetail.username];

    if ([fetchArray count] == 0) {
        user.username = userDetail.username;
        [self saveContext];
    }
}
}
</code></pre>

<p>Method to fetch from coredata</p>

<pre><code>- (NSArray *)fetchUserWithUsername:(NSString *)username {
if (username != nil) {
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    NSEntityDescription *userEntity = [NSEntityDescription entityForName:@“EntityName” inManagedObjectContext:[self sharedContext]];
    [fetchRequest setEntity:userEntity];
    fetchRequest.predicate = [NSPredicate predicateWithFormat:@""username = %@"", username];

    NSError *error;
    NSArray *fetchedObjects = [[self sharedContext] executeFetchRequest:fetchRequest error:&amp;error];

    return fetchedObjects;
}

return nil;
}
</code></pre>
",https://stackoverflow.com/questions/43625748/unit-testing-with-core-data-in-objective-c,"['objective-c', 'unit-testing', 'core-data']",401,TRUE,0,1
Unit Testing PHP class with new keyword insight,"<p>So the other day I have a bad designed PHP class which, for example, populate some objects:</p>

<pre><code>class Populator
{
    function populate(array $data): array
    {
        $result = [];

        foreach ($data as $row) {
            $result[] = new PopulateMeGently($row);
        }

        return $result;
    }
}
</code></pre>

<p>Assume also <code>PopulateMeGently</code> is really heavy and the only option is mock it in unit tests.</p>

<p>So how test <code>populate</code> method in <code>Populator</code> class? Or how to refactor it, to make testable?
I have available IoC and other fancy stuff I can use, but for now everything I tried looks bulky and ugly.</p>

<p>Thank you!</p>
",https://stackoverflow.com/questions/42901171/unit-testing-php-class-with-new-keyword-insight,"['php', 'unit-testing', 'class', 'mocking', 'phpunit']",252,TRUE,1,1
Angular unit testing with ngMock - $timeout.flush() throws exception,"<p>I am using ngMock for unit testing and I need to use the $timeout.flush function in one of my tests, so I have added the two following lines to my test:</p>

<pre><code>$timeout.flush();
$timeout.verifyNoPendingTasks();
</code></pre>

<p>as indicated on <a href=""http://www.bradoncode.com/blog/2015/06/11/unit-testing-code-that-uses-timeout-angularjs/"" rel=""nofollow noreferrer"">http://www.bradoncode.com/blog/2015/06/11/unit-testing-code-that-uses-timeout-angularjs/</a>.</p>

<p>$timeout.flush() does flush the timeout as expected, however I am now getting an exception from angular-mocks.js every time I run my test:</p>

<blockquote>
  <p>LOG: 'Exception: ', Error{line: 1441, sourceURL: '<a href=""http://localhost:9876/base/node_modules/angular-mocks/angular-mocks.js?05a191adf8b7e3cfae1806d65efdbdb00a1742dd"" rel=""nofollow noreferrer"">http://localhost:9876/base/node_modules/angular-mocks/angular-mocks.js?05a191adf8b7e3cfae1806d65efdbdb00a1742dd</a>', stack: '$httpBackend@<a href=""http://localhost:9876/base/node_modules/angular-mocks/angular-mocks.js?05a191adf8b7e3cfae1806d65efdbdb00a1742dd:1441:90"" rel=""nofollow noreferrer"">http://localhost:9876/base/node_modules/angular-mocks/angular-mocks.js?05a191adf8b7e3cfae1806d65efdbdb00a1742dd:1441:90</a>
  ....<br>
  global code@<a href=""http://localhost:9876/context.html:336:28"" rel=""nofollow noreferrer"">http://localhost:9876/context.html:336:28</a>'}, 'Cause: ', undefined</p>
</blockquote>

<p>Does anyone know where this exception could come from? I get it as many times as I use the $timeout.flush() function.</p>

<p>Looking at the angular-mocks.js file, it looks like it comes from the $httpBackend function. I have tried to update the ngMock version but it does not change anything. I have tried version 1.4.7 (which is my angular version) and version 1.6.2.</p>

<pre><code>  function $httpBackend(method, url, data, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers) {

var xhr = new MockXhr(),
    expectation = expectations[0],
    wasExpected = false;

xhr.$$events = eventHandlers;
xhr.upload.$$events = uploadEventHandlers;

function prettyPrint(data) {
  return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp)
      ? data
      : angular.toJson(data);
}

function wrapResponse(wrapped) {
  if (!$browser &amp;&amp; timeout) {
    if (timeout.then) {
      timeout.then(handleTimeout);
    } else {
      $timeout(handleTimeout, timeout);
    }
  }

  return handleResponse;

  function handleResponse() {
    var response = wrapped.response(method, url, data, headers, wrapped.params(url));
    xhr.$$respHeaders = response[2];
    callback(copy(response[0]), copy(response[1]), xhr.getAllResponseHeaders(),
             copy(response[3] || ''));
  }

  function handleTimeout() {
    for (var i = 0, ii = responses.length; i &lt; ii; i++) {
      if (responses[i] === handleResponse) {
        responses.splice(i, 1);
        callback(-1, undefined, '');
        break;
      }
    }
  }
}

if (expectation &amp;&amp; expectation.match(method, url)) {
  if (!expectation.matchData(data)) {
    throw new Error('Expected ' + expectation + ' with different data\n' +
        'EXPECTED: ' + prettyPrint(expectation.data) + '\nGOT:      ' + data);
  }

  if (!expectation.matchHeaders(headers)) {
    throw new Error('Expected ' + expectation + ' with different headers\n' +
                    'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT:      ' +
                    prettyPrint(headers));
  }

  expectations.shift();

  if (expectation.response) {
    responses.push(wrapResponse(expectation));
    return;
  }
  wasExpected = true;
}

var i = -1, definition;
while ((definition = definitions[++i])) {
  if (definition.match(method, url, data, headers || {})) {
    if (definition.response) {
      // if $browser specified, we do auto flush all requests
      ($browser ? $browser.defer : responsesPush)(wrapResponse(definition));
    } else if (definition.passThrough) {
      originalHttpBackend(method, url, data, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers);
    } else throw new Error('No response defined !');
    return;
  }
}
throw wasExpected ?
    new Error('No response defined !') :
    new Error('Unexpected request: ' + method + ' ' + url + '\n' +
              (expectation ? 'Expected ' + expectation : 'No more request expected'));
</code></pre>

<p>}</p>
",https://stackoverflow.com/questions/42517688/angular-unit-testing-with-ngmock-timeout-flush-throws-exception,"['angularjs', 'unit-testing', 'httpbackend', 'angularjs-ngmock']",353,FALSE,1,0
Unit testing a function that i didn&#39;t write,"<p>So I have this function </p>

<pre><code>const firstEntityValue = (entities: Object, entity: string) =&gt; {
  const val = entities &amp;&amp; entities[entity] &amp;&amp;
    Array.isArray(entities[entity]) &amp;&amp;
    entities[entity].length &gt; 0 &amp;&amp;
    entities[entity][0].value
  ;
  if (!val) {
    return null;
  }
  return typeof val === 'object' ? val.value : val;
};
</code></pre>

<p>I didn't write it, it was provided by the application I'm cloning.
The app is working quite good, but now I'm Writing unit tests and I don't have any idea of the test to write to this function and even what to test.
I already tested if the function was called once with the right parameters using mocha and sinon spy, but istanbul is telling me that all that comes after the declaration ""const firstEntityValue"" is not covered.
Hope you can help me out.</p>
",https://stackoverflow.com/questions/43933070/unit-testing-a-function-that-i-didnt-write,"['unit-testing', 'mocha.js', 'sinon']",36,TRUE,1,1
Unit Testing a method which queries the database,"<p>So I've created a function which accepts an ID, internally queries a database via a repository from the data returned mutations are made to the data depending on different scenarios and then we return the data.</p>

<p>How would I unit test this function?
  Would I stub the find method on my repository layer to return data so I'm not dependant on connecting on the database?</p>
",https://stackoverflow.com/questions/42938197/unit-testing-a-method-which-queries-the-database,"['node.js', 'mongodb', 'unit-testing', 'testing', 'meteor']",354,TRUE,1,1
Unit Testing Visual Studio Online Selenium ChromeDriver Exception,"<p>I use Selenium ChromeDriver in a Unit Test project to test some action on a web page ... </p>

<p><code>var chromeDriver = new ChromeDriver();
 chromeDriver.Navigate().GoToUrl(""https://www.google.com"");</code></p>

<p>Chrome driver has been installed from nuget </p>

<p><code>Install-Package Selenium.WebDriver.ChromeDriver -Version 2.28.0</code>.</p>

<p>When build my project in Visual Studio Online I receive some error:</p>

<blockquote>
  <p>System.InvalidOperationException: unknown error: cannot find Chrome binary
  (Driver info: chromedriver=2.28.455520</p>
</blockquote>

<p>Any solution to solve this?</p>
",https://stackoverflow.com/questions/43092392/unit-testing-visual-studio-online-selenium-chromedriver-exception,"['c#', 'unit-testing', 'selenium', 'azure-devops', 'selenium-chromedriver']",1021,TRUE,0,4
Bean IO Stream Builder Unit Testing using spock,"<p>I have following lines of code that create a <code>StreamBuilder</code> for me.</p>

<pre><code>@Override
protected StreamBuilder getStreamBuilder() {
   return new StreamBuilder(BEAN_IO_STREAM_NAME)
         .format(FILE_FORMAT)
         .addRecord(FileHeader.class)
         .addRecord(Records.class);
}
</code></pre>

<p>Now as a part of unit testing, how can I test this method using Spock specification?</p>

<p>Here is my Spock test:</p>

<pre><code>def ""Get Stream Builder""()
    given:
    StreamBuilder streamBuilder = new StreamBuilder(""STREAM"").format(""fixedlength"").addRecord(Header.class).addRecord(Records.class)

    expect:
    streamBuilder == fileProcessor.streamBuilder

}
</code></pre>

<p>Output:</p>

<pre><code>Expected :config: StreamConfig[name=STREAM]
Actual   :config: StreamConfig[name=STREAM]
</code></pre>
",https://stackoverflow.com/questions/46387763/bean-io-stream-builder-unit-testing-using-spock,"['java', 'unit-testing', 'spock']",192,FALSE,0,2
Unit-testing of private method and possible refactoring,"<p>I am currently testing private method this way (using <code>nunit</code>):</p>

<pre><code>class Foo
{
    private int Identity(int n) =&gt; n;
}

[TestFixture]
class MyTests
{
    [Test]
    public void TestFoo()
    {
        var myFoo = new Foo();
        var identityMethod = myFoo.GetType().GetMethod(""Identity"", BindingFlags.NonPublic | BindingFlags.Instance);
        Assert.That(identityMethod.Invoke(myFoo, new []{ (object)42 }), Is.EqualTo(42));
    }
}
</code></pre>

<p>My team does not like this, because put the method name as a string prevent this method to be renamed, if we want to do refactoring through automatic tools.</p>

<p>I tried to replace the name with <code>nameof</code>, but:</p>

<blockquote>
  <p>Foo.Indentity(int) is inaccessible due to its protection level</p>
</blockquote>

<p>(By the way, this is strange in my opinion that such an operator respects the privacy protections).</p>

<p>So, can I test private methods without sacrificing possible refactoring?</p>

<p>I was proposed to make the private methods protected and inherit the class with the class test, but this does not satisfy me.</p>

<p><em>Disclaimer: I know that some people think that private method should not be tested, but this is not the point here. Please do not transform this question into a debate about this.</em></p>
",https://stackoverflow.com/questions/44971543/unit-testing-of-private-method-and-possible-refactoring,"['c#', 'unit-testing', 'nunit']",346,TRUE,0,2
How to perform unit testing in android studio,"<p>I have made a sample application in android and included the aar file in it and i have peform unit testing for the application whether it is possible to carry out unit testing for the sample application?</p>
",https://stackoverflow.com/questions/43316796/how-to-perform-unit-testing-in-android-studio,"['java', 'unit-testing', 'android-studio', 'aar']",143,FALSE,-1,2
Python unit testing execute main() before test cases,"<p>I'm fairly new to unit testing in general and I'm trying to generate unit tests for a script I'm developing in Python. The script is designed to take in a data file and several command line arguments, and then run several functions in order while updating a database. For example, here is how my script would run:</p>

<pre><code>import argparse
if __name__ == ""__main__"": 
    parser = argparse.ArgumentParser(description='Script to process data files')
    parser.add_argument('-f', help='The absolute file_path to the source file')
    args = parser.parse_args()
    main(args)

def main(args):
    file_info = get_file_info(args)
    process1(args, file_info)
    process2(args, file_info)

def file_info(args):
    file_info = {'path':args.file_path...}
    ...
    return file_info

def process1(args):
    #update database1
    ...

def process2(args):
    #update database2
    ...
</code></pre>

<p>As you can see process1 and process2 are meant to modify the database, not to return a value, so the only way to check if those worked properly is to check the database to see if it has the correct values. I can do this easily in a unit test, but I want to run similar unit tests on separate calls to the main function. So I want my unit tests to look like this:</p>

<pre><code>import unittest
import myScript

class Test_Load(unittest.TestCase):        
    test_args_1 = ['-f','C:\file1.txt']
    myScript.main(test_args_1)

    def test_get_file_info_1(self):
        test_file_info = {'foo':'bar'}
        self.assertDictEqual(test_file_info, myScript.get_file_info(test_args_1))

    def test_process1_1(self):
        #get list from sql query on database
        test_db_info = {'load_time':'1997-07-16T19:20:30', 'file_size':512}
        self.assertDictEqual(test_db_info, sql_query)

    def test_process2_1(self):
        #get list from sql query on database
        test_db_info = {'foo':'bar'}
        self.assertDictEqual(test_db_info, sql_query)

    test_args_2 = ['-f','C:\file2.txt']
    myScript.main(test_args_2)

    def test_get_file_info_2(self):
        test_file_info = {'foo':'bar'}
        self.assertDictEqual(test_file_info, myScript.get_file_info(test_args_2))

    def test_process1_2(self):
        #get list from sql query on database
        test_db_info = {'load_time':'2017-02-08T12:00:00', 'file_size':1024}
        self.assertDictEqual(test_db_info, sql_query)

    def test_process2_2(self):
        #get list from sql query on database
        test_db_info = {'foo':'foobar'}
        self.assertDictEqual(test_db_info, sql_query)
    ...

if __name__ == '__main__':
    Test_Load.main()
</code></pre>

<p>The <code>get_file_info()</code> function returns a dictionary so I should have no problem testing that. </p>

<p>So I want to call the main of my script and then run some tests on the expected results. Am I able to call my scripts main like this in the Test_Load class? And is there a better way to group these unit tests so they can be run independently of each other?</p>
",https://stackoverflow.com/questions/42119109/python-unit-testing-execute-main-before-test-cases,"['python', 'unit-testing', 'testing', 'test-suite']",1071,FALSE,0,0
Local unit testing with Mockito in Android studio,"<p>Can someone please show me a working unit test om this code, using mockito? Im new to testing in Android studio and could really need some help.</p>

<pre><code>public class PreferenceHelper {

public static final String SHARED_PREFS_NAME = ""EDUBACK_PREFS"";
public static final String PREF_KEY_IS_STUDENT = ""PREF_KEY_IS_STUDENT"";
private final SharedPreferences mPref;

public PreferenceHelper(Context context) {
    mPref = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);
}


public void setIsStudent(boolean isStudent) {
    mPref.edit().putBoolean(PREF_KEY_IS_STUDENT, isStudent).apply();
}


public boolean getIsStudent() {
    return mPref.getBoolean(PREF_KEY_IS_STUDENT, true); // Default true
}}
</code></pre>
",https://stackoverflow.com/questions/43170574/local-unit-testing-with-mockito-in-android-studio,"['android', 'unit-testing', 'mockito']",244,FALSE,-2,1
Swift unit testing of function with generic parameter,"<p>I have a function defined as follows:</p>

<pre><code>func parse&lt;T: Mappable&gt;(_ data: Data, _ completion: (Result&lt;[T]&gt;) -&gt; Void) {
    completion(Result {
        do {
            let decodedData: Any = try decode(data)
            let checkedArray: [AnyObject] = try check(decodedData)
            let models: [T] = mapToModels(checkedArray)
            return models
        } catch {
            throw error
        }
    })
}
</code></pre>

<p>When I try to run the following unit test:</p>

<pre><code>func testInvalidData() {
    let test = ""test""
    let invalidData = test.data(using: .utf8)

    parse(invalidData, { result in
  //^Generic parameter 'T' could not be inferred
        switch result {
        case .success(let users):
            XCTFail()
        case .failure(let error):
            XCTAssertNotNil(error)
        }
    })
}
</code></pre>

<p>As commented above I get the error <code>Generic parameter 'T' could not be inferred</code>.</p>

<p>This function compiles, builds and works fine otherwise (when not unit testing).</p>

<p>Any idea how to test?</p>
",https://stackoverflow.com/questions/44698924/swift-unit-testing-of-function-with-generic-parameter,"['swift', 'unit-testing', 'generics', 'xctest', 'xctestcase']",1561,TRUE,0,1
Angular2 unit testing a component that uses MdlSnackbarService,"<p>I've got the following component:</p>

<pre><code>import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, FormControl, Validators} from ""@angular/forms"";
import {ValidationService} from ""../../services/validation.service"";
import {Router} from ""@angular/router"";
import {UsersService} from ""../../services/users.service"";
import {MdlSnackbarService} from ""angular2-mdl"";

@Component({
  selector: 'app-signup',
  templateUrl: 'signup.component.html',
  styleUrls: ['signup.component.css'],
  providers: [UsersService]
})
export class SignupComponent implements OnInit {

  form: FormGroup;

  constructor(private fb: FormBuilder,
              private router: Router,
              private usersService: UsersService,
              private mdlSnackbarService: MdlSnackbarService) {
    this.form = fb.group({
      ""email"": new FormControl("""", [Validators.required, ValidationService.emailValidator]),
      ""password"": new FormControl("""", Validators.required)
    });
  }

  ngOnInit() {
  }

  onSignup() {
    if (this.form.valid) {
      let email = this.form.value.email;
      let password = this.form.value.password;
      this.usersService.signup(email, password)
        .then(() =&gt; {
          this.router.navigate(['/app/home']);
        })
        .catch(err =&gt; {
          this.mdlSnackbarService.showToast(err);
        });
    }

  }

}
</code></pre>

<p>And I am trying to setup some unit tests for this, but after quite a few hours I am still unable to run the simplest test (the one autogenerated by the angular CLI):</p>

<pre><code>fdescribe('SignupComponent', () =&gt; {
  let component: SignupComponent;
  let fixture: ComponentFixture&lt;SignupComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ SignupComponent ],
      providers: [UsersService, AngularFire, MdlDialogOutletService],
      imports: [
        AngularFireModule.initializeApp(firebaseConfig),
        ReactiveFormsModule,
        CommonModule,
        RouterTestingModule.withRoutes([
          // { path: 'settings/:collection/edit/:item', component: DummyComponent }
        ])
      ]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(SignupComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p>I get the following error: <code>No provider for MdlSnackbarService!</code> so what I did is adding <code>MdlSnackbarService</code> to the providers <code>configureTestingModule</code>:</p>

<pre><code>providers: [UsersService, AngularFire, MdlDialogOutletService, MdlSnackbarService]
</code></pre>

<p>but then, the error I've got is <code>Error: No component factory found for MdlSnackbarComponent. Did you add it to @NgModule.entryComponents?</code>
which I have no clue how to fix. I haven't found any answer related with unit testing.</p>

<p>Does anyone knows how to fix this?</p>
",https://stackoverflow.com/questions/42961887/angular2-unit-testing-a-component-that-uses-mdlsnackbarservice,"['unit-testing', 'angular', 'angular2-testing']",910,TRUE,0,1
Unit testing dynamically created controls in windows forms,"<p>I am using MVP pattern for a windows forms project and have left some of the creation logic in the view because I read that it shouldn't really be separated out from the form anyway. So now that I am coming to test the form I don't know how I can unit test methods like this. I have read about mocking but I'm not sure how to implement it with controls being created.</p>

<pre><code>    internal void createExamLabels(List&lt;string&gt; examList)
    {
        labelList = new List&lt;Label&gt;();

        foreach (string exam in examList)
        {
            LinkLabel label = new LinkLabel();
            label.Text = exam;
            label.Location = labelPoint;
            label.Click += examlabelLinkClicked;
            label.AutoSize = true;
            this.Controls.Add(label);
            labelList.Add(label);
            labelPoint.Y = labelPoint.Y + 30;

        }
    }
</code></pre>

<p>or this </p>

<pre><code>    private void Form_Paint(object sender, PaintEventArgs e)
    {
        int count = 1;
        while (count == 1)
        {
            e.Graphics.DrawImage(image, rec);
            count++;
        }


            DrawCircle(e.Graphics, point.X, point.Y);

    }

    private void DrawCircle(Graphics g, float x, float y)
    {

        using (Brush semiTransBrush = new SolidBrush(Color.Coral))
        {
            using (Pen pen = new Pen(Color.Aquamarine, 2))
            {
                g.DrawEllipse(pen, x, y, 50, 50);
                g.FillEllipse(semiTransBrush, x, y, 50, 50);

            }
        }
    }
</code></pre>
",https://stackoverflow.com/questions/46076798/unit-testing-dynamically-created-controls-in-windows-forms,"['c#', 'winforms', 'unit-testing']",110,TRUE,0,1
Unit testing angularjs - How to inject service dependency?,"<p>
I introduced a MyDataApiService dependency into ThingBuilderService, and now ThingBuilderService tests are failing. How do I mock MyDataApiService and tell ThingBuilderService about it in tests?
</p>

<pre><code>export default class ThingBuilderService {
    public static $inject = ['MyDataApiService'];

    public myData: any[];

    /**
    * Construct an instance of ThingBuilderService.
    *
    * @param {xyz.MyDataApiService} myDataApiService The MyDataApiService object.
    */
    constructor(myDataApiService: xyz.MyDataApiService) {
        myDataApiService.getSomeData()
        .then((response) =&gt; this.myData = response.data);
    }

    //...
}
</code></pre>

<p>Test: (I've included code showing part of what I <em>think</em> I need to do, but I don't understand how to fit the pieces together.</p>

<pre><code>describe('Thing Builder Service', () =&gt; {
    var service;
    var mockMyDataApiService = {};

    beforeEach(() =&gt; {
        var mockMyDataApiService.getSomeData = () =&gt; {
            var deferred = $q.defer();
            deferred.resolve({ data: [
                {
                    'ItemId': 1010101,
                    'Description': 'asdfasdf'
                },
                {
                    'ItemId': 1010102,
                    'Description': 'jkjkjkjk'
                } 
            ]});
            return deferred.promise;
        };

        // *********** now what? ***********
        // and do I have to do something to make '$q' 
        // available in the getSomeData function?

        angular.mock.module('abc.module');
        angular.mock.inject(_ThingBuilderService_ =&gt; {
            service = _ThingBuilderService_;
        });    
    });

    // tests here
    it('should ...', () =&gt; { ... });
});
</code></pre>



<p>
Test runs are giving errors like this: </p>

<blockquote>
  <p>Error: [$injector:unpr] Unknown provider: MyDataApiServiceProvider &lt;-
  MyDataApiService &lt;- ThingBuilderService</p>
</blockquote>

<p>and this:</p>

<blockquote>
  <p>Error: Base URL not defined for MyDataApiService</p>
</blockquote>
",https://stackoverflow.com/questions/47780813/unit-testing-angularjs-how-to-inject-service-dependency,"['angularjs', 'unit-testing', 'dependency-injection', 'karma-webpack']",872,TRUE,0,1
Jersey - Unit testing resource with spring-injected service,"<p>My question is similar to <a href=""https://stackoverflow.com/questions/28614846/how-to-in-memory-unit-test-spring-jersey"">this one</a>.</p>

<p><strong><em>Setting</em></strong>:
I have a <code>GreetingResource</code> which has a <code>Autowired</code> <code>GreetingService</code> to handle <code>GET</code> requests:</p>

<pre><code>@Path(""greetings"")
public class GreetingResource 
{

@Autowired
private GreetingService service;

@GET
@Produces(MediaType.TEXT_PLAIN_VALUE)
public String getHello()
{
    try
    {
        return service.greet(""world"");
    }
    catch(SQLException e)
    {
        System.out.println(""Request failed (500)"");
        e.printStackTrace();
        return null;
    }
}
}
</code></pre>

<p><strong><em>Problem</em></strong>: In my unit test I get
    org.springframework.beans.factory.NoSuchBeanDefinitionException: </p>

<pre><code>No qualifying bean of type 'demo.rest.jersey.spring.GreetingService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1466)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1097)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1059)
    at org.glassfish.jersey.server.spring.AutowiredInjectResolver.getBeanFromSpringContext(AutowiredInjectResolver.java:104)
    at org.glassfish.jersey.server.spring.AutowiredInjectResolver.resolve(AutowiredInjectResolver.java:96)
</code></pre>

<p><strong><em>Unit test class</em></strong>: In order to unit test this I have a <code>testContext.xml</code> which acts as application context for unit tests. It creates just one bean, namely the <code>TestConfig</code>:</p>

<pre><code>@Configuration
public class TestConfig 
{
    @Bean
    @Primary
    public GreetingService greetingService() throws SQLException
    {
        GreetingService service = Mockito.mock(GreetingService.class);
        when(service.greet(anyString())).thenReturn(""Hello"");
        return service;
    }
}
</code></pre>

<p>The <code>testContext.xml</code> should be loaded by the unit test and hence the correct beans created:</p>

<pre><code>public class Test_GreetingResource extends JerseyTest 
{
    @Override
    protected TestContainerFactory getTestContainerFactory() 
    {
        return new GrizzlyWebTestContainerFactory();
    }

    @Override
    protected DeploymentContext configureDeployment(){
        return ServletDeploymentContext
                .forServlet(new ServletContainer(new TestApp()))
                .addListener(ContextLoaderListener.class)
                .contextParam(""contextConfigLocation"", ""classpath:testContext.xml"")
                .build();
    }

    @Test
    public void doTest() throws SQLException
    {
        String response = target(""greetings"").request().get(String.class);
        assertEquals(""response incorrect"", ""Hello"", response);
        System.out.println(response);
    }
}
</code></pre>

<p><strong><em>Notes</em></strong>: The <code>TestApp</code> simply registers the <code>GreetingResource</code></p>

<pre><code>public class TestApp extends ResourceConfig 
{
    public TestApp()
    {
        register(GreetingResource.class);
        packages(""demo.rest.jersey.spring"");
    }
}
</code></pre>

<p>Here is also the <code>testContext.xml</code> that I mentioned above:</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;beans xmlns=""http://www.springframework.org/schema/beans""
    xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
    xsi:schemaLocation=""http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd""&gt;

    &lt;bean id=""testConfig"" class=""demo.rest.jersey.spring.TestConfig""&gt;&lt;/bean&gt;
&lt;/beans&gt;
</code></pre>

<p><strong><em>Additional question</em></strong>: If the <code>GreetingService</code> mock is created as a bean, can I somehow alter the mock behaviour? I.e. right now I specify in the <code>TestConfig</code> what response the mock should give but I might want to alter that behaviour from test to test.</p>

<p>Thanks for the help!</p>
",https://stackoverflow.com/questions/47713431/jersey-unit-testing-resource-with-spring-injected-service,"['java', 'spring', 'unit-testing', 'jersey-2.0']",1229,FALSE,0,1
Error in Unit testing with Angular js 1.6.6,"<p>Hi I am doing basic unit testing with Angularjs 1.5.6 and getting error.
        Using karma and Jasmine for unit testing.
        Please let me know what I am doing wrong.
        I have tried many hit and trail but no luck.
        is there any easy way to do this.   </p>

<pre><code>PhantomJS 2.1.1 (Windows 8 0.0.0) Name of group should return movie list FAILED
        TypeError: undefined is not a constructor (evaluating '$http.get(url)
                        .success') in src/omdb/service.js (line 9)
        httpPromise@src/omdb/service.js:9:25
        search@src/omdb/service.js:20:23
        spec/omdb/service.spec.js:17:23
        loaded@http://localhost:9876/context.js:162:17
</code></pre>

<p>My service.js is</p>

<pre><code>angular.module('omdb', [])
.factory('omdbApi', function ($http, $q) {
    var service = {};
    var baseUrl = 'http://www.omdbapi.com/?v=1&amp;';

    function httpPromise(url){
        var deferred = $q.defer();
        $http.get(url)
            .success(function (data) {
                //return response.data;
                return deferred.resolve(data);
            })
            .error(function(){
                deferred.reject();
            })
        return deferred.promise;
    }

    service.search = function (query) {
       httpPromise(baseUrl+'s='+encodeURIComponent(query))
    }
    service.find = function (id) {
        httpPromise(baseUrl+'i='+id)
    }
    return service;
})  
</code></pre>
",https://stackoverflow.com/questions/47242208/error-in-unit-testing-with-angular-js-1-6-6,"['javascript', 'angularjs', 'unit-testing', 'karma-jasmine']",60,FALSE,0,0
Function working live but not while unit testing,"<p>I'm trying to run some unit tests and I need to do the <code>[TestInitialize]</code> thing.</p>

<p>I found some info in <a href=""https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it"">this post</a>. I have no idea how to fix it because it makes no sense to me.</p>

<pre><code>[TestInitialize]
public void TestInitialize()
{
    mock = new Mock&lt;ILibraryRepository&gt;();

    books = new List&lt;Book&gt;()
    {
        new Book { Id = 0, Title = ""Title 0"", Edition = 0, PublicationDate = DateTime.Now, Author = { Id = 0, Name = ""Author 0"", DateOfBirth = DateTime.Now, DateOfDeath = DateTime.Now }, AuthorId = 0 },
        new Book { Id = 1, Title = ""Title 1"", Edition = 1, PublicationDate = DateTime.Now, Author = { Id = 1, Name = ""Author 1"", DateOfBirth = DateTime.Now, DateOfDeath = DateTime.Now }, AuthorId = 1 },
        new Book { Id = 2, Title = ""Title 2"", Edition = 2, PublicationDate = DateTime.Now, Author = { Id = 2, Name = ""Author 2"", DateOfBirth = DateTime.Now, DateOfDeath = DateTime.Now }, AuthorId = 2 }
    };

    mock.Setup(m =&gt; m.Books).Returns(books.AsQueryable());

    var controller = new BooksController(mock.Object);
}
</code></pre>

<p>It looks all good and fine. But when I run this test:</p>

<pre><code>[TestMethod]
public void IndexLoadsValid()
{
    // Arrange
    var controller = new BooksController(mock.Object);

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

    // Assert
    Assert.IsNotNull(result);
}
</code></pre>

<p>I get the following error:</p>

<blockquote>
  <p>object reference not set to an instance of an object</p>
</blockquote>

<p>And this is clear. It's null. But what I don't understand is <i>why</i> it's null?</p>

<p>The debugging says:</p>

<pre><code>System.NullReferenceException: 'Object reference not set to an instance of an object.'

Assignment2.Models.Book.Author.get returned null.
</code></pre>

<p>And this makes no sense to me because this function works when I fire up the program.</p>

<p>The <code>Book</code> model is here:</p>

<pre><code>public class Book
{
    [Key]
    public int Id { get; set; }

    [Required]
    public string Title { get; set; }

    [Display(Name = ""Publication date"")]
    public DateTime? PublicationDate { get; set; }

    public float? Edition { get; set; } // We might have a 2.5 edition. Rare but happens

    public int AuthorId { get; set; }

    public Author Author { get; set; }
}
</code></pre>

<p>I have no idea if it helps but my <code>ILibraryRepository</code> is here:</p>

<pre><code>public interface ILibraryRepository
{
    IQueryable&lt;Book&gt; Books { get; }
    IQueryable&lt;Author&gt; Authors { get; }

    Book Save(Book book);
    Author Save(Author author);

    void Delete(Book book);
    void Delete(Author author);
}
</code></pre>

<p>Any idea why I'm getting this error?</p>

<p>EDIT: I changed the <code>HomeController</code> to <code>BooksController</code>. I have no idea why I mixed the two here. <b>The error is happening in the <code>[TestInitialize]</code> part</b></p>
",https://stackoverflow.com/questions/47934564/function-working-live-but-not-while-unit-testing,"['c#', 'asp.net', 'entity-framework', 'unit-testing']",67,TRUE,0,3
"Ionic 3x: unit testing, mock for default controllers","<p>I'm writing an Ionic app and make test for code inner. I've got an <a href=""https://github.com/lathonez/clicker"" rel=""nofollow noreferrer"">example</a> and it's very helpful. But I'm using other stuff like Geolocation or <a href=""http://ionicframework.com/docs/api/components/loading/LoadingController/"" rel=""nofollow noreferrer"">Loading Controller</a> for my features and I don't know how should I mock them. For example I provide in <code>.spec.ts</code> </p>

<p><code>{ provide: LoadingController, useClass: LoadMock }</code></p>

<p>but I don't know what should I provide (which type and data). Error logs are not meaningful especially. What I should provide here for Loading Controller for example. It has methods: create, present and dismiss.</p>

<pre><code>export class LoadMock {

    public create(): type??? {
        return what???
    }

    public present(): type??? {
        return what???
    }

    public dismiss(): type??? {
        return what???
    }
}
</code></pre>
",https://stackoverflow.com/questions/44176092/ionic-3x-unit-testing-mock-for-default-controllers,"['angular', 'unit-testing', 'typescript', 'ionic-framework', 'ionic3']",734,TRUE,0,1
Unit testing in java using mockito and powermockito,"<p>I have a method</p>

<pre><code>public TaskProperty addTask()
{
     /*some operations
     *
     */
     mapToProperty();
 }

private TaskProperty mapToProperty()
{
    /**some op's**/
}
</code></pre>

<p>How to write unit test case for the <code>addTask()</code> without allowing the control to go inside <code>mapToProperty()</code> method. </p>

<p>How to mock the private method <code>mapToProperty()</code>? </p>
",https://stackoverflow.com/questions/43159749/unit-testing-in-java-using-mockito-and-powermockito,"['java', 'junit', 'mockito', 'powermockito']",232,TRUE,0,1
Unit testing Exception scenarios with cucumber in java,"<p>I am following BDD apprach and using cucumber to perform unit testing
 I have a class as given below</p>

<pre><code>public class EmployeeServiceImpl {

private static Log log = LogFactory.getlog(EmployeeServiceImpl.class);

@Autowired
private EmployeeDao employeeDao;

public void saveEmployee(Employee emp) throws Exception {
    try {
employeeDao.saveemployee(emp);
      } catch (Exception ex) {
            log.error(""Error occured ""+ex);
      }
  }
}
</code></pre>

<p>Can anyone please help me how to write exception scenario for the above code snippet? </p>
",https://stackoverflow.com/questions/41544476/unit-testing-exception-scenarios-with-cucumber-in-java,"['java', 'junit', 'cucumber']",1403,TRUE,-1,1
Eclipse plug-in development - unit testing e4 parts,"<p>I am trying to test an Eclipse plug-in with a E4 style view. I have created a test class inside a JUnit plug-in Test run configuration. But I'm struggling to even open the view. The old e3 way was to use the following snippet to open views:</p>

<pre><code>PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getActivePage().showView(""some view id"")
</code></pre>

<p>In e4, we can use a <code>EPartService</code> (<a href=""https://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fe4%2Fui%2Fworkbench%2Fmodeling%2FEPartService.html"" rel=""nofollow noreferrer"">documentation</a>) instead. However, I'm not sure how to access it. Trying to inject it does not work. This is what I have tried:</p>

<pre><code>public class MyTest {

@Inject EPartService partService;

@Test
public void testOne() {
// partService is still null here...
</code></pre>

<p>I've also tried adding the @PostConstruct annotation to the test method, with no luck. Shouldn't this work, since it is running as a JUnit plug-in test, which I assume has an Eclipse context with a part service ready?</p>

<p>According to <a href=""http://www.vogella.com/tutorials/Eclipse4Testing/article.html"" rel=""nofollow noreferrer"">this</a> article, it should also be possible to create a <code>Display</code> class and an associated Shell, which can be passed to the view's <code>createPartControl</code> method. I have tried this in the test method as well:</p>

<pre><code>    Display display = Display.getCurrent();
    Shell shell = new Shell(display);
    IEclipseContext context = EclipseContextFactory.create();
    IPartService partService = mock(IPartService.class);
    context.set(IPartService.class, partService);
    context.set(Composite.class, shell);
    view = ContextInjectionFactory.make(InspView.class, context);
    shell.open();
</code></pre>

<p>I need the IPartService (not to be confused with the EPartService...) because the view needs it. This actually works. But, as you can see, I need to mock an IPartService and hand it to the Eclipse context. This does not give me what I want. Instead, I want an Eclipse context with all the services instantiated. Is this possible? Which approach is the most correct? Using Display+Shell, or EPartService?</p>

<p>Thanks!</p>

<p>UPDATE:
It is possible to open the part using the following:</p>

<pre><code>EPartService partService = 
PlatformUI.getWorkbench().getService(EPartService.class);
partService.showPart(VIEW_ID, PartState.ACTIVATE);
</code></pre>

<p>Is that a good approach?</p>
",https://stackoverflow.com/questions/46748621/eclipse-plug-in-development-unit-testing-e4-parts,"['unit-testing', 'eclipse-plugin', 'e4']",72,FALSE,0,0
Unit Testing a C# function that uses Console.ReadLine(),"<p>The function below uses <code>TryParse()</code> to parse a <code>Console.Readline()</code> value</p>

<pre><code>public uint parse_input(string input)
{
    uint parseNumber;

    while (!uint.TryParse(input, out parseNumber))
    {
        Console.Write(""The value must be of integer type, please try again: "");
    }

    return parseNumber;
}
</code></pre>

<p>where <code>input</code> is <code>string input = Console.ReadLine();</code> defined in another method.</p>

<p>If I enter an erroneous value, I get stuck in a loop as the input value is set.</p>

<p>However, if I replace <code>input</code> with <code>Console.ReadLine()</code>:</p>

<pre><code>while (!uint.TryParse(Console.ReadLine(), out parseNumber))
{
    Console.Write(""The value must be of integer type, please try again: "");
}
</code></pre>

<p>The function works, as <code>input returned</code> is replaced with <code>System.Console.ReadLine</code> returned.</p>

<p>I want to be able to unit test this function, so ideally, I would like how I initially defined it to work.  Any ideas?  Thanks!</p>
",https://stackoverflow.com/questions/45334401/unit-testing-a-c-function-that-uses-console-readline,"['c#', 'unit-testing', 'console', 'console-application']",890,TRUE,0,1
Unit testing methods with dependencies (with no interfaces),"<p>Starting with unit testing, I wonder how to test our old code, that looks something like that:</p>

<pre><code>public Player DetermineWinner(Player a, Player b)
{
   if(a.Age&gt;b.Age)
    ....  
   ///few more conditions checking properties of both players
}

class Player
{
  public Player (DBConnection c, world w, DateTime logTime)
  {} //not easy to mock...
}
</code></pre>

<p>How to mock that? I understand that if the Player implemented an interface, I could simply create a mock and pass it in the unit test with desired values, but that is not the case here.
The Player class is instantiated using various parameters so I cannot simply create an instance during the unit test and pass it - it depends on various external objects.
I would need to mock the Player object and set its properties at the same time so that the tests are deterministic. What is the best approach to start with?  </p>

<p>Should I next time use interfaces to decouple that?</p>
",https://stackoverflow.com/questions/42212117/unit-testing-methods-with-dependencies-with-no-interfaces,"['c#', 'unit-testing', 'mocking']",476,TRUE,0,2
Unit testing SBT code within the local project,"<p>I have an SBT project, within which I have defined a <a href=""http://www.scala-sbt.org/0.12.2/docs/Howto/generatefiles.html"" rel=""nofollow noreferrer"">source generator</a> that parses some DB migration scripts in order to make the current DB version available to the application at compile-time.</p>

<p>For example, I might have the following resources:</p>

<pre><code>subproject1/src/main/resources/db/migration/
  |- V1__Baseline.sql
  |- V2__AddCustomerTable.sql
  |- V2_1__Refactor.sql
</code></pre>

<p>And I would require my source generator to create a scala object with the field <code>val version = ""2.1""</code>.</p>

<p>The SBT project is structured as:</p>

<pre><code>project/
  |- build.sbt
  |- SchemaVersionParser.scala
</code></pre>

<p>Where <code>SchemaVersionParser</code> defines the utility functions that are used by <code>build.sbt</code> in order to parse the resources and generate the appropriate file.</p>

<p>Now since this is a key component of my app, I'd like to ensure that the functions in <code>SchemaVersionParser</code> which extract and sort the versions are unit tested.</p>

<p>Is there any supported means of unit testing SBT code residing locally in the one project? I know I can do this if I create a separate SBT plugin, however it'd be nice if I could avoid this.</p>
",https://stackoverflow.com/questions/41800608/unit-testing-sbt-code-within-the-local-project,"['scala', 'unit-testing', 'sbt']",113,TRUE,0,1
Unit testing a complex renderer class (Best Practices),"<p>I'm trying to test a class which purpose is taking a specification of what to do with a BufferedImage array and proccess it.</p>

<p>I'm concerned about how to aproach this task, it makes no sense to me just duplicate the function code on the test in order to generate a ""expected bufferedImage array"" and check if the generated BufferedImages are equals to the returned by the class methods.</p>

<p>I've read some slightly similar questions here, but the answers was ""charge expected images from file and check with returned ones by class methods"" but that sounds real hard to maintain if the proccess changes, new methods are added to the renderer class, it's hard or imposible pregenerate a resulting image or simply the class is refactorized and functions are splitted.</p>

<p>My actual question might be: Is there a little more elegant, ""better to maintain"" way to do that. I haven't so much experience with unit testing so i'm not sure about how to do this.</p>

<p><strong>EDIT:</strong> sorry for the long code, i simplified and translated it. Excuse me if i did a bad translation. english it's not my main language.</p>

<pre><code>public class Renderer extends SwingWorker&lt;BufferedImage[], Integer&gt;
{
  private Device device;
  private Main main;
  private Controller controller;
  public static final int FPS = 25;



  public Renderer(Device device, Main main, Controller controller)
  {
    this.device = device;
    this.main = main;
    this.controller = controller;
  }

  @Override
  protected BufferedImage[] doInBackground() throws Exception
  {

    // rendering image array
    BufferedImage[] output = renderize(main.getActualEscene());
    LOG.log.log(Level.INFO, ""Rendering"");
    // getting how many times should repeat 
    String stringRepeat =
        main.getActualEscene().getProperties().get(TextProperties.REPEAT.toString());
    int repeat = (stringRepeat == null) ? 1 : Integer.parseInt(stringRepeat);
    // getting text speed
    String stringFps =
        main.getActualEscene().getProperties().get(TextProperties.TEXT_SPEED.toString());
    int fps = (stringFps == null) ? FPS : Integer.parseInt(stringFps);
    if (!this.isCancelled()) // if this task is not cancelled
    {
      // we create a pre-viewer
      controller.setPreviewer(
          new Previewer(controller, repeat, fps, main.getActualEscene()));
      SwingUtilities.invokeLater(new Runnable()
      {// sincronizing this code with AWT thread

        @Override
        public void run()
        { // if it's not cancelled
          if (controller.getPreviewer() != null
              &amp;&amp; !controller.getPreviewer().isCancelled())
          {
            controller.getPreviewer().execute(); //execute the task
          }

        }

      });
    }


    return output;
  }

  /**
   * Renders a scene and transforms it in a image array, then save it to the scene
   * 
   * @param scene -&gt; scene 
   * @return an array with the scene frames
   */
  public BufferedImage[] renderize(Scene scene)
  {
    BufferedImage[] output = null; // end result
    BufferedImage[] base = new BufferedImage[1]; // base image
    BufferedImage[] animationImages = null; // animation layer
    BufferedImage[] textLayer = null; // text layer
    BufferedImage[] overLayer = null; // overlayer


    // omitted long process to retrieve image properties

    // once the text properties are retrieved if it's not null it will be rendered
    if (text != null)
    {
      String backgroundColorString =
          scene.getProperties().get(TextProperties.BACKGROUND_COLOR.toString());
      int backGroundcolorInt = Integer.parseInt(backgroundColorString);
      if (animationImages != null) // if there is an animation layer we create a same size text layer
      {
        textLayer = new BufferedImage[animationImages.length];
      } else 
      {
        textLayer = new BufferedImage[1];
      }
      for (int i = 0; i &lt; textLayer.length; i++)
      {
        textLayer[i] = new BufferedImage(device.getWidth(), device.getHeight(),
            BufferedImage.TYPE_INT_ARGB);
      }
      String font = scene.getProperties().get(TextProperties.FONT.toString());
      int lettersHeigth = device.getHeight() / 3;
      int colorNumber =
          Integer.parseInt(scene.getProperties().get(TextProperties.TEXT_COLOR.toString()));
      textLayer = addTextToAImage(text, font, lettersHeigth, new Color(colorNumber),
          new Color(backGroundcolorInt), textLayer);
    }
    // has it overlayer?

    if (scene.getProperties().containsKey(AnimationProperties.OVER.toString())) // if it has over
    {
      String over = scene.getProperties().get(AnimationProperties.OVER.toString());
      overLayer =
          this.readingImagesFromAnimation(OverLibrary.getInstance().getOverByName(over));
    }

    // mixing layers
    output = base; // adding base base
    if (animationImages != null) // if there is animation layer we add it
    {
      output = mixingTwoImages(output, animationImages);
    }
    if (textLayer != null) // if there is text layer
    {
      output = mixingTwoImages(output, textLayer);
    }
    if (overLayer != null) //if there is overlayer
    {
      output = mixingTwoImages(output, overLayer);
    }
    // delimiting image operative zone.
    output = delimite(output, device);
    main.getActualEscene().setPreview(new Preview(output));
    LOG.log.log(Level.INFO, ""Rendering scene finished: "" + scene.getNombre());
    return output;

  }

  /**
   * Apply the device mask to an image. Delimiting the scene operative zone.
   * 
   * @param input -&gt; BufferedImage array which need to be delimited
   * @param device -&gt; device which it mask need to be applied
   * @return An BufferedImage array with a delimited image for the device.
   */
  private BufferedImage[] delimite(BufferedImage[] input, Device device)
  {
    BufferedImage[] output = new BufferedImage[input.length];
    for (int i = 0; i &lt; output.length; i++) // copy all original frames
    {
      output[i] = new BufferedImage(device.getWidth(), device.getHeight(),
          BufferedImage.TYPE_INT_ARGB);
      Graphics2D graphics = output[i].createGraphics();
      graphics.drawImage(input[i], 0, 0, null);
    }

    for (int i = 0; i &lt; output.length; i++) // for each frame
    {
      for (int j = 0; j &lt; output[i].getHeight(); j++) // for each row
      {
        for (int k = 0; k &lt; output[i].getWidth(); k++) // for each column
        {
          if (!device.estaEnZonaOperativa(j, k)) // if the coordinate is not in the operative zone
          {
            int pixel = 0x00000000; // we create a transparent pixel
            output[i].setRGB(j, k, pixel); // set the original pixel with this new one
          }

        }
      }
    }
    return output;
  }

  /**
   * method that reads an animation images and returns it into an array
   * 
   * @param animation -&gt; animación de la que obtendremos sus image
   * @return array de BufferedImage con los frames de la animación ordenados por orden de lectura
   *         ascendente.
   */
  private BufferedImage[] readingImagesFromAnimation(Animation animation)
  {
    BufferedImage[] output = new BufferedImage[animation.getData().length];
    for (int i = 0; i &lt; animation.getData().length; i++) // for each frame
    {
      try
      {
        File ruta = animation.getData()[i]; // getting its path
        output[i] = ImageIO.read(ruta); // reading from the path and save it into output
      } catch (IOException e)
      {
        LOG.log.log(Level.SEVERE, ""error reading animation file: "" + animation.getData()[i],
            e);
      }
    }
    return output;
  }

  /**
   * create a text layer an add it to the image parameter center
   * 
   * @param text -&gt; text to include
   * @param font -&gt; font of the text
   * @param size -&gt; size
   * @param color -&gt; text color
   * @param image -&gt; image you want to add text
   * @return a text layer that need to be mixed with original one.
   */
  private BufferedImage[] addTextToAImage(String text, String font, int size, Color color,
      Color backgroundColor, BufferedImage[] image)
  {
    // we set the size of the output as the same of the original image
    BufferedImage[] output = new BufferedImage[image.length];
    for (int i = 0; i &lt; image.length; i++) // for each frame
    {
      output[i] = new BufferedImage(image[i].getWidth(), image[i].getHeight(),
          BufferedImage.TYPE_INT_ARGB); // we create a single new image
      Graphics2D graphics = output[i].createGraphics(); // get its graphics
      // calculate for metrics
      Font font = new Font(font, Font.PLAIN, size); // create a font
      graphics.setFont(font); // setting it into the graphics
      FontMetrics fontMetrics = graphics.getFontMetrics(font); // generating metric object

      // calculate the text coordinates
      int x = (image[i].getWidth() - fontMetrics.stringWidth(text)) / 2;
      int y = ((image[i].getHeight() - fontMetrics.getAscent() - fontMetrics.getDescent()) / 2)
          + fontMetrics.getAscent();
      int width = fontMetrics.stringWidth(text); // usefull metric to set a brackground
      int height = fontMetrics.getAscent() + fontMetrics.getDescent(); 

      // setting a background
      graphics.setColor(backgroundColor);
      graphics.fill(new Rectangle(x, y - fontMetrics.getAscent(), width, height));

      // drawing text
      graphics.setColor(color); // setting a color for text
      graphics.drawString(text, x, y); 
    }
    return output;
  }

  /**
   * method to join two bufferedImage arrays and mix them. The shortest array will be played on loop
   * 
   * WARNIN: the images needs to has the same resolution
   * 
   * @param image -&gt; image mixed as background
   * @param image2 -&gt; image mixed as foreground
   * @return a mixed image array.
   */
  private BufferedImage[] mixingTwoImages(BufferedImage[] image, BufferedImage[] image2)
  {
    // checking no empty images.
    if (image.length == 0 || image2.length == 0) 
    {
      RuntimeException exception =
          new RuntimeException(""empty images"");
      LOG.log.log(Level.SEVERE, exception.getMessage(), exception);
      throw exception;
    }
    int width = Math.max(image[0].getWidth(), image2[0].getWidth());
    int height = Math.max(image[0].getHeight(), image2[0].getHeight());
    // creating a sequence of the longest size of them
    BufferedImage[] output = new BufferedImage[Math.max(image.length, image2.length)];
    for (int i = 0; i &lt; output.length; i++) // for each frame
    {
      // we create a frame
      output[i] = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
      Graphics g = output[i].getGraphics();
      // mixing the frame 
      if (image.length &gt; image2.length) // if the first array is longer
      {
        g.drawImage(image[i], 0, 0, null);
        g.drawImage(image2[i % image2.length], 0, 0, null);
      } else if (image.length &lt; image2.length) // if the second array is longer
      {
        g.drawImage(image[i % image.length], 0, 0, null);
        g.drawImage(image2[i], 0, 0, null);
      } else // bot of the same size
      {
        g.drawImage(image[i], 0, 0, null);
        g.drawImage(image2[i], 0, 0, null);
      }
    }
    return output;
  }
</code></pre>
",https://stackoverflow.com/questions/47633191/unit-testing-a-complex-renderer-class-best-practices,"['java', 'testing', 'rendering', 'bufferedimage']",120,FALSE,0,0
Unit testing log nodes in Apache camel routes,"<p>Suppose I have the following camel route:</p>

<pre><code>.from(""direct:start"")
.log(""received ${body} message"")
.to(""mock:end"");
</code></pre>

<p>How would you test that the message ""received Camel rocks!"" message is logged when you send a ""Camel rocks!"" message to the direct:start endpoint</p>
",https://stackoverflow.com/questions/43881586/unit-testing-log-nodes-in-apache-camel-routes,['apache-camel'],954,TRUE,0,3
Unit testing issue with bundling in a SPA,"<p>I am working on a single page app with bundling. It is taking too much time to unit test when i make a change in the js file as i have to go through the following steps</p>

<ol>
<li>Gulp (Happens when project is compiled in Visual studio) </li>
<li>Open chrome and start right from the login page</li>
<li>Navigate to the page by clicking next-> next->next.</li>
</ol>

<p>Is there any trick available to avoid going through these steps everytime??</p>
",https://stackoverflow.com/questions/44257014/unit-testing-issue-with-bundling-in-a-spa,"['javascript', 'angularjs']",24,TRUE,-2,1
Python unit testing for code containing with statement,"<p>I have the following function I'd like to write tests for.</p>

<pre><code>def _find_latest_backup(self):
    """"""
    Find the latest backup in S3 bucket
    """"""
    aem_instance_type = self.instance_of
    if aem_instance_type == 'standby':
        aem_instance_type = 'author'

    with S3Bucket(name=self.s3_bucket) as bucket:
        objects = bucket.objects.filter(
            Prefix=self.s3_folder + ""/aem_"" + aem_instance_type,
        )
        print objects
        try:
            return max(objects, key=attrgetter('last_modified')).Object()
        except ValueError:
            self.logger.info(""No backups found in %s/aem_%s"", self.s3_folder, aem_instance_type)
</code></pre>

<p>My unittest looks like this,</p>

<pre><code>    @pytest.mark.parametrize('s3_obj_summaries,latest_key', [
        (
            [
                MockS3ObjectSummary(
                    key='aem-cpp-dev-01/backup1',
                    last_modified=datetime(2017, 1, 10, 15, 0)
                ),
                MockS3ObjectSummary(
                    key='aem-cpp-dev-01/backup2',
                    last_modified=datetime(2017, 2, 11, 15, 0)
                ),
                MockS3ObjectSummary(
                    key='aem-cpp-dev-01/backup3',
                    last_modified=datetime(2017, 3, 12, 15, 0)
                ),
                MockS3ObjectSummary(
                    key='aem-cpp-dev-01/backup4',
                    last_modified=datetime(2017, 4, 12, 15, 0)
                ),
            ],
            ""aem-cpp-dev-01/backup4""
        ),
    ])
    def test_find_latest_backup(self, mocker, s3_obj_summaries, latest_key):
        """""" Test getting the latest backup file """"""
        bucket = mocker.patch('aem_management.restore.S3Bucket')
        bucket.__enter__.objects.filter.return_value = True
        restore_manager = blank_restore_manager()
        assert restore_manager._find_latest_backup().key == latest_key
</code></pre>

<p>However I don't get the correct value for return_value. Output I'm seeing is</p>

<pre><code> with mocker.patch('aem_management.restore.S3Bucket', return_value=mock_bucket) as bucket:
            restore_manager = blank_restore_manager()
&gt;           assert restore_manager._find_latest_backup().key == latest_key
E           AttributeError: 'NoneType' object has no attribute 'key'
</code></pre>

<p>This is the first time I'm writing tests for code containing with statement and do I need do so anything different to make this work?</p>

<p>Many thanks,</p>
",https://stackoverflow.com/questions/46045648/python-unit-testing-for-code-containing-with-statement,"['python', 'unit-testing', 'pytest']",411,TRUE,-2,1
Angular2: Unit testing a component with Route resolve,"<p>I have a component that depends on a data from Route Resolve.
Following is the code snippet of the router</p>

<pre><code>           {
                path: 'attachment',
                component: SgCreateAttachmentComponent,
                resolve: {
                    referenceData: SgCreateAttachmentResolve
                },
                data: {
                    'seq' : 5
                },
                canActivate: [SgCreateCanActivateGaurd]
            }
</code></pre>

<p>Inside the component I fetch the resolve data inside ngOnInit.</p>

<pre><code>ngOnInit() {

    this.standardAttachmentCategories = this._activatedRoute.snapshot.data['referenceData'].json();

   }
</code></pre>

<p>I am trying to unit test the ngOnInit function of the component. Following is a code snippet from my spec.</p>

<pre><code>it('should ensure ngOnInit is called', () =&gt; {
    fixture.detectChanges();
});
</code></pre>

<p>Also, i have the following configuration of the test bed</p>

<pre><code>beforeEach(async(() =&gt; {

        TestBed.configureTestingModule({
            imports: [HttpModule, SgCreateModule],
            providers: [FormBuilder, { provide: SgCreateService, useClass: SgCreateMockService },
                { provide: SgCreateAttachmentService, useClass: SgCreateAttachmentServiceMock },
                SgCreateModelService,
                { provide: Router, useClass: RouterStub },
                  { provide: ActivatedRoute, useClass: ActivatedRouteStub },
                { provide: XHRBackend, useClass: MockBackend }
            ]
        })
            .compileComponents();
        fixture = TestBed.createComponent(SgCreateAttachmentComponent);
        comp = fixture.componentInstance;



    }));
</code></pre>

<p>But, executing the above test throws error: </p>

<p>Cannot read property 'referenceData' of undefined</p>

<p>I have also tried the following </p>

<pre><code>  it('should ensure ngOnInit is called', () =&gt; {
        const activatedRouteStub = fixture.debugElement.injector.get(ActivatedRoute);
        activatedRouteStub.testParams = { data: new Response() };
        fixture.detectChanges();
    });
</code></pre>

<p>But i am facing the same issue.</p>
",https://stackoverflow.com/questions/45811379/angular2-unit-testing-a-component-with-route-resolve,"['angular', 'jasmine', 'angular2-testing']",1269,FALSE,0,0
Unit testing in flask with a global setup,"<p>I have a simple flask app that I've got deployed in Elastic Beanstalk and I'm trying to write some unit tests for it and having some difficulty.</p>

<p>The app, when it starts, needs to talk to EC2's parameter store ( via ssm ), to download a secret key, which is decrypted via kms.  If you aren't familiar with elasticbeanstalk - when the the flask app is deployed, it's done via httpd/wsgi.</p>

<p>The 'secret' parameter only ever needs to retrieved once - I don't want to go out to ssm for every request to flask.</p>

<p>The problem is that I had something like this:</p>

<pre><code>import flask
application = flask.Flask(__name__)

secret = get_ssm_parameter()
application.config['SECRET'] = secret

@application.route('/some/route')
def do_something():
    # does something
</code></pre>

<p>When I try and test this application, as soon as I do the 'import myapp' into the unit test, it obviously tries to run get_ssm_parameter, which I don't want, but I'm unsure how to create some global setup functions without calling them as soon as I do an import.  So I need some way to import myapp, so that I can then mock out the get_secret before it's called.</p>

<p>The best I've been able to come up with is something like:</p>

<pre><code>def get_secret()
    if application.config['SECRET'] is None:
        application.config['SECRET'] = get_ssm_parameter()
    return application.config['SECRET']

@application.route('/some/route')
def route_that_needs_secret():
    secret = get_secret()
    # do some stuff
</code></pre>

<p>Where upon I retrieve the secret once it's needed in a route, and I set it into the application.config, which keeps it around globally.</p>

<p>Is there a pattern for initializing expensive setup once in a Flask app and keeping those results around between requests?  I wanted to try and stay away from storing the secret in a cache anywhere, but I'm not sure how to keep it around between requests otherwise.</p>
",https://stackoverflow.com/questions/43833860/unit-testing-in-flask-with-a-global-setup,"['python', 'unit-testing', 'flask']",138,FALSE,0,0
Karma - Unit Testing Angular Controller with Mocked API,"<p>I wrote some unit tests for an angular factory that mock the response with a fake promise using $q.resolve({}). I'm now writing the controller test and want to call the factory from the controller and assign the resolved mock factory response to the controller scope (vm), and verify the data. Is this the proper way to test a factory from within a controller?</p>

<p><strong><em>factory test</em></strong></p>

<pre><code>describe('getVICs()', function() {
  var vicFactory, $q, $httpBackend, result;
  beforeEach(module('vicModule'));
  beforeEach(inject(function(_vicFactory_, _$q_, _$httpBackend_) {
    vicFactory = _vicFactory_;
    $q = _$q_;
    $httpBackend = _$httpBackend_;
  }));
  beforeEach(function() {
    result = {};
    spyOn(vicFactory, 'getVICs').and.callThrough(function() {
      var deferred = $q.defer();
      return deferred.promise;
    });
  });
  it('should be defined', function() {
    expect(vicFactory.getVICs()).toBeDefined();
  });
  it('should return list of vics', function() {
    var vicList = {
      ""results"": [
        {
          ""version"": 5
        },
        {
          ""version"": 1
        }
      ]
    };
    var qs = '?sort=version&amp;dir=DESC&amp;page=1&amp;limit=10&amp;status=ACTIVE';
    $httpBackend.expectGET('/path/to/my/api' + qs).respond(200, vicList);
    $httpBackend.whenGET('http://localhost:3000/path/to/my/api' + qs).respond(200, $q.when(vicList));
    vicFactory.getVICs(qs)
    .then(function(response) {
      result = response;
    });
    // flush pending HTTP requests
    $httpBackend.flush();
    expect(result.data.results).toBeDefined();
  });
});
</code></pre>

<p><strong><em>factory</em></strong></p>

<pre><code>function getVICs(query) {
  return $http.get('/path/to/my/api' + query)
  .then(function(response) {
    return response;
  });
}
</code></pre>

<p><strong><em>controller test</em></strong></p>

<pre><code>describe('vicController', function() {
  var $controller, vicController, vicFactory, $q, $scope, $httpBackend, deferred;
  var vicList = {
    ""results"": [
      {
        ""version"": 5
      },
      {
        ""version"": 1
      }
    ]
  };
  var qs = '?sort=version&amp;dir=DESC&amp;page=1&amp;limit=10&amp;status=ACTIVE';
  beforeEach(module('vicModule'));
  beforeEach(inject(function(_$controller_, _vicFactory_, _$q_, _$rootScope_, _$httpBackend_, _$httpParamSerializer_) {
    $controller = _$controller_;
    vicFactory = {
      getVICs: function () {
        deferred = $q.defer();
        return deferred.promise;
      }
    };
    $q = _$q_;
    $rootScope = _$rootScope_;
    $scope = $rootScope.$new();
    $httpBackend = _$httpBackend_;
    $httpParamSerializer = _$httpParamSerializer_;
    spyOn(vicFactory, 'getVICs').and.callThrough();
    vicController = $controller('vicController', {vicFactory: vicFactory});
    deferred.resolve(vicList);
  }));
  it('should be defined', function() {
    expect(vicController).toBeDefined();
  });
  it('should call getVICs() on load', function() {
    $httpBackend.expectGET(''/path/to/my/api?' + qs).respond(200, vicList);
    $scope.$digest();
    expect(vicFactory.getVICs).toHaveBeenCalledWith(qs);
    expect($scope.vicList).toEqual(vicList);
  });
});
</code></pre>

<p><strong><em>controller</em></strong></p>

<pre><code>  angular.module('vicModule')
  .controller('vicController', vicController);
  vicController.$inject = [
    'vicFactory'
  ];

  function vicController(vicFactory) {
    var vm = this;
    var qs = '?sort=version&amp;dir=DESC&amp;page=1&amp;limit=10&amp;status=ACTIVE';
    vicFactory.getVICs(qs)
    .then(function(response) {
      console.log('vic controller success');
      console.log(response);
      vm.vicList = response;
    }, function(response) {
      console.log('vic controller error');
      console.log(response);
    });
  }
</code></pre>

<p><strong><em>Fixed</em></strong></p>

<p>Got this working by injecting $q and $scope, setting vicFactory in beforeEach, updating spy, and then resolving the deferred with the expected data set after controller initialization. The controller test spec has been updated, hope this help someone.</p>
",https://stackoverflow.com/questions/45473107/karma-unit-testing-angular-controller-with-mocked-api,"['angularjs', 'unit-testing', 'karma-jasmine']",182,FALSE,0,0
unit testing for unverified user trying to login,"<p>I've been trying to test for a user that hasn't been verified.</p>

<pre><code>class TestLoginApi(TestCase):
    URL = '/rest-auth/login/'
    EMAIL = 'testuser@test
    PASSWORD = 'password'
    DATA = {'email': EMAIL, 'password': PASSWORD}

    @classmethod
    def setUpTestData(cls):
        cls.user = get_user_model().objects.create_user(username='testuser', email=cls.EMAIL,
                                                    password=cls.PASSWORD)

def test_login_api_without_verification(self):
    response = self.client.post(self.URL, self.DATA, format='json')
</code></pre>

<p>The ""response"" line throws the following error</p>

<p><strong>Error</strong></p>

<blockquote>
  <p>Traceback (most recent call last):</p>
  
  <p>File ""/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/case.py"", line 59, in testPartExecutor
      yield</p>
  
  <p>File ""/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/case.py"", line 601, in run
      testMethod()</p>
  
  <p>File ""/Users/docdocengineering3/GitHub/website/project/authorization/Tests/test_login.py"", line 34, in test_login_api_without_verification
      response = self.client.post(self.URL, self.DATA, format='json')</p>
  
  <p>File ""/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/test/client.py"", line 548, in post
      secure=secure, **extra)</p>
  
  <p>File ""/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/test/client.py"", line 350, in post
      secure=secure, **extra)</p>
  
  <p>File ""/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/test/client.py"", line 416, in generic
      return self.request(**r)</p>
  
  <p>File ""/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/test/client.py"", line 501, in request
      six.reraise(*exc_info)</p>
  
  <p>File ""/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/utils/six.py"", line 686, in reraise
      raise value</p>
  
  <p>File ""/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/core/handlers/exception.py"", line 41, in inner
      response = get_response(request)</p>
  
  <p>File ""/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/core/handlers/base.py"", line 187, in _get_response
      response = self.process_exception_by_middleware(e, request)</p>
  
  <p>File ""/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/core/handlers/base.py"", line 185, in _get_response
      response = wrapped_callback(request, *callback_args, **callback_kwargs)</p>
  
  <p>File ""/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/views/decorators/csrf.py"", line 58, in wrapped_view
      return view_func(*args, **kwargs)</p>
  
  <p>File ""/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/views/generic/base.py"", line 68, in view
      return self.dispatch(request, *args, **kwargs)</p>
  
  <p>File ""/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/utils/decorators.py"", line 67, in _wrapper
      return bound_func(*args, **kwargs)</p>
  
  <p>File ""/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/views/decorators/debug.py"", line 76, in sensitive_post_parameters_wrapper
      return view(request, *args, **kwargs)</p>
  
  <p>File ""/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/utils/decorators.py"", line 63, in bound_func
      return func.<strong>get</strong>(self, type(self))(*args2, **kwargs2)</p>
  
  <p>File ""/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/rest_auth/views.py"", line 49, in dispatch
      return super(LoginView, self).dispatch(*args, **kwargs)</p>
  
  <p>File ""/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/rest_framework/views.py"", line 489, in dispatch
      response = self.handle_exception(exc)</p>
  
  <p>File ""/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/rest_framework/views.py"", line 449, in handle_exception
      self.raise_uncaught_exception(exc)</p>
  
  <p>File ""/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/rest_framework/views.py"", line 486, in dispatch
      response = handler(request, *args, **kwargs)</p>
  
  <p>File ""/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/rest_auth/views.py"", line 92, in post
      self.serializer.is_valid(raise_exception=True)</p>
  
  <p>File ""/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/rest_framework/serializers.py"", line 237, in is_valid
      self._validated_data = self.run_validation(self.initial_data)</p>
  
  <p>File ""/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/rest_framework/serializers.py"", line 435, in run_validation
      value = self.validate(value)</p>
  
  <p>File ""/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/rest_auth/serializers.py"", line 105, in validate
      email_address = user.emailaddress_set.get(email=user.email)</p>
  
  <p>File ""/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/db/models/manager.py"", line 85, in manager_method
      return getattr(self.get_queryset(), name)(*args, **kwargs)</p>
  
  <p>File ""/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/db/models/query.py"", line 380, in get
      self.model._meta.object_name</p>
  
  <p>Exception: EmailAddress matching query does not exist.</p>
</blockquote>

<p>I have no idea why this is happening. It isn't a setup problem as I've tried actually running the system, creating a user (not verifying) and when I ""PostMan"" the same link, I get the correct error back</p>

<pre><code>{""non_field_errors"": [ ""E-mail is not verified."" ] }
</code></pre>

<p>So it works in the actual product but not when testing. Anyone know why? Any help is greatly appreciated.</p>

<p>This is the only test that I can't get to work, all the rest runs correctly.</p>
",https://stackoverflow.com/questions/45853553/unit-testing-for-unverified-user-trying-to-login,"['python-3.x', 'django-rest-framework', 'django-allauth', 'django-rest-auth']",315,FALSE,0,1
Unit testing mongoose validation with promise resolve/reject,"<p>I'm struggling to find a way to unit test the validation of a field in  mongoose. I currently have the following test:</p>

<pre><code>it('should be invalid if googleId is empty', () =&gt; 
  testBook.googleId = '';
  const newBook = new Book(testBook);
  return newBook.validate().catch((err) =&gt; {
    should.exist(err.errors.googleId);
  });
});
</code></pre>

<p>This test is not working as intended because, if I have a correct validation for <code>googleId</code>, the test will pass because it will assert the <code>err.errors.googleId</code> exists, but if I don't have any validation for <code>googleId</code>, it will also pass because the <code>.catch()</code> never gets called and it assumes the test is passing.</p>

<p>I've tried putting <code>should.fail()</code> inside a <code>.then()</code>, but that way it always ends up in <code>.catch()</code> but with different errors, if there's no validation it will be catched with the <code>should.fail()</code> error, if there's validation it will catch with the model validation error.</p>

<p>What would be the best way to achieve this kind of testing? </p>

<p>Thanks alot!</p>

<p>EDIT:
I've tried using the callback of <code>newBook.validate()</code> and it works, but I never use callbacks for model methods, I always tend to use promises, so should I be using the callback in this particular case or there's still a better way to handle it using promises?</p>
",https://stackoverflow.com/questions/46720132/unit-testing-mongoose-validation-with-promise-resolve-reject,"['node.js', 'unit-testing', 'mongoose', 'mocha.js', 'chai']",665,TRUE,0,2
Unit testing for a function (tolower) using pointers,"<p>I have this function that changes the string to all lower cases.</p>

<p>I am trying to create a unit test for this function, but I think I am passing the argument wrong, and I get this error.</p>

<pre><code>Segmentation Fault (core dumped)
</code></pre>

<p>This is my code.</p>

<pre><code>void example (char const * str1, int length, char * str2) {
    int i;
    for(i = 0; i &lt; length; i++) {
        *(str2 + i) = putchar(tolower( *(str1 + i) ));
    }
}

void testexample() {
    char * str1 = ""TEST"";
    char * str2 = """";
    example( str1, 4, str2);
    printf(""%s\n"", *str2);
}

int main() {
    testexample();
    return 0;
}
</code></pre>

<p>str1 is the original string, and n is the length of the string, and str2 is the all lower case version of str1.</p>

<p>I've been stuck trying to solve this problem for a while now. </p>

<p>I appreciate any help. Thank you.</p>
",https://stackoverflow.com/questions/42373676/unit-testing-for-a-function-tolower-using-pointers,"['c', 'unit-testing', 'pointers', 'tolower']",259,FALSE,-6,2
Angular 2 Services Unit Testing with DarkSkyApi call,"<p>I hope you can help. I search in the whole internet for answer to my questions. I new in programming with Angular 2 and all answers i find are to crypticle to me.</p>

<p>so thats my question. I will test a service in angular 2 with karma. And have the DarkskyApi in Use at the Service:</p>

<pre><code>//imports
import DarkSkyApi from 'dark-sky-api';  

@Injectable()
export class WetterService {

  /***
   * Konstruktor
   */
  constructor() {
    this.skyApi = this.InitDarkSky();
  }

  /**
   * Die Verbindung zur API Darksky initalialisiern
   */
  private InitDarkSky(): IDarkSkyApi {
    const darksky: IDarkSkyApi = new DarkSkyApi(this.ApiKey);

    // Ansteuern der Api
    return darksky
      .units('si')
      .language('de');
  }
}
</code></pre>

<p>and this is the test to the service:</p>

<pre><code>import { TestBed, inject } from '@angular/core/testing';

import { WetterService } from './wetter.service';
import {HttpClientModule} from '@angular/common/http';
import DarkSkyApi from 'dark-sky-api';

describe('WetterService', () =&gt; {
  let darkSkyApi: DarkSkyApi;

  beforeEach(() =&gt; {
    darkSkyApi = new DarkSkyApi();
    TestBed.configureTestingModule({
      providers: [
        WetterService
      ],
      imports: [HttpClientModule]
    });
  });

  it('should be created', inject([WetterService], (service: WetterService) =&gt; {
    expect(service).toBeTruthy();
  }));
});
</code></pre>

<p>When i run the test i become follow error:</p>

<p>TypeError: dark_sky_api_1.default is not a constructor</p>

<p>I hope so you can help. </p>

<p>Thanks,
Steffen</p>
",https://stackoverflow.com/questions/47556386/angular-2-services-unit-testing-with-darkskyapi-call,"['angular', 'unit-testing', 'typescript', 'karma-jasmine', 'angular2-services']",111,TRUE,0,1
Slick 3.0 Avoid Excessive Logging When Unit Testing,"<p>I have a project where I'm using Slick to model my relational data. I have written few unit tests which leverages H2 database. I have integrated a CI pipeline that runts the unit tests upon every commit to my master branch!</p>

<p>I'm using sbt as my build tool and what I see from the build logs is that it contains loads and loads of log lines with DEBUG messages. These messages are written by the underlying Slick library and I definitely want to get rid of them. I have tried several approaches, but none seems to take effect against those army of DEBUG log statements.</p>

<p>My project is a Play Framework based web project and here is what I have as my dependency in my build.sbt:</p>

<pre><code>libraryDependencies ++= Seq(
  ws,
  ""io.monix"" %% ""monix"" % ""2.1.0"",
  ""com.typesafe.slick"" %% ""slick"" % ""3.2.0"",
  ""com.typesafe.scala-logging"" %% ""scala-logging"" % ""3.4.0"",
  ""org.scala-lang.modules"" % ""scala-async_2.11"" % ""0.9.6"",
  ""com.zaxxer"" % ""HikariCP"" % ""2.4.1"",
  ""com.typesafe"" % ""config"" % ""1.3.1"",
  ""mysql"" % ""mysql-connector-java"" % ""5.1.26"",

  // test
  ""com.typesafe.akka"" %% ""akka-testkit"" % ""2.5.2"" % Test,
  ""org.scalatest"" %% ""scalatest"" % ""3.0.1"" % Test,
  ""com.h2database"" % ""h2"" % ""1.4.186"" % Test,
""org.scalatestplus.play"" %% ""scalatestplus-play"" % ""1.5.0"" % Test
)
</code></pre>

<p>I tried the following:</p>

<ol>
<li><p>Set the logLevel in build.sbt to INFO</p>

<p>logLevel := Level.Info</p></li>
</ol>

<p>Unfortunately that did not have any effect!</p>

<ol start=""2"">
<li><p>I used a logback.xml that looks like this:</p>

<p></p>

<pre><code>&lt;logger name=""scala.slick"" level=""INFO"" /&gt;
&lt;logger name=""play"" level=""INFO"" /&gt;
&lt;logger name=""application"" level=""INFO"" /&gt;
&lt;logger name=""akka"" level=""INFO"" /&gt;
</code></pre>

<p></p></li>
</ol>

<p>and used the following command when I run my unit tests:</p>

<pre><code>sbt -Dlogger.resource=conf/logback.xml clean coverage test coverageReport
</code></pre>

<p>But strangely, that did not have any effect at all as I still keep seeing those annoying DEBUG statements! I'm using Play Framework 2.5.9!</p>
",https://stackoverflow.com/questions/45672363/slick-3-0-avoid-excessive-logging-when-unit-testing,"['logging', 'sbt', 'slick']",283,TRUE,0,1
Unit testing Angular directive with templateUrl and triggerHandler,"<p>I try to write unit test for my example directive, but if I replace <code>template</code> on <code>templateUrl</code> then <code>element.triggerHangler</code> does not trigger directive events and I don't understand why.</p>

<p>My directive</p>

<pre><code>'use strict';

angular.module('app')
  .directive('chatEditor', function() {
    return {
      scope: {
        onAdd: '&amp;'
      },
      templateUrl: 'chat/chat-editor.directive.html',
      /*template: '&lt;div&gt;&lt;/div&gt;'*/
      link: function(scope, element, attrs) {
        element.on('click', function() {
          scope.onAdd({message: 'test'});
      });
    }
  }
});
</code></pre>

<p>Unit test</p>

<pre><code>'use strict';

describe('chatEditor', () =&gt; {
  beforeEach(module('app', 'templates'));

  it('should add player', inject(($compile, $rootScope) =&gt; {
    $rootScope.onAddSpy = jasmine.createSpy('onAddSpy');
    const element = $compile('&lt;chat-editor on-add=""onAddSpy(message)""&gt;&lt;/chat-editor&gt;')($rootScope);

    element.triggerHandler('click');

    $rootScope.$digest();

    expect($rootScope.onAddSpy).toHaveBeenCalledWith('test');
  }));
});
</code></pre>

<p>got error</p>

<blockquote>
  <p>Expected spy onAddSpy to have been called with [ 'test' ] but it was never called.</p>
</blockquote>

<p>but if I comment out <code>templateUrl</code> and uncomment <code>template</code> then test successful pass.</p>

<p>Also I installed and configured <code>karma-ng-html2js-preprocessor</code>. My cut from <code>karma.conf.js</code></p>

<pre><code>...

// list of files / patterns to load in the browser
files: [
  'app/**/*.module.js',
  'app/**/*.js',
  'app/**/*.html'
],

preprocessors: {
  'app/**/*.html': ['ng-html2js']
},

ngHtml2JsPreprocessor: {
  stripPrefix: 'app/',
  //prependPrefix: 'app/'
  moduleName: 'templates'
},
...
</code></pre>

<p>but it doesn't solve problem.</p>
",https://stackoverflow.com/questions/43345636/unit-testing-angular-directive-with-templateurl-and-triggerhandler,"['angularjs', 'unit-testing', 'karma-runner']",544,FALSE,0,1
How to Use Rhino Mock in unit testing,"<p>i am new to unittesting with rhino mocks and i am confused how to mock my dependency which are initialized in controller constructor using unity container.</p>

<p>as per the below code i have to unittest ""GetHelloWorld"" method with two dependency TestRepository and  RedisCacheManager   . </p>

<pre><code>public class TestController : BaseController
{
    private ITestRepository testRepo;
    private IRedisCacheManager cacheManager;

    public TestController()
    {
        testRepo = UnityResolver.Resolve&lt;ITestRepository&gt;();
        cacheManager = UnityResolver.Resolve&lt;IRedisCacheManager&gt;();
    }

    public ActionResult GetHelloWorld()
    {
        LoggerHelper.WriteInfo(""Inside GetHelloWorld Method.."");
        testRepo.PutDataInCustomAzureDB();
        cacheManager.Add(""Test"", ""TestData"", new TimeSpan(0, 1, 0));
        var getData = cacheManager.Get&lt;string&gt;(""Test"");
        cacheManager.Add(""Test"", ""TestData123"", new TimeSpan(0, 1, 0));
        var getDataa = cacheManager.Get&lt;string&gt;(""Test"");
        LoggerHelper.WriteInfo(""Leaving GetHelloWorld Method.."");
        return null;
    }
    }
    }
</code></pre>
",https://stackoverflow.com/questions/46357066/how-to-use-rhino-mock-in-unit-testing,['unit-testing'],57,TRUE,0,1
Unit testing a GORM call with a closure,"<p>I have a Grails service that does a <code>where</code> query like this:</p>

<pre><code>List&lt;Car&gt; search(Long makeId = null) {
    Car.where {
        join(""make"")
        if(makeId) {
            make.id == makeId
        }
    }.findAll()
}
</code></pre>

<p>I'm trying to unit test it with Spock like this:</p>

<pre><code>def setup() {
    GroovyMock(Car, global: true)
}

void ""test search""() {
    when:
        service.search()
    then:
        1 * Car.where {}
}
</code></pre>

<p>However, I can't seem to find a way to test the content of the closure.</p>

<p>I can get the test to pass by verifying <code>1 * Car.where(_)</code>, but how can I make assertions on the content of the closure, i.e. that <code>join</code> was called and that the <code>make.id</code> constraint is specified only when needed?</p>
",https://stackoverflow.com/questions/45802933/unit-testing-a-gorm-call-with-a-closure,"['unit-testing', 'grails', 'closures', 'spock']",403,TRUE,0,1
Unit Testing issue with Moq and Include (EF6),"<p>I have done fair bit research and tried all sorts of different ways of getting the Test to pass but now i need some help.</p>

<p>I am trying to test the following <strong>repository</strong> method:</p>

<pre><code>public class PortalsRepository : BaseRepository&lt;PortalDomainRole&gt;, IPortalsRepository
{
    public PortalsRepository(IAuthDbContext context) : base(context)
    {

    }

    public IEnumerable&lt;PortalRole&gt; GetRoles(string domainName)
    {
        return Set.Include(x =&gt; x.PortalDomain)
            .Include(x =&gt; x.PortalRole)
            .Where(x =&gt; x.PortalDomain.Name.ToLower() == domainName)
            .Select(x =&gt; x.PortalRole)
            .ToList();
    }
}
</code></pre>

<p>The <strong>Context</strong> looks like:</p>

<pre><code>public interface IAuthDbContext : IDbContextBase
{

}

public interface IDbContextBase
{
    IDbSet&lt;T&gt; Set&lt;T&gt;() where T : class;
    IEnumerable&lt;DbValidationError&gt; GetEntityValidationErrors();
    int SaveChanges();
    Task&lt;int&gt; SaveChangesAsync();
    Task&lt;int&gt; SaveChangesAsync(CancellationToken cancellationToken);
}
</code></pre>

<p>My Unit Test <strong>Set-up</strong> Looks like:</p>

<pre><code>    protected override void GivenThat()
    {
        var mockRolesSet = GetMockDbSet(PortalRoles().AsQueryable());
        mockRolesSet.Setup(x =&gt; x.Include(""PortalRole"")).Returns(mockRolesSet.Object);

        var mockDomainsSet = GetMockDbSet(PortalDomains().AsQueryable());
        mockDomainsSet.Setup(x =&gt; x.Include(""PortalDomain"")).Returns(mockDomainsSet.Object);

        var mockPortalDomanRolesSet = GetMockDbSet(PortalDomainRoles().AsQueryable());

        mockPortalDomanRolesSet.Setup(x =&gt; x.Include(""PortalRole"")).Returns(mockPortalDomanRolesSet.Object);
        mockPortalDomanRolesSet.Setup(x =&gt; x.Include(""PortalDomain"")).Returns(mockPortalDomanRolesSet.Object);

        var customDbContextMock = new Mock&lt;IAuthDbContext&gt;();
        customDbContextMock.Setup(x =&gt; x.Set&lt;PortalRole&gt;()).Returns(mockRolesSet.Object);
        customDbContextMock.Setup(x =&gt; x.Set&lt;PortalDomain&gt;()).Returns(mockDomainsSet.Object);
        customDbContextMock.Setup(x =&gt; x.Set&lt;PortalDomainRole&gt;()).Returns(mockPortalDomanRolesSet.Object);

        ClassUnderTest = new PortalsRepository(customDbContextMock.Object);
    }
</code></pre>

<p>My Unit Test <strong>Supporting</strong> Methods:</p>

<pre><code>public List&lt;PortalDomainRole&gt; PortalDomainRoles()
        {
            var data = new List&lt;PortalDomainRole&gt;
            {
                new PortalDomainRole { PortalRoleId = 2, PortalDomainId = 1},
                new PortalDomainRole { PortalRoleId = 1, PortalDomainId = 2},
                new PortalDomainRole { PortalRoleId = 2, PortalDomainId = 2}
            };
            return data;
        }

    public List&lt;PortalDomain&gt; PortalDomains()
    {
        var data = new List&lt;PortalDomain&gt;
        {
            new PortalDomain { Name = ""google.co.uk"", PortalDomainId = 1 },
            new PortalDomain { Name = ""bbc.com"", PortalDomainId = 2 }
        };
        return data;
    }

    public List&lt;PortalRole&gt; PortalRoles()
    {
        var data = new List&lt;PortalRole&gt;
        {
            new PortalRole {Name = ""New Products"", PortalRoleId = 1},
            new PortalRole {Name = ""Classic Products"", PortalRoleId = 2}
        };
        return data;
    }
</code></pre>

<p>When the unit test executes the method in question, i get:</p>

<p><strong><em>System.NullReferenceException : Object reference not set to an instance of an object.</em></strong></p>

<p>Most likely it does not know how to handle the nested include statements - i have followed many online questions and tutorials and now i am stuck.</p>
",https://stackoverflow.com/questions/44944765/unit-testing-issue-with-moq-and-include-ef6,"['c#', 'entity-framework', 'mocking', 'nunit', 'moq']",415,TRUE,0,1
unit testing and mocking then methods in promises,"<p>If one has a piece of logic to be unit tested with various sequential promises, how does one go about actually asserting on the logic within the <code>then(() =&gt; {})</code> functions? With a similar setup to below I run into issues where the first test will pass but the second test does not. I am curious as to <em>why</em> the anonymous then block in the implementation is never reached.</p>

<pre><code>//Implementation
class FiddleService {
    constructor(dependencies = {}) {
        const { someService = new SomeService() } = dependencies;
        this.someService = someService;
    }

    doSomething(params) {
        this.someService.asyncOperation1(params).then((result) =&gt; {
            ...
            //never gets called by spy in test
            return this.someService.asyncOperation2(result.firstName);
        }).then((result) =&gt; {
            return this.someService.asyncOperation3(result.age);
        });
    }
}
//test
describe(""FiddleService"", () =&gt; {
    let someService;
    beforeAll(() =&gt; {
        someService = new SomeService();
        spyOn(someService.asyncOperation1).and
          .returnValue(new Promise(() =&gt; {firstName: ""Jan""});
        spyOn(someService.asyncOperation2).and
          .returnValue(new Promise(() =&gt; {age: 50});
        spyOn(someService.asyncOperation3);
    });

    it(""calls asyncOperation1"", () =&gt; {
        let fiddleService = new FiddleService();
        fiddleService.doSomething({});
        expect(someService.asyncOperation1).toHaveBeenCalled();
    });

    it(""calls asyncOperation2"", () =&gt; {
        let fiddleService = new FiddleService();
        fiddleService.doSomething({});
        expect(someService.asyncOperation2).toHaveBeenCalled();
    });
});
</code></pre>
",https://stackoverflow.com/questions/46858362/unit-testing-and-mocking-then-methods-in-promises,"['node.js', 'unit-testing', 'promise', 'jasmine']",39,FALSE,0,2
How to fail laravel route for unit testing?,"<p>I have following code in my controller</p>

<pre><code>public function store(CreateSpecialityRequest $request) 
{
    DB::beginTransaction();
    try {
        $speciality = $this-&gt;specialityRepository-&gt;create($request-&gt;all());
        DB::commit();

        return redirect()-&gt;route('specialities.index')
            -&gt;with('success', 'Speciality Added successfully');
    } catch (\Exception $e) {
        DB::rollBack();
        return $e-&gt;getMessage();
        return redirect()-&gt;route('specialities.index')
            -&gt;with('error', 'Specialities details updating failed');
    }

}
</code></pre>

<p>My Testcase</p>

<pre><code>$speciality = [
            'name' =&gt; $faker-&gt;name,
            'description' =&gt; $faker-&gt;sentence,
            'icon' =&gt; $uploadedFile
        ];

        $this-&gt;post('/specialities', $speciality)
            -&gt;assertResponseStatus(302)
            -&gt;assertRedirectedToRoute('specialities.index')
            -&gt;assertSessionHas(['success' =&gt; 'Speciality Added successfully'])
            -&gt;followRedirects()
            -&gt;assertViewHas('specialities');
</code></pre>

<p>On my code coverage it shows that I have covered only try block
I want to cover catch block too. How can I fail my route in unit tests? to get into catch block</p>
",https://stackoverflow.com/questions/44177372/how-to-fail-laravel-route-for-unit-testing,"['php', 'unit-testing', 'phpunit', 'laravel-5.3']",466,FALSE,0,1
Create bulk of model objects unit testing django,"<p>For testing the pagination behavior of a search view, I have to create a bulk of dummy objects. Is there a more elegant way to create a bulk of objects?</p>

<pre><code>create_question('First question.', -1, [Choice(choice_text='First choice.')])
create_question('Second question.', -1, [Choice(choice_text='First choice.')])
# ...
</code></pre>
",https://stackoverflow.com/questions/42588095/create-bulk-of-model-objects-unit-testing-django,"['python', 'django', 'unit-testing', 'python-unittest']",475,TRUE,0,1
Unit-Testing Entity Framework 6 with SQLite Inmemory database,"<p>Actually I'm migrating unit-tests from a .NET Core project into a .NET Framework project. Before, I migrated a project using EF Core into a project using EF 6.</p>

<p>Now I want to use my DBContext for my unit-tests. I configured it in my .NET Core Unit-Test project like here: <a href=""https://github.com/doubleSlashde/ASPNETCoreExample/blob/master/Tests/RepositoryTests/TestBase.cs"" rel=""noreferrer"">https://github.com/doubleSlashde/ASPNETCoreExample/blob/master/Tests/RepositoryTests/TestBase.cs</a> . But this only works with EF Core.</p>

<p><strong>How do I have to configure the DBContext now in my Unit-Test project (.NET Framework 4.6)?</strong>
<strong>Prerequisite</strong> is that I can use <strong>Full-Text-Search</strong>. For SQLite I used one of the FTS-Extensions.</p>
",https://stackoverflow.com/questions/46681096/unit-testing-entity-framework-6-with-sqlite-inmemory-database,"['c#', 'entity-framework', 'sqlite', 'unit-testing', 'entity-framework-6']",704,FALSE,6,0
Android RecyclerView Adapter is giving null on unit testing,"<p>I am trying to test RecyclerView with AndroidJunit4, it is my test code:</p>

<pre><code>package com.kaushik.myredmart.ui;
// all includes
@RunWith(AndroidJUnit4.class)
public class ProductListActivityTest {

    @Rule
    public ActivityTestRule&lt;ProductListActivity&gt; rule  = new  ActivityTestRule&lt;&gt;(ProductListActivity.class);

    @Test
    public void ensureListViewIsPresent() throws Exception {
        ProductListActivity activity = rule.getActivity();
        View viewByIdw = activity.findViewById(R.id.productListView);
        assertThat(viewByIdw,notNullValue());
        assertThat(viewByIdw, instanceOf(RecyclerView.class));
        RecyclerView productRecyclerView = (RecyclerView) viewByIdw;
        RecyclerView.Adapter adapter = productRecyclerView.getAdapter();
        assertThat(adapter, instanceOf(ProductAdapter.class));

    }
}
</code></pre>

<p>I am facing a problem to check the Adapter. Although productRecyclerView  is passing not null test and an instance of RecyclerView, it is following error in last line:</p>

<pre><code>java.lang.AssertionError:
Expected: an instance of com.kaushik.myredmart.adapter.ProductAdapter
but: null
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
at org.junit.Assert.assertThat(Assert.java:956)
at org.junit.Assert.assertThat(Assert.java:923)
at com.kaushik.myredmart.ui.ProductListActivityTest.ensureListViewIsPresent(ProductListActivityTest.java:45)
</code></pre>

<p>What is the problem in code?</p>
",https://stackoverflow.com/questions/43730887/android-recyclerview-adapter-is-giving-null-on-unit-testing,"['java', 'android', 'android-recyclerview', 'android-junit']",1502,TRUE,6,1
"Symfony unit testing form, form using jquery datepicker","<p>I have a Roster entity in my Symfony project which contains two datetime fields. </p>

<p>Input field on FormType uses two single_text boxes, one for date one for time.</p>

<pre><code> $builder-&gt;add('serviceUserId', EntityType::class, array('class' =&gt; 'AppBundle:ServiceUser',
            'data' =&gt; $options['serviceUser']))
            -&gt;add('rosterStartTime', DateTimeType::class,
                array('date_widget' =&gt; ""single_text"",
                    'time_widget' =&gt; ""single_text"",
                ))
            -&gt;add('rosterEndTime', DateTimeType::class, array('date_widget' =&gt; ""single_text"",
                'time_widget' =&gt; ""single_text"",
            )
</code></pre>

<p>Can anyone tell me how to format the date I'm passing to this field in my Unit Test.</p>

<p>The nearest I've gotten is </p>

<pre><code>      $client = static::createClient(array(), array(
        'PHP_AUTH_USER' =&gt; 'username',
        'PHP_AUTH_PW' =&gt; 'password',
    ));

    $date = new \DateTime('2015-04-01 08:00');

    //browse to an exsting service user and add a roster to that record
    $crawler = $client-&gt;request('GET', '/serviceuser/2');
    $crawler = $client-&gt;click($crawler-&gt;selectLink('Add New Roster')-&gt;link());

    // Fill in the form and submit it
    $form = $crawler-&gt;selectButton('Create')-&gt;form(array(
        'appbundle_roster[serviceUserId]' =&gt; 2,
        'appbundle_roster[rosterStartTime]'  =&gt; $date-&gt;format('yyyy-MM-dd'),

        'appbundle_roster[rosterStatus ]' =&gt; 1,
        'appbundle_roster[numberResourcesNeeded]' =&gt; 2,
        'appbundle_roster[customerId]' =&gt; 2,
    ));
</code></pre>

<p>It's failing with this error</p>

<pre><code>     AppBundle\Tests\Controller\RosterControllerTest::testCompleteScenario
     InvalidArgumentException: Cannot set value on a compound field ""appbundle_roster[rosterStartTime]"".
</code></pre>
",https://stackoverflow.com/questions/43576545/symfony-unit-testing-form-form-using-jquery-datepicker,"['php', 'symfony', 'unit-testing', 'phpunit']",615,TRUE,0,1
Unit Testing of chain of promises with Jasmine,"<p>I want to write the unit test for the factory which have lot chain of promises. Below is my code snippet:</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>angular.module('myServices',[])
.factory( ""myService"",
    ['$q','someOtherService1', 'someOtherService2', 'someOtherService3',  'someOtherService4',
    function($q, someOtherService1, someOtherService2,  someOtherService3,  someOtherService4) {

method1{
	method2().then(
		function(){	someOtherService3.method3();},
		function(error){/*log error;*/}
	);
	return true;
};

var method2 = function(){
	var defer = $q.defer();
	var chainPromise = null;
	angular.forEach(myObject,function(value, key){
		if(chainPromise){
			chainPromise = chainPromise.then(
				function(){return method4(key, value.data);},
				function(error){/*log error*/});
		}else{
			chainPromise = method4(key, value.data);
		}
	});

	chainPromise.then(
		function(){defer.resolve();},
		function(error){defer.reject(error);}
	);
	return defer.promise;
};

function method4(arg1, arg2){
	var defer = $q.defer();
	someOtherService4.method5(
		function(data) {defer.resolve();},
		function(error) {defer.reject(error);},
		[arg1,arg2]
	);
	return defer.promise;
};

var method6 = function(){
	method1();
};
return{
method6:method6,
method4:method4
};
}]);</code></pre>
</div>
</div>
</p>

<p>To test it, I have created spy object for all the services, but mentioning the problematic one </p>

<pre><code>beforeEach( function() {
    someOtherService4Spy = jasmine.createSpyObj('someOtherService4', ['method4']); 
    someOtherService4Spy.method4.andCallFake(
        function(successCallback, errorCallback, data) {
           // var deferred = $q.defer();
            var error = function (errorCallback) { return error;}
            var success = function (successCallback) {
                deferred.resolve();
                return success;
            }
            return { success: success, error: error};
        }
    );

    module(function($provide) {
        $provide.value('someOtherService4', someOtherService4);
    });
    inject( function(_myService_, $injector, _$rootScope_,_$q_){
        myService = _myService_;
        $q = _$q_;
        $rootScope = _$rootScope_;
        deferred = _$q_.defer();
    });
</code></pre>

<p>});</p>

<pre><code>it(""test method6"", function() {
    myService.method6();
    var expected  = expected;
    $rootScope.$digest();

    expect(someOtherService3.method3.mostRecentCall.args[0]).toEqualXml(expected);
    expect(someOtherService4Spy.method4).toHaveBeenCalledWith(jasmine.any(Function), jasmine.any(Function), [arg,arg]);
    expect(someOtherService4Spy.method4).toHaveBeenCalledWith(jasmine.any(Function), jasmine.any(Function), [arg,arg]);
});
</code></pre>

<p>It is showing error on </p>

<p>expect(someOtherService3.method3.mostRecentCall.args[0]).toEqualXml(expected);</p>

<p>After debugging I found that it is not waiting for any promise to resolve, so method 1 return true, without even executing method3. I even tried with </p>

<pre><code>someOtherService4Spy.method4.andReturn(function(){return deferred.promise;});
</code></pre>

<p>But result remain same. 
My question is do I need to resolve multiple times ie for each promise. How can I wait till all the promises are executed.</p>
",https://stackoverflow.com/questions/47896879/unit-testing-of-chain-of-promises-with-jasmine,"['javascript', 'angularjs', 'unit-testing', 'karma-jasmine', 'angular-promise']",1946,FALSE,0,2
Unit testing presented view controller and keyboard in iOS,"<p>I'm trying to write unit tests to ensure that the keyboard and presented view controllers are triggered properly, but I'm getting the strange behaviour I don't understand that I believe is related to how <strong><code>UIWindow</code></strong> works. I'm using <a href=""https://github.com/Quick/Quick"" rel=""noreferrer"">Quick</a> and <a href=""https://github.com/Quick/Nimble"" rel=""noreferrer"">Nimble</a>, but I've tested with vanilla <code>XCTest</code> and get the same issues.</p>

<p>My Code:</p>

<pre><code>import Quick
import Nimble

class TestSpec: QuickSpec {
    override func spec() {

        let sut = UIViewController()

        // The window is nil when this test is run in isolation
        UIApplication.shared.keyWindow?.rootViewController = sut

        // This does not work either
        let window = UIWindow(frame: UIScreen.main.bounds)
        window.rootViewController = sut
        window.makeKeyAndVisible()

        describe(""ViewController"") {

            it(""presents a UIAlertController"") {
                let alert = UIAlertController(title: ""Test"", message: ""This is a test"", preferredStyle: .alert)
                let okAction = UIAlertAction(title: ""OK"", style: .default, handler: nil)
                alert.addAction(okAction)

                sut.present(alert, animated: true, completion: nil)
                expect(sut.presentedViewController).toEventually(beAnInstanceOf(UIAlertController.self))
            }
        }
    }
}
</code></pre>

<p>At first, I wasn't putting the view controller in a window, which prevented it from presenting other view controllers. Now I'm trying to put in in a window, but that isn't working either. When this test is run in isolation the window is always nil. When I run it with a bunch of other tests the window is not nil sometimes, but tests still fail. There was a brief period where the tests did pass, but I can't replicate it anymore for some reason. </p>

<p>Any ideas what's up?</p>
",https://stackoverflow.com/questions/42872347/unit-testing-presented-view-controller-and-keyboard-in-ios,"['ios', 'swift', 'unit-testing']",8641,TRUE,6,2
Unit Testing the App_Code of an ASP.Net Web Application,"<p>I want to create an ASP.Net Web Application, and I want to write unit tests for it. But my unit test project can't see any of the types in my web application's App_Code directory.</p>

<h2>Steps to reproduce</h2>

<p>(skip down past the images if you already know how to create a default webforms web application and add an app_code folder)</p>

<p>Open Visual Studio. Choose File->New->Project.<br>
Choose Templates -> Visual C# -> Web. Choose ASP.Net Web Application. Choose ""OK"".</p>

<p><a href=""https://i.stack.imgur.com/0AUbd.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/0AUbd.png"" alt=""enter image description here""></a></p>

<p>Choose ""Web Forms"". Check ""Add unit tests"". Click OK.</p>

<p><a href=""https://i.stack.imgur.com/ZoaDb.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ZoaDb.png"" alt=""enter image description here""></a></p>

<p>In the solution explorer, right-click on the web application and choose ""Add -> Add ASP.Net Folder -> App_Code"".</p>

<p><a href=""https://i.stack.imgur.com/gv8uE.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/gv8uE.png"" alt=""enter image description here""></a>
<a href=""https://i.stack.imgur.com/nKybV.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/nKybV.png"" alt=""enter image description here""></a></p>

<p>Add a new item to App_Code, named ""Util.cs"". Add a function to the file so the contents are:</p>

<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.App_Code
{
    public class Util
    {
        public static int getMeaningOfLife()
        {
            return 42;
        }
    }
}
</code></pre>

<p>In the Unit Testing project, change UnitTest1.cs to: </p>

<pre><code>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace WebApplication1.Tests
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            int result = WebApplication1.App_Code.Util.getMeaningOfLife();
            if (result != 42)
            {
                Assert.Fail();
            }
        }
    }
}
</code></pre>

<p>Then build the project.</p>

<h2>Expected behavior:</h2>

<p>The solution should build. If we attempt to test, the test should succeed.</p>

<h2>Actual behavior:</h2>

<p>The solution fails to build with <code>The type or namespace name 'App_Code' does not exist in the namespace 'WebApplication1' (are you missing an assembly reference?)</code></p>

<h2>Other notes</h2>

<p>I looked at <a href=""https://stackoverflow.com/q/1198555/953482"">Unit Testing ASP.net Web Site Project code stored in App_Code</a>, but I don't think the problem exactly matches my circumstances because they're testing a website and I'm testing a web application. Some answers specifically suggest switching to a web application, implying that it would no longer be a problem:</p>

<blockquote>
  <p>However, if you have the option of segregating the code into binaries (class libraries) or <strong>just using a web application</strong>, I'd suggest that as a better alternative.</p>
</blockquote>

<p>&nbsp;</p>

<blockquote>
  <p>I would either move this logic out to its own class library project or <strong>change the project type to Web Application</strong>, as Fredrik and Colin suggest.</p>
</blockquote>

<p>&nbsp;</p>

<blockquote>
  <p>And as the OP stated it's also possible to <strong>move to a Web App project</strong>, which i would say is cleaner as well</p>
</blockquote>

<p>The advice ""try using a web application"" doesn't apply to me, because I'm <em>already</em> using a web application, and it still doesn't work.</p>

<p>The answers also suggest ""Try moving the code out to its own project"", and I do expect that would work, but in my actual solution I have dozens of files in the App_Code directory. I would prefer not to perform any serious structural changes before I can establish a testing framework first.</p>
",https://stackoverflow.com/questions/42561058/unit-testing-the-app-code-of-an-asp-net-web-application,"['c#', 'asp.net', '.net', 'unit-testing']",1710,TRUE,5,1
Angular 2 Unit testing component with other component dependencies,"<p>Basically I have a component that look like this:</p>

<pre><code>export class CmpB extends CmpA {
    variableA:any = {};
    @Input() config:any = {};
    constructor(private serviceA: serviceA,
        @Optional() private CmpC?: CmpC) {
        super();
    }
    ngOnInit() {
        if (this.CmpC) {
            super.doSomething(parameterA);
            //other stuff
        }
    }
}
</code></pre>

<p>so basically I got CmpB that extends CmpA (which mutates variableA depending on the config)  and in order to do something it needs a specific parent component CmpC. ...And I need to write a test for it that actually verifies the CmpA mutations.</p>

<p>my test looks like this</p>

<pre><code>describe('CmpB', () =&gt; {
    let mock: any = MockComponent({ selector: ""app-element"", template: ""&lt;CmpC&gt;&lt;CmpB&gt;&lt;/CmpB&gt;&lt;/CmpC&gt;"" });
    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            declarations: [mock, CmpC, CmpB],
            providers: [
                ServiceA
            ]
        }).compileComponents();
    });

    it('CmpB component test', async(() =&gt; {
        const appMock = TestBed.createComponent(mock);
        appMock.detectChanges();
        const el = appMock.debugElement.nativeElement as HTMLElement;
        expect(el.tagName).toEqual(""DIV"");
    }));
}
</code></pre>

<p>which works and in terms of coverage it go through the whole thing.
But what I need is to manually set the config input and see how variableA mutates; I can't figure out how though.</p>

<p>mock component originates from the following code</p>

<pre><code>    import { Component } from '@angular/core';

export function MockComponent(options: Component): Component {
  let metadata: Component = {
    selector: options.selector,
    template: options.template || '',
    inputs: options.inputs,
    outputs: options.outputs
  };

  class Mock {}

  return Component(metadata)(Mock);
}
</code></pre>
",https://stackoverflow.com/questions/42560504/angular-2-unit-testing-component-with-other-component-dependencies,"['unit-testing', 'angular', 'angular2-testing']",1128,FALSE,5,0
Unit testing play controller actions that have json parsers,"<p>I have a controller action that I would like to test however I am getting the error below. I feel like there is something small that I could be missing but can't quite figure out what it is.I wrote out some small code to help illustrate the problem. </p>

<p>Abit of more context, I would like to be able to supply mock dependencies to the controller thats why I am manaully taking over its instantiation.</p>

<pre><code>java.lang.UnsupportedOperationException: NoMaterializer does not provide an ExecutionContext
[info]   at play.api.test.NoMaterializer$.executionContext(Helpers.scala:661)
[info]   at play.api.mvc.PlayBodyParsers.$anonfun$enforceMaxLength$1(BodyParsers.scala:866)
[info]   at akka.stream.impl.Compose.apply(TraversalBuilder.scala:164)
[info]   at akka.stream.impl.PhasedFusingActorMaterializer.materialize(PhasedFusingActorMaterializer.scala:488)
[info]   at akka.stream.impl.PhasedFusingActorMaterializer.materialize(PhasedFusingActorMaterializer.scala:424)
[info]   at akka.stream.impl.PhasedFusingActorMaterializer.materialize(PhasedFusingActorMaterializer.scala:415)
[info]   at akka.stream.scaladsl.RunnableGraph.run(Flow.scala:496)
</code></pre>

<p>Below is the controller I wrote to help illustrate the problem</p>

<pre><code>case class Location(lat: Double, long: Double)

object Location {

  implicit val locationReads: Reads[Location] = (
    (JsPath \ ""lat"").read[Double](min(-90.0) keepAnd max(90.0)) and
      (JsPath \ ""long"").read[Double](min(-180.0) keepAnd max(180.0))
    ) (Location.apply _)
}

class HomeController @Inject()(
    cc: ControllerComponents,
    mat: Materializer
)(implicit val ec: ExecutionContext) extends AbstractController(cc) {


  def savePlace: Action[JsValue] = Action(parse.json) { request: Request[JsValue] =&gt;
    val placeResult = request.body.validate[Location]
    placeResult.fold(
      errors =&gt; {
        BadRequest(Json.obj(""status"" -&gt; ""KO"", ""message"" -&gt; JsError.toJson(errors)))
      },
      place =&gt; {
        Ok(Json.obj(""status"" -&gt; ""OK"", ""message"" -&gt; ""Location saved""))
      }
    )
  }
}
</code></pre>

<p>and the test code    </p>

<pre><code>class HomeControllerSpec extends PlaySpec with Injecting with Inside with GuiceOneAppPerSuite with BeforeAndAfterEach with Results with BeforeAndAfterAll {
  implicit lazy override val app: play.api.Application = new GuiceApplicationBuilder().configure().build()
  implicit lazy val materializer: Materializer = app.materializer
  implicit lazy val components = Helpers.stubControllerComponents()

  ""savePlace"" must {

    val api = new HomeController(components, mat = materializer)

    val payload = Json.obj(
      ""location"" -&gt; Json.obj(""lat"" -&gt; 51.235685, ""lng"" -&gt; -1.309197)
    )

    ""just demo"" in {
      val request = FakeRequest(POST, ""/location"").withJsonBody(payload)

      val result = call(api.savePlace, request)
      status(result) mustBe UNAUTHORIZED
    }
  }
}
</code></pre>

<p>I am using play 2.6.3</p>
",https://stackoverflow.com/questions/46289476/unit-testing-play-controller-actions-that-have-json-parsers,"['json', 'scala', 'unit-testing', 'playframework']",1373,TRUE,5,3
Cannot read property &#39;contextTypes&#39; of undefined Unit Testing enzyme,"<p>I'm trying unit testing in my react using redux app. So I need to test connected components unfortunately i got this error: </p>

<blockquote>
  <p>Cannot read property 'contextTypes' of undefined
  I use enzyme in unit testing Here is my component:</p>
</blockquote>

<pre><code>    import React from 'react';
    import TextFieldGroup from '../common/TextFieldGroup';
    import validateInput from '../../server/validations/login';
    import { connect } from 'react-redux';
    import { login } from '../../actions/authActions';

    class LoginForm extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          username: '',
          password: '',
          errors: {},
          isLoading: false
        };

        this.onSubmit = this.onSubmit.bind(this);
        this.onChange = this.onChange.bind(this);
      }

      isValid() {
        const { errors, isValid } = validateInput(this.state);

        if (!isValid) {
          this.setState({ errors });
        }

        return isValid;
      }

      onSubmit(e) {
        e.preventDefault();
        if (this.isValid()) {
          this.setState({ errors: {}, isLoading: true });
          this.props.login(this.state).then(
            (res) =&gt; this.context.router.push('/'),
            (err) =&gt; this.setState({ errors: err.response.data.errors, isLoading: false })
          );
        }
      }

      onChange(e) {
        this.setState({ [e.target.name]: e.target.value });
      }

      render() {
        const { errors, username, password, isLoading } = this.state;

        return (
          &lt;form onSubmit={this.onSubmit}&gt;
            &lt;h1&gt;Login&lt;/h1&gt;

            { errors.form &amp;&amp; &lt;div className=""alert alert-danger""&gt;{errors.form}&lt;/div&gt; }

            &lt;TextFieldGroup
              field=""username""
              label=""Username""
              value={username}
              error={errors.username}
              onChange={this.onChange}
            /&gt;

            &lt;TextFieldGroup
              field=""password""
              label=""Password""
              value={password}
              error={errors.password}
              onChange={this.onChange}
              type=""password""
            /&gt;

            &lt;div className=""form-group""&gt;&lt;button className=""btn btn-primary"" disabled={isLoading}&gt;Login&lt;/button&gt;&lt;/div&gt;
          &lt;/form&gt;
        );
      }
    }

    LoginForm.propTypes = {
      login: React.PropTypes.func.isRequired
    }

    LoginForm.contextTypes = {
      router: React.PropTypes.object.isRequired
    }

    export default connect(null, { login })(LoginForm);
</code></pre>

<p>Here is my test: </p>

<pre><code>    import React from 'react';
    import { mount, shallow } from 'enzyme';
    import {expect} from 'chai';
    import sinon from 'sinon';
    import { connect } from 'react-redux'

    import { Login } from '../../js/react/components/login/LoginForm';

    describe('&lt;Login /&gt;', function () {
      it('should have an input for the username', function () {
        const wrapper = shallow(&lt;Login /&gt;);
        expect(wrapper.find('input[name=username]')).to.have.length(1);
      });

      it('should have an input for the password', function () {
        const wrapper = shallow(&lt;Login /&gt;);
        expect(wrapper.find('input[name=password]')).to.have.length(1);
      });

      it('should have a button', function () {
        const wrapper = shallow(&lt;Login /&gt;);
        expect(wrapper.find('button')).to.have.length(1);
      });

      it('simulates click events', () =&gt; {
        const onButtonClick = sinon.spy();
        const wrapper = shallow(
          &lt;Login onButtonClick={onButtonClick} /&gt;
        );
        wrapper.find('button').simulate('click');
        expect(onButtonClick).to.have.property('callCount', 1);
      });

    });
</code></pre>

<p>Suggestions and answers are highly appreciated :)</p>
",https://stackoverflow.com/questions/41951427/cannot-read-property-contexttypes-of-undefined-unit-testing-enzyme,"['unit-testing', 'reactjs', 'redux', 'react-redux', 'enzyme']",11269,TRUE,5,2
VSTO Unit Testing Office AddIn in C# .NET via RequestComAddInAutomationService,"<p>I have worked and read through various StackOverflow questions and other tutorials and documentation over the past weeks (N.B. some of them below) to try and find a way of unit testing a VSTO AddIn.</p>

<p>Unfortunately, it always results in an <code>E_NOINTERFACE</code> exception in my tests.</p>

<p>The code I am using is below - one extract of the ThisAddin partial class overriding the <code>RequestComAddinAutomationService</code>, another describing the test utility interface, the test itself, as well as an additional assembly extract proving that the AddIn assembly and its internals are visible to the test.</p>

<blockquote>
  <p><strong>My question is</strong>: why is this not working?  I am pretty sure that this follows the generally accepted practices of VSTO testing.</p>
</blockquote>

<p>If the below is not possible anymore, how should one go about testing VSTO?  Is .NET remoting/IPC the only solution?</p>

<h3>ThisAddin.cs</h3>

<pre><code>public partial class ThisAddin 
{
    #region Testing Utilities

    private AddinHelper _comAddinObject;

    protected override object RequestComAddInAutomationService()
    {
        // This is being called when I debug/run my project, but not when I run the tests
        return _comAddinObject ?? (_comAddinObject = new AddinHelper());
    }

    #endregion
}

#region Testing Utilities

[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface IAddinHelper
{
    Presentation GetPresentation();
    string GetString();
}

[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(IAddinHelper))]
public class AddinHelper : StandardOleMarshalObject, IAddinHelper
{
    public Presentation GetPresentation()
    {
        return Globals.ThisAddin... [...];
    }

    public string GetString()
    {
        return ""Hello World!"";
    }
}

#endregion
</code></pre>

<h3>AssemblyInfo.cs</h3>

<pre><code>[assembly: InternalsVisibleTo(""MyProject.Tests"")]
</code></pre>

<h3>MyUnitTest.cs (has a reference to <code>MyProject</code>)</h3>

<pre><code>[TestClass]
public class BasicTest
{
    [TestMethod]
    public void TestInstantiates()
    {
        var application = new Application();
        var doc = application.Presentations.Open(@""C:\Presentation.pptx"",
            MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);
        var comAddins = application.COMAddIns;
        var comAddin = comAddins.Item(""MyProject""); // Returns okay
        var comObject = (IAddinHelper) comAddin.Object; // Exception occurs

        Assert.AreEqual(true, true); // Never reached

        doc.Close();
    }
}
</code></pre>

<p>Furthermore, the project's settings are set to ""Register for COM interop"" and Visual Studio runs elevated without errors - running it as non-admin results in the DLLs not being registered; therefore, I also know that the COM objects <strong>are</strong> registered.</p>

<h3>Resulting Exception</h3>

<blockquote>
  <p>An exception of type 'System.InvalidCastException' occurred in MyProject.Tests.dll but was not handled in user code
  Additional information: Unable to cast COM object of type 'System.__ComObject' to interface type 'MyProject.IAddinHelper'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{59977378-CC79-3B27-9093-82CD7A05CF74}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).</p>
</blockquote>

<p>StackOverflow</p>

<ul>
<li><a href=""https://stackoverflow.com/questions/35553446/how-to-call-vsto-class-from-other-c-sharp-project"">How to call VSTO class from other c# project</a></li>
<li><a href=""https://stackoverflow.com/questions/30906070/unit-testing-vsto-projects"">Unit Testing VSTO projects</a></li>
<li><a href=""https://stackoverflow.com/questions/10875278/vsto-add-ins-comaddins-and-requestcomaddinautomationservice"">VSTO Add-ins, COMAddIns and RequestComAddInAutomationService</a> (<code>Register for COM Interop</code> doesn't change anything)</li>
<li><a href=""https://stackoverflow.com/questions/16938467/why-cannot-i-cast-my-com-object-to-the-interface-it-implements-in-c/16943296#16943296"">Why cannot I cast my COM object to the interface it implements in C#?</a> (the issue is likely not STAThread related)</li>
<li><a href=""https://sqa.stackexchange.com/questions/2545/how-do-i-unit-test-word-addin-written-in-c"">https://sqa.stackexchange.com/questions/2545/how-do-i-unit-test-word-addin-written-in-c</a></li>
</ul>

<p>Microsoft</p>

<ul>
<li><a href=""https://blogs.msdn.microsoft.com/varsha/2010/08/17/writing-automated-test-cases-for-vsto-application/"" rel=""noreferrer"">https://blogs.msdn.microsoft.com/varsha/2010/08/17/writing-automated-test-cases-for-vsto-application/</a>  &lt;-- Even with this supposedly working sample project, I am getting the exact same error.</li>
<li><a href=""https://msdn.microsoft.com/en-us/library/bb608621.aspx"" rel=""noreferrer"">https://msdn.microsoft.com/en-us/library/bb608621.aspx</a></li>
<li>General workflow background: <a href=""https://msdn.microsoft.com/en-us/library/bb386298.aspx"" rel=""noreferrer"">https://msdn.microsoft.com/en-us/library/bb386298.aspx</a></li>
</ul>

<p>I honestly don't know how one is supposed to test VSTO Add-Ins without this working. </p>
",https://stackoverflow.com/questions/45121396/vsto-unit-testing-office-addin-in-c-net-via-requestcomaddinautomationservice,"['c#', 'testing', 'com', 'vsto', 'office-interop']",2353,TRUE,11,1
Unit Testing with Catch C++ is interfering with my main(),"<p>I'm new to unit testing and decided to use the Catch framework for c++ because it seemed easy to integrate with its one header file. However, I have a multifile binary search tree program (files are: main.cpp, Tree.h, Tree.hxx, TreeUnitTests.cpp, catch.hpp). I can only get my unit tests to run if I comment out my int main() function in main.cpp. I understand that it is conflicting with '#define CATCH_CONFIG_MAIN' declaration in my TreeUnitTests.cpp, but I cannot get the unit tests to run if I do not include that declaration. How can I get both to run without having to comment my main() every time I want to run the unit tests?</p>

<p>This is the header file I am using:
<a href=""https://raw.githubusercontent.com/philsquared/Catch/master/single_include/catch.hpp"" rel=""noreferrer"">https://raw.githubusercontent.com/philsquared/Catch/master/single_include/catch.hpp</a></p>

<p>And the Catch tutorial I found it on and used as a guide:
<a href=""https://github.com/philsquared/Catch/blob/master/docs/tutorial.md"" rel=""noreferrer"">https://github.com/philsquared/Catch/blob/master/docs/tutorial.md</a></p>

<p>Some relevant files for reference:
<strong>main.cpp:</strong></p>

<pre><code>//******************* ASSN 01 QUESTION 02 **********************

#include ""Tree.h""
#include &lt;iostream&gt;

using namespace std;

/*
int main()
{

    //creating tree with ""5"" as root
    Tree&lt;int&gt; tree(5);
    tree.insert(2);
    tree.insert(88);
    tree.inorder();
    cout &lt;&lt; ""does tree contain 2?: "";
    cout &lt;&lt; tree.find(2) &lt;&lt; endl;
    cout &lt;&lt; ""does tree contain 3?: "";
    cout &lt;&lt; tree.find(3) &lt;&lt; endl;

    Tree&lt;int&gt; copytree(tree);
    cout &lt;&lt; ""copied original tree..."" &lt;&lt; endl;
    copytree.preorder();
    cout &lt;&lt; ""after deletion of 2:\n"";
    copytree.Delete(2);
    copytree.postorder();


    return 0;
}
*/
</code></pre>

<p><strong>TreeUnitTests.cpp:</strong></p>

<pre><code>#include &lt;iostream&gt;
#include ""Tree.h""
#define CATCH_CONFIG_MAIN
#include ""catch.hpp""

TEST_CASE(""Pass Tests"")
{
    REQUIRE(1 == 1);
}

TEST_CASE(""Fail test"")
{
    REQUIRE(1 == 0);
}
</code></pre>

<p>(my tests are not real tests, only to verify that the Catch framework was working correctly. I guess you can say it's a meta test)</p>
",https://stackoverflow.com/questions/45989932/unit-testing-with-catch-c-is-interfering-with-my-main,"['c++', 'unit-testing', 'catch-unit-test']",6497,TRUE,11,2
Mock Firebase Admin Auth for Unit Testing Authenticated Routes,"<p>I'm using firebase-admin for authentication on my express backend. I have a middleware that checks if requests are authenticated.</p>

<pre><code>public resolve(): (req, res, next) =&gt; void {
  return async (req, res, next) =&gt; {
    const header = req.header('Authorization');
    if (!header || !header.split(' ')) {
      throw new HttpException('Unauthorized', UNAUTHORIZED);
    }
    const token = header.split(' ')[1];
    await admin.auth().verifyIdToken(token).then((decodedToken: any) =&gt; {
      req.user = decodedToken;
      next();
    }).catch((error: any) =&gt; {
      throw new HttpException(error, UNAUTHORIZED);
    });
  };
}
</code></pre>

<p>So far, I can only unit test my routes to make sure that they respond <code>UNAUTHORIZED</code> instead of <code>NOT_FOUND</code>.</p>

<pre><code>it('GET /api/menu should return 401 ', done =&gt; {
  const NOT_FOUND = 404;
  const UNAUTHORIZED = 401;
  supertest(instance)
    .get('/api/menu')
    .end((error, response: superagent.Response) =&gt; {
      expect(response.status).not.toEqual(NOT_FOUND);
      expect(response.status).toEqual(UNAUTHORIZED);
      done();
    });
});
</code></pre>

<p>But, I want to write more unit tests than this! I want to mock users so I can make <code>AUTHORIZED</code> requests! I want to use the <code>type</code> property I have on users to verify that users of a certain <code>type</code> can/cannot use certain routes. Does anyone have an idea of how I could do this with firebase-admin-node?</p>

<p>It looks like the <a href=""https://github.com/firebase/firebase-admin-node"" rel=""nofollow noreferrer"">firebase-admin-node repo</a> generates tokens for unit tests <a href=""https://github.com/firebase/firebase-admin-node/blob/master/test/unit/auth/token-generator.spec.ts"" rel=""nofollow noreferrer"">here</a>, but I'm not sure how I would apply that to my specific problem.</p>
",https://stackoverflow.com/questions/46032009/mock-firebase-admin-auth-for-unit-testing-authenticated-routes,"['unit-testing', 'express', 'firebase', 'supertest', 'firebase-admin']",2547,FALSE,4,0
Setting up JSDOM navigator.serviceWorker for unit testing service workers,"<p>I'm looking for a way to set up navigator.serviceWorker to unit test my service worker. My current JSDOM setup looks like this:</p>

<pre><code>import { JSDOM } from 'jsdom';

const dom = new JSDOM('&lt;!DOCTYPE html&gt;&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt;&lt;/body&gt;&lt;/html&gt;');

global.window = dom.window;
global.document = dom.window.document;

Object.keys(global.window).forEach(property =&gt; {
  if (typeof global[property] === 'undefined') {
    global[property] = global.window[property];
  }
});

global.navigator = {
  userAgent: 'node.js'
};
</code></pre>

<p>I've already tried commenting out <code>global.navigator = ...</code> for <code>global.navigator = global.window.navigator</code>. However, the following <code>console.log(global.navigator.serviceWorker)</code> and <code>console.log(navigator.serviceWorker)</code> both return <code>undefined</code> in my unit test:</p>

<pre><code>describe('Service Worker', () =&gt; {
  it('should register a service worker and cache files on install', () =&gt; {
    console.log(navigator.serviceWorker); // undefined
    // navigator.serviceWorker.register() // not used yet since undefined
  });
});
</code></pre>
",https://stackoverflow.com/questions/44222121/setting-up-jsdom-navigator-serviceworker-for-unit-testing-service-workers,"['javascript', 'unit-testing', 'mocha.js', 'service-worker', 'jsdom']",2621,TRUE,4,1
&#39;Toolkit not initialized&#39; exception when unit-testing an JavaFX application,"<p>When I try to perform unit tests on components which contain JavaFX controls I get a <code>java.lang.IllegalStateException: Toolkit not initialized</code>.</p>

<p>How can components be unit tested which operate with JavaFX controls?</p>
",https://stackoverflow.com/questions/45109876/toolkit-not-initialized-exception-when-unit-testing-an-javafx-application,"['java', 'unit-testing', 'javafx-8']",5159,TRUE,10,3
ReactJS Unit Testing - TypeError: this.props.onChange is not a function,"<p>I am doing unit-testing on React Components with karma+jasmine involving Login. The tests always throws error </p>

<pre><code>? LoginForm test &gt; ValidatedInput test &gt; should validate password
</code></pre>

<blockquote>
  <p><strong>TypeError: this.props.onChange is not a function</strong></p>
</blockquote>

<pre><code> at ValidatedInput.handleChangeValue (src/components/ValidatedInput.js:14:24)
 at node_modules/enzyme/build/ShallowWrapper.js:844:23
 at ReactDefaultBatchingStrategyTransaction.perform (node_modules/react-test-renderer/lib/shallow/Transaction.js:143:20)
 at Object.batchedUpdates (node_modules/react-test-renderer/lib/shallow/ReactDefaultBatchingStrategy.js:62:26)
 at Object.batchedUpdates (node_modules/react-test-renderer/lib/shallow/ReactUpdates.js:97:27)
 at ReactShallowRenderer.unstable_batchedUpdates (node_modules/react-test-renderer/lib/shallow/ReactShallowRenderer.js:130:25)
 at performBatchedUpdates (node_modules/enzyme/build/ShallowWrapper.js:103:21)
 at node_modules/enzyme/build/ShallowWrapper.js:843:13
 at withSetStateAllowed (node_modules/enzyme/build/Utils.js:284:3)
 at ShallowWrapper.simulate (node_modules/enzyme/build/ShallowWrapper.js:840:42)
 at Object.&lt;anonymous&gt; (src/__tests__/login-test.js:93:37)
 at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)
 at process._tickCallback (internal/process/next_tick.js:109:7)
</code></pre>

<p>Following are my files:</p>

<blockquote>
  <p><strong>LoginForm.js</strong> renders the component</p>
</blockquote>

<pre><code>&lt;ValidatedInput
    name={'userId'}
    type={'text'}
    title={'User ID'}
    value={this.state.userId}
    placeholder={'Enter User ID'}
    onChange={this.handleUserIdChange}
    onComponentMounted={this.handleRegisterFormFields}
    validations={/^[0-9]{5,10}$/}
    validationError={'This is not valid user Id'}
    isRequired={true}
/&gt;
</code></pre>

<p>I have bind the <strong>handleUserIdChange</strong> in constructor and defined in the class body as</p>

<pre><code>handleUserIdChange(value) {
    this.setState({ userId : value });
}
</code></pre>

<blockquote>
  <p><strong>ValidatedInput.js</strong></p>
</blockquote>

<pre><code>import React, { Component } from 'react';

class ValidatedInput extends Component {
    constructor(props) {
        super(props);

        this.handleChangeValue = this.handleChangeValue.bind(this);
        this.isValid = this.isValid.bind(this);
        this.validateInput = this.validateInput.bind(this);
    }

    /**********************************************/
    // referred function //
    handleChangeValue(e) {
        this.props.onChange(e.target.value);
        var isValidField = this.isValid(e.target);
    }
    /**********************************************/    
    isValid(input) {
        if (input.getAttribute('required') !== null &amp;&amp; input.value === """") {
            input.classList.add('Error');
            input.nextSibling.textContent = this.props.validationError;
            return false;
        } else {
            input.classList.remove('Error');
            input.nextSibling.textContent =  '';
        }

        if(input.value !== """") {
            if(!this.validateInput(input.value)) {
                input.classList.add('Error');
                input.nextSibling.textContent = this.props.validationError;
                return false;
            } else {
                input.classList.remove('Error');
                input.nextSibling.textContent =  '';
            }
        }
            return true;
    }

    validateInput(value) {
        var regularExpressionToBeMatched = this.props.validations;
        return regularExpressionToBeMatched.test(value);
    }

    componentDidMount() {
        if (this.props.onComponentMounted) {
            this.props.onComponentMounted(this);
        }
    }

    render () {
        console.log(this.props.onChange);
        return (
            &lt;div className=""form-group""&gt;
                &lt;div className=""col-5 text-center""&gt;
                    &lt;label htmlFor={this.props.name}&gt;{this.props.title}&lt;/label&gt;
                &lt;/div&gt;
                &lt;div className=""col-5 text-center""&gt;
                    &lt;input
                        className=""form-input text-center""
                        type={this.props.type}
                        ref={this.props.name}
                        name={this.props.name}
                        value={this.props.value}
                        required={this.props.isRequired}
                        placeholder={this.props.placeholder}
                        onChange={this.handleChangeValue}
                    /&gt;
                    &lt;span className='Error'&gt;&lt;/span&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        );
    }
}

export default ValidatedInput;
</code></pre>

<p>The following is the code of the test:</p>

<pre><code>it('should validate userId', () =&gt; {
    const component = shallow( &lt;ValidatedInput
            name={'userId'}
            type={'text'}
            title={'User Id'}
            value={'001251623'}
            placeholder={'Enter User Id'}
            validations={/^[0-9]{5,10}$/}
            validationError={'This is not valid user Id'}
            isRequired={true}
    /&gt;);
    const handleChangeValue = spyOn(component.instance(), 'handleChangeValue');
    component.find('input').simulate('change', {target: { value: '00125' } });
    // expect(component.state().value).equals(""00125"");
    expect(handleChangeValue.calledWith('00125'));
});
</code></pre>

<p>I have looked extensively in all resources. The app is working fine and <strong>console.log(this.props.onChange)</strong> in ValidatedInput says <strong>bound handleUserIdChange</strong>. Please suggest a work-around or change.
Thanks.</p>

<p><strong><em>EDIT 1</em></strong></p>

<blockquote>
  <p>LoginForm.js</p>
</blockquote>

<pre><code>class LoginForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            userId : '',
            password : '',
            loginType : ['Customer', 'Payer', 'Super-User'],
            userLoggedInAs : ['Customer'],
            userType : '',
            FieldsRegister : [],
            serverMessage : '',
        }
        this.handleClearForm = this.handleClearForm.bind(this);
        this.handleSubmitForm = this.handleSubmitForm.bind(this);
        this.handleUserIdChange = this.handleUserIdChange.bind(this);
        this.handlePasswordChange = this.handlePasswordChange.bind(this);
        this.handleUserTypeChangeSelect = this.handleUserTypeChangeSelect.bind(this);
        this.handleRegisterFormFields = this.handleRegisterFormFields.bind(this);
    }

    handleUserIdChange(value) {
        this.setState({ userId : value });
    }
...
</code></pre>

<p><strong><em>EDIT 2</em></strong></p>

<pre><code>it('should validate userId', () =&gt; {
            const component = shallow( &lt;ValidatedInput
                    name={'userId'}
                    type={'text'}
                    title={'User Id'}
                    value={'001251623'}
                    placeholder={'Enter User Id'}
                    validations={/^[0-9]{5,10}$/}
                    validationError={'This is not valid user Id'}
                    isRequired={true}
                    onChange={handleUserIdChange()}
            /&gt;);
            const handleChangeValue = spyOn(component.instance(), 'handleChangeValue');
            component.find('input').simulate('change', {target: { value: '00125' } });
            // expect(component.state().value).equals(""00125"");
            expect(handleChangeValue.calledWith('00125'));
        });
</code></pre>
",https://stackoverflow.com/questions/45848337/reactjs-unit-testing-typeerror-this-props-onchange-is-not-a-function,"['javascript', 'reactjs', 'unit-testing']",16419,TRUE,3,1
Sinon Stub/Spy on local functions in unit testing,"<p>I use es6 modules and Karma/Mocha/Sinon/Chai for unit testing. If I have an es6 module called within another es6 module I am able to stub/spy on that second es6 module, as seen below:</p>

<p><strong>module-a.js</strong></p>

<pre><code>export function a() {
     // do something
}
</code></pre>

<p><strong>module-b.js</strong></p>

<pre><code>import * as moduleA from './module-a';

export function b() {
     // do something
     moduleA.a();
}
</code></pre>

<p>With the above code I can spy on moduleA.a() and determine when it was called and stub moduleA.a() and force specific return values.  </p>

<p>BUT, if I have this situation instead, I cannot spy or stub:</p>

<p><strong>module-a.js</strong></p>

<pre><code>export function a() {
     // do something
}

export function b() {
     // do something
     a();
}
</code></pre>

<p>If I try to spy/stub function a() in this example the spy/stub in Sinon is never called/  This is a pretty common situation so has anyone found a way to spy/stub the local functions?</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/46124087/sinon-stub-spy-on-local-functions-in-unit-testing,"['javascript', 'unit-testing', 'karma-runner', 'sinon']",2553,TRUE,3,1
Config class not found when unit testing laravel package,"<p>I'm working on a Laravel (5.4) package, and I'm trying to do unit testing. I have this class :</p>

<pre><code>&lt;?php

namespace Sample;

class Foo
{
    public function getConfig()
    {
        $config = \Config::get('test');

        return $config;
    }   
}
</code></pre>

<p>I have this test :</p>

<pre><code>&lt;?php

use PHPUnit\Framework\TestCase;
use Sample\Foo;

class FooTest extends TestCase
{
    public function testGetConfig()
    {
        $foo = new Foo;
        $config = $foo-&gt;getConfig();
    }
}
</code></pre>

<p>When I execute phpunit I have this error :</p>

<blockquote>
  <p>Error: Class 'Config' not found</p>
</blockquote>

<p>How can I unit test this class ?</p>

<p>Thank you.</p>
",https://stackoverflow.com/questions/42271029/config-class-not-found-when-unit-testing-laravel-package,"['php', 'unit-testing', 'laravel-5', 'phpunit', 'package']",3027,TRUE,3,3
Mock ngx-restangular for unit testing Angular 5 app,"<p>I saw <a href=""https://github.com/2muchcoffeecom/ngx-restangular/blob/master/demo/mock-data/mock-providers.ts"" rel=""nofollow noreferrer"">https://github.com/2muchcoffeecom/ngx-restangular/blob/master/demo/mock-data/mock-providers.ts</a> as an answer to a similar question asked previously but i could not understand how to use this. Can someone please explain this?</p>

<p>My issue-</p>

<p>I have a service method-</p>

<pre><code>restoreProject(project) {
        this.restangular.one('projects', project.id).get();
    }
</code></pre>

<p>How do i mock restangular for this?</p>

<p>Till now I have </p>

<pre><code>beforeEach(() =&gt; {

    this.injector = Injector.create([
        {provide: ConnectionBackend, useClass: MockBackend, deps: []},
        {provide: RequestOptions, useClass: BaseRequestOptions, deps: []},
        {provide: Restangular, useClass: Restangular, deps:[]},
        {provide: ProjectService, useClass: ProjectService, deps:[Restangular]}
    ]);

    this.service = this.injector.get(ProjectService);
    this.backend = this.injector.get(ConnectionBackend) as MockBackend;
    this.backend.connections.subscribe((connection: any) =&gt; this.connection = connection);

});

it('should query restore project', () =&gt; {

            this.service.restoreProject({id: 2});

            expect(this.connection.request.url).toMatch('projects/2');
        }));
</code></pre>

<p>But this gives the following error</p>

<pre><code>TypeError: Cannot read property 'createRequest' of undefined
    at Object.resource.(anonymous function) [as get] (http://0.0.0.0:9876/_karma_webpack_/webpack:/home/app/node_modules/ngx-restangular/dist/esm/src/ngx-restangular-config.factory.js:475:1)
    at Object.elemFunction (http://0.0.0.0:9876/_karma_webpack_/webpack:/home/app/node_modules/ngx-restangular/dist/esm/src/ngx-restangular.js:396:1)
    at wrapper (http://0.0.0.0:9876/_karma_webpack_/webpack:/home/app/node_modules/lodash/lodash.js:4968:1)
    at Object.getFunction (http://0.0.0.0:9876/_karma_webpack_/webpack:/home/app/node_modules/ngx-restangular/dist/esm/src/ngx-restangular.js:405:1)
    at Object.wrapper [as get] (http://0.0.0.0:9876/_karma_webpack_/webpack:/home/app/node_modules/lodash/lodash.js:4968:1)
    at CommunicatorProjectService.restoreProject (http://0.0.0.0:9876/_karma_webpack_/webpack:/home/app/src/app/budget-and-time-estimator/shared/communicator-project/communicator-project.service.ts:21:54)
    at Object.&lt;anonymous&gt; (http://0.0.0.0:9876/_karma_webpack_/webpack:/home/app/src/app/budget-and-time-estimator/shared/communicator-project/communicator-project.service.spec.ts:35:17)
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke (http://0.0.0.0:9876/_karma_webpack_/webpack:/home/app/node_modules/zone.js/dist/zone.js:392:1)
    at ProxyZoneSpec.webpackJsonp.../../../../zone.js/dist/proxy.js.ProxyZoneSpec.onInvoke (http://0.0.0.0:9876/_karma_webpack_/webpack:/home/app/node_modules/zone.js/dist/proxy.js:79:1)
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke (http://0.0.0.0:9876/_karma_webpack_/webpack:/home/app/node_modules/zone.js/dist/zone.js:391:1)
</code></pre>
",https://stackoverflow.com/questions/47979347/mock-ngx-restangular-for-unit-testing-angular-5-app,"['unit-testing', 'angular5']",267,FALSE,3,0
Which unit testing framework to use for JavaFX application?,"<p>I have finished writing an API for my application, and wanted to connect a GUI to it. I am programming in Java, so that's why I chose JavaFX as GUI framework. Because I like its design.</p>

<p>But when I started to write unit tests for JavaFX components, I was surprised that JUnit, Mockito, and PowerMockito doesn't work. e.g. I could not suppress constructor of the class that extends <code>MenuBar</code> or <code>BorderPane</code> etc.</p>

<p>When I googled, I found out that for writing unit tests for the code that uses JavaFX there are some other frameworks needed <em>(JemmyFX - seems not being updated for a long time, MarvinFX - very new, TestFX - has alpha version yet)</em> and I realized there are no good or well-documented frameworks there at all. Here I mean that I could not find any related book.</p>

<p><strong>Could anyone tell me which unit testing framework to use when writing the GUI in JavaFX?</strong></p>
",https://stackoverflow.com/questions/42832617/which-unit-testing-framework-to-use-for-javafx-application,"['java', 'unit-testing', 'user-interface', 'junit', 'javafx-8']",1275,TRUE,3,1
Karma Jasmine unit testing with Angular 4 is caching,"<p>I comment out code in a spec file and it is still failing my test.  </p>

<ol>
<li>why is it like this?</li>
<li>what can I do about this ,  edit karma config file with something????</li>
</ol>

<p>So here is a snippet of what I commented out</p>

<pre><code>it('Should find trackerId in the session tracker slider panel', () =&gt; {
    let sessionTrackerfixture = TestBed.createComponent(TrackerFormTemplateComponent);
    let sessionTrackerapp = sessionTrackerfixture.debugElement.componentInstance;
    sessionTrackerapp.model.session = '1234567890-1-1';
    sessionTrackerfixture.detectChanges();
    let compiled = sessionTrackerfixture.debugElement.nativeElement;
    expect(compiled.querySelector('.session').textContent).toContain('1234567890-1-1');
});
</code></pre>

<p>It still shows up </p>

<pre><code>TrackerFormTemplateComponent Should find trackerId in the session tracker slider panel
</code></pre>
",https://stackoverflow.com/questions/46415403/karma-jasmine-unit-testing-with-angular-4-is-caching,"['angular', 'unit-testing', 'karma-runner', 'karma-jasmine', 'karma-coverage']",521,FALSE,3,0
Error: No provider for DeepLinker while unit testing components,"<p>Testing suite is still not ready in <code>ionic 2</code>. So I am using this <a href=""http://lathonez.github.io/2017/ionic-2-unit-testing/"" rel=""nofollow noreferrer"">tutorial</a> for the test. This essentially uses <code>angular 2</code> testing suite . Here is my <code>test.ts</code></p>

<pre><code>declare var __karma__: any;
declare var require: any;

// Prevent Karma from running prematurely.
__karma__.loaded = function (): void { /* no op */};

// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting(),
);
// Then we find all the tests.
const context: any = require.context('./', true, /\.spec\.ts/);
// And load the modules.
context.keys().map(context);
// Finally, start Karma to run the tests.
__karma__.start();

export class TestUtils {

  public static beforeEachCompiler(components: Array&lt;any&gt;): Promise&lt;{fixture: any, instance: any}&gt; {
    return TestUtils.configureIonicTestingModule(components)
    .compileComponents().then(() =&gt; {
      let fixture: any = TestBed.createComponent(components[0]);
      return {
        fixture: fixture,
        instance: fixture.debugElement.componentInstance,
      };
    });
  }

  public static configureIonicTestingModule(components: Array&lt;any&gt;): typeof TestBed {
    return TestBed.configureTestingModule({
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      declarations: [
      ...components
      ],
      providers: [
      NavController,LoadingController,App, Form, Keyboard, DomController, MenuController,
      { provide: Bookemon, useClass: BookMock},
      { provide: Authentication, useClass: AuthMock},
      {provide: Storage, useClass: StorageMock},
      {provide: Config, useClass: ConfigMock},
      {provide: Platform, useClass: PlatformMock},
      {provide: Events, useClass: Eventsmock}
      ],
      imports: [
      FormsModule,
      IonicModule,
      ReactiveFormsModule,
      SwingModule
      ],
    });
  }
</code></pre>

<p>I am trying to test my <code>tab.ts</code> component. </p>

<p><code>tab.ts</code></p>

<pre><code>@Component({
  selector: 'page-tabs',
  templateUrl: 'tabs.html'
})
export class TabsPage {
  user: any;
  tab1Root: any = UserHuntsPage;
  tab2Root: any = HomePage;
  tab3Root: any = FeedPage;

  constructor(public navCtrl: NavController , public auth: Authentication ,public events: Events) {

  }
  ngOnInit(){
    this.events.subscribe('logout-user' , () =&gt; {
      this.navCtrl.setRoot(WelcomePage);
     })
  }
}
</code></pre>

<p>Here is <code>tab.pec.ts</code></p>

<pre><code>let fixture: ComponentFixture&lt;TabsPage&gt; = null;
let instance: any = null;
describe('Tabs component',()=&gt;{
  beforeEach(async(() =&gt; TestUtils.beforeEachCompiler([TabsPage]).then(compiled =&gt; {
    fixture = compiled.fixture;
    instance = compiled.instance;
  })));
  it('initialises', () =&gt; {
    expect(1).toBeTruthy();
  });
})
</code></pre>

<p>When i run the test I get this error,</p>

<pre><code>Error: No provider for DeepLinker!
    at NoProviderError.BaseError [as constructor] (webpack:///~/@angular/core/src/facade/errors.js:24:0 &lt;- src/test.ts:8542:34)
    at NoProviderError.AbstractProviderError [as constructor] (webpack:///~/@angular/core/src/di/reflective_errors.js:41:0 &lt;- src/test.ts:72995:16)
    at new NoProviderError (webpack:///~/@angular/core/src/di/reflective_errors.js:72:0 &lt;- src/test.ts:73026:16)
    at ReflectiveInjector_._throwOrNull (webpack:///~/@angular/core/src/di/reflective_injector.js:758:0 &lt;- src/test.ts:119137:19)
    at ReflectiveInjector_._getByKeyDefault (webpack:///~/@angular/core/src/di/reflective_injector.js:786:0 &lt;- src/test.ts:119165:25)
    at ReflectiveInjector_._getByKey (webpack:///~/@angular/core/src/di/reflective_injector.js:749:0 &lt;- src/test.ts:119128:25)
    at ReflectiveInjector_.get (webpack:///~/@angular/core/src/di/reflective_injector.js:558:0 &lt;- src/test.ts:118937:21)
    at TestBed.get (webpack:///~/@angular/core/bundles/core-testing.umd.js:814:0 &lt;- src/test.ts:39277:67)
    at CompiledTemplate.proxyViewClass.AppView.injectorGet (webpack:///~/@angular/core/src/linker/view.js:109:0 &lt;- src/test.ts:119679:45)
    at CompiledTemplate.proxyViewClass.DebugAppView.injectorGet (webpack:///~/@angular/core/src/linker/view.js:351:0 &lt;- src/test.ts:119921:49)
Error: Uncaught (in promise): Error: Error in ./TabsPage class TabsPage - inline template:0:0 caused by: No provider for DeepLinker!
    at resolvePromise (webpack:///~/zone.js/dist/zone.js:468:0 &lt;- src/test.ts:141307:31)
    at resolvePromise (webpack:///~/zone.js/dist/zone.js:453:0 &lt;- src/test.ts:141292:17)
    at webpack:///~/zone.js/dist/zone.js:502:0 &lt;- src/test.ts:141341:17
    at ZoneDelegate.invokeTask (webpack:///~/zone.js/dist/zone.js:265:0 &lt;- src/test.ts:141104:35)
    at ProxyZoneSpec.onInvokeTask (webpack:///~/zone.js/dist/proxy.js:103:0 &lt;- src/test.ts:110667:39)
    at ZoneDelegate.invokeTask (webpack:///~/zone.js/dist/zone.js:264:0 &lt;- src/test.ts:141103:40)
    at Zone.runTask (webpack:///~/zone.js/dist/zone.js:154:0 &lt;- src/test.ts:140993:47)
    at drainMicroTaskQueue (webpack:///~/zone.js/dist/zone.js:401:0 &lt;- src/test.ts:141240:35)
</code></pre>

<p>I have not used <code>DeepLinker</code> anywhere in my app. I am thinking it might be a dependency of something in my providers. I have spent a lot of time on this and I cant understand why this is happening. Any help would be appreciated.</p>

<p><strong>Edit</strong></p>

<p>I added <code>DeepLinker</code>in the <code>providers</code> but that gives another error,</p>

<pre><code>Failed: Can't resolve all parameters for DeepLinker: (?, ?, ?).
Error: Can't resolve all parameters for DeepLinker: (?, ?, ?).
    at CompileMetadataResolver._getDependenciesMetadata (webpack:///~/@angular/compiler/src/metadata_resolver.js:623:0 &lt;- src/test.ts:50686:19)
    at CompileMetadataResolver._getTypeMetadata (webpack:///~/@angular/compiler/src/metadata_resolver.js:517:0 &lt;- src/test.ts:50580:26)
    at webpack:///~/@angular/compiler/src/metadata_resolver.js:667:0 &lt;- src/test.ts:50730:41
    at Array.forEach (native)
    at CompileMetadataResolver._getProvidersMetadata (webpack:///~/@angular/compiler/src/metadata_resolver.js:647:0 &lt;- src/test.ts:50710:19)
    at CompileMetadataResolver._loadNgModuleMetadata (webpack:///~/@angular/compiler/src/metadata_resolver.js:430:0 &lt;- src/test.ts:50493:50)
    at CompileMetadataResolver.loadNgModuleMetadata (webpack:///~/@angular/compiler/src/metadata_resolver.js:313:0 &lt;- src/test.ts:50376:29)
    at RuntimeCompiler._loadModules (webpack:///~/@angular/compiler/src/runtime_compiler.js:99:0 &lt;- src/test.ts:69258:41)
    at RuntimeCompiler._compileModuleAndAllComponents (webpack:///~/@angular/compiler/src/runtime_compiler.js:83:0 &lt;- src/test.ts:69242:35)
    at RuntimeCompiler.compileModuleAndAllComponentsAsync (webpack:///~/@angular/compiler/src/runtime_compiler.js:65:0 &lt;- src/test.ts:69224:21)
</code></pre>

<p><strong>edit</strong></p>

<p>adding providers as <code>{ provide: DeepLinker, useValue: {} }</code> results in new error,</p>

<pre><code>TypeError: this.parent.registerChildNav is not a function
    at new Tabs (webpack:///~/ionic-angular/components/tabs/tabs.js:173:0 &lt;- src/test.ts:46470:25)
    at new Wrapper_Tabs (/IonicModule/Tabs/wrapper.ngfactory.js:7:18)
    at CompiledTemplate.proxyViewClass.View_TabsPage0.createInternal (/DynamicTestModule/TabsPage/component.ngfactory.js:27:20)
    at CompiledTemplate.proxyViewClass.AppView.create (webpack:///~/@angular/core/src/linker/view.js:74:0 &lt;- src/test.ts:119644:21)
    at CompiledTemplate.proxyViewClass.DebugAppView.create (webpack:///~/@angular/core/src/linker/view.js:330:0 &lt;- src/test.ts:119900:44)
    at CompiledTemplate.proxyViewClass.View_TabsPage_Host0.createInternal (/DynamicTestModule/TabsPage/host.ngfactory.js:16:19)
    at CompiledTemplate.proxyViewClass.AppView.createHostView (webpack:///~/@angular/core/src/linker/view.js:81:0 &lt;- src/test.ts:119651:21)
    at CompiledTemplate.proxyViewClass.DebugAppView.createHostView (webpack:///~/@angular/core/src/linker/view.js:341:0 &lt;- src/test.ts:119911:52)
    at ComponentFactory.create (webpack:///~/@angular/core/src/linker/component_factory.js:154:0 &lt;- src/test.ts:54276:25)
    at initComponent (webpack:///~/@angular/core/bundles/core-testing.umd.js:852:0 &lt;- src/test.ts:39321:53)
Error: Uncaught (in promise): Error: Error in ./TabsPage class TabsPage - inline template:0:0 caused by: this.parent.registerChildNav is not a function
    at resolvePromise (webpack:///~/zone.js/dist/zone.js:468:0 &lt;- src/test.ts:141416:31)
    at resolvePromise (webpack:///~/zone.js/dist/zone.js:453:0 &lt;- src/test.ts:141401:17)
    at webpack:///~/zone.js/dist/zone.js:502:0 &lt;- src/test.ts:141450:17
    at ZoneDelegate.invokeTask (webpack:///~/zone.js/dist/zone.js:265:0 &lt;- src/test.ts:141213:35)
    at ProxyZoneSpec.onInvokeTask (webpack:///~/zone.js/dist/proxy.js:103:0 &lt;- src/test.ts:110667:39)
    at ZoneDelegate.invokeTask (webpack:///~/zone.js/dist/zone.js:264:0 &lt;- src/test.ts:141212:40)
    at Zone.runTask (webpack:///~/zone.js/dist/zone.js:154:0 &lt;- src/test.ts:141102:47)
    at drainMicroTaskQueue (webpack:///~/zone.js/dist/zone.js:401:0 &lt;- src/test.ts:141349:35)
</code></pre>
",https://stackoverflow.com/questions/41773526/error-no-provider-for-deeplinker-while-unit-testing-components,"['angular', 'ionic2']",1577,TRUE,3,3
Visual studio 2017 Live Unit Testing does not work,"<p>Hello I'm getting a very strange exception (object reference not set to an instance of object) when using Visual studio 2017 Live Unit Testing if I run this test through Test Explorer->Run All all works fine and it’s also work in debugging but Live Unit Testing fall. <a href=""https://i.stack.imgur.com/G1lsh.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/G1lsh.png"" alt=""enter image description here""></a></p>

<p><a href=""https://www.amazon.com/clouddrive/share/eMIR6W6dUGcYOIVABIdIhlsZS0yWvF3LoXvI3OAk7rO?ref_=cd_ph_share_link_copy"" rel=""nofollow noreferrer"">Test Project</a></p>
",https://stackoverflow.com/questions/43591499/visual-studio-2017-live-unit-testing-does-not-work,"['visual-studio-2017', 'live-unit-tests']",527,FALSE,3,0
Unit testing a AWS Spring Boot Configuration file - possible?,"<p>We are currently using Spring Boot to connect to a mocked local instance of Amazon SQS. The application itself is working when run, but we would like to try and test the SQS Config class, if possible and if it makes sense.</p>

<p>Here is the configuration class. All properties are pulled from the typical <code>application.properties</code> file when the Spring application itself is run.</p>

<pre><code>import com.amazonaws.services.sqs.AmazonSQSAsync;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.aws.core.env.ResourceIdResolver;
import org.springframework.cloud.aws.messaging.core.QueueMessagingTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AWSSQSConfig {
    @Value(""${aws.sqs.endpoint}"")
    private String AWSSqsEndpoint;

    // Producer QueueMessageTemplate
    @Bean
    public QueueMessagingTemplate queueMessagingTemplate(AmazonSQSAsync amazonSqs, ResourceIdResolver resourceIdResolver) {
        if (!AWSSqsEndpoint.isEmpty())
            amazonSqs.setEndpoint(AWSSqsEndpoint);

        return new QueueMessagingTemplate(amazonSqs, resourceIdResolver);
    }
}
</code></pre>

<p>Here is the test class. We are attempting to pass the configuration in via TestPropertySource, but they don't actually seem to get to the <code>AWSSQSConfig</code> class. <code>AWSSqsEndpoint</code> inside the instance of the class is always NULL.</p>

<pre><code>import com.amazonaws.services.sqs.AmazonSQSAsync;
import com.lonewolf.formsbuilder.config.AWSSQSConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.aws.core.env.ResourceIdResolver;
import org.springframework.cloud.aws.messaging.core.QueueMessagingTemplate;
import org.springframework.test.context.TestPropertySource;

import static org.junit.Assert.assertNotNull;

@RunWith(MockitoJUnitRunner.class)
@SpringBootTest
@TestPropertySource(properties = {
        ""cloud.aws.region.static=us-east-1"",
        ""cloud.aws.credentials.accessKey=zzzzz"",
        ""cloud.aws.credentials.secretKey=zzzzzz"",

        ""aws.sqs.endpoint = http://localhost:9324"",
        ""aws.sqs.requestQueue = CreateSchemaRequest"",
        ""aws.sqs.responseQueue = CreateSchemaResponse""
})
public class AWSSQSConfigTests {
    @Mock
    private AmazonSQSAsync amazonSqs;

    @Mock
    private ResourceIdResolver resourceIdResolver;

    @Test
    public void contextLoads() {
        AWSSQSConfig config = new AWSSQSConfig();

        QueueMessagingTemplate queueMessagingTemplate = config.queueMessagingTemplate(amazonSqs, resourceIdResolver);

        assertNotNull(""The response body must not be null"", queueMessagingTemplate);
    }
}
</code></pre>

<p>Is this a chicken and the egg situation, where the spring framework actually needs to run first to inject those config values? Do we need an integration test here instead?</p>

<p><strong>EDIT with working solution...</strong></p>

<p>Using the accepted answer, here is my working test! I was able to remove my dependency of the Spring framework.</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)
public class AWSSQSConfigTests {
    @Mock
    private AmazonSQSAsync amazonSqs;

    @Mock
    private ResourceIdResolver resourceIdResolver;

    @InjectMocks
    private AWSSQSConfig config;

    @Before
    public void setup() {
        ReflectionTestUtils.setField(config, ""AWSSqsEndpoint"", ""http://fake"");
    }

    @Test
    public void contextLoads() {
        QueueMessagingTemplate queueMessagingTemplate = config.queueMessagingTemplate(amazonSqs, resourceIdResolver);

        assertNotNull(""The response body must not be null"", queueMessagingTemplate);
    }
}
</code></pre>
",https://stackoverflow.com/questions/42260849/unit-testing-a-aws-spring-boot-configuration-file-possible,"['java', 'spring', 'amazon-web-services', 'spring-boot']",5251,TRUE,3,1
Angular Unit testing : can&#39;t change the reporter of karma,"<p>I am trying to use the JUnit reporter with karma. </p>

<p>When I launch </p>

<pre><code>$ ng test --watch=false --code-coverage
</code></pre>

<p>It always outputs me </p>

<pre><code>10% building modules 1/1 modules 0 active01 06 2017 11:57:51.797:ERROR 
[reporter]: Can not load reporter ""coverage-istanbul"", it is not registered!
</code></pre>

<p>The problem is, in my <code>karma.conf.json</code> I have no reference to istanbul : </p>

<pre><code>module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular/cli'],
    plugins: [
      require('karma-jasmine'),
      // require('karma-chrome-launcher'),
      require('karma-phantomjs-launcher'),
      require('karma-junit-reporter'),
      require('karma-mocha-reporter'),
      require('@angular/cli/plugins/karma')
    ],
    files: [
      { pattern: './src/test.ts', watched: false }
    ],
    preprocessors: {
      './src/test.ts': ['@angular/cli']
    },
    mime: {
      'text/x-typescript': ['ts', 'tsx']
    },
    junitReporter: {
      outputDir: 'coverage', // results will be saved as $outputDir/$browserName.xml
      useBrowserName: false, // add browser name to report and classes names
      outputFile: 'test-report.xml', // if included, results will be saved as $outputDir/$browserName/$outputFile
    },
    angularCli: {
      config: './angular-cli.json',
      environment: 'dev'
    },
    reporters: config.angularCli &amp;&amp; config.angularCli.codeCoverage ?
      ['mocha', 'junit'] :
      ['mocha'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: [
      'PhantomJS',
      // 'Chrome'
    ],
    singleRun: false
  });
};
</code></pre>

<p>Do you have any idea where it might come from ? </p>

<p>I also deleted all packages refering to istanbul in my <code>package.json</code> file, I also used <code>npm prune</code> just to be sure. </p>
",https://stackoverflow.com/questions/44304530/angular-unit-testing-cant-change-the-reporter-of-karma,"['angular', 'unit-testing', 'karma-jasmine', 'karma-coverage']",3879,TRUE,3,2
Unit testing with Moq method invoked inside of Task.Run,"<p>I am trying to mock a service call inside of a method that I want to test.</p>

<p>The method body looks like this:</p>

<pre><code>public string OnActionException(HttpActionContext httpRequest, Exception ex)
{
    var formattedActionException = ActionLevelExceptionManager.GetActionExceptionMessage(httpRequest);

    var mainErrorMessage = $""[{formattedActionException.ErrorId}]{formattedActionException.ErrorMessage}, {ex.Message}"";

    this.LogError(mainErrorMessage, ex);

    if (this._configuration.MailSupportOnException)
        Task.Run(async () =&gt; await this._mailService.SendEmailForThrownException(this._configuration.SupportEmail, $""{mainErrorMessage} ---&gt; Stack trace: {ex.StackTrace.ToString()}"")); 

    return $""(ErrID:{formattedActionException.ErrorId}) {formattedActionException.ErrorMessage} {formattedActionException.KindMessage}"";
}
</code></pre>

<p>What I am trying to mock inside my test is:</p>

<p><strong>Task.Run(async () => await this._mailService.SendEmailForThrownException(this._configuration.SupportEmail, $""{mainErrorMessage} ---> Stack trace: {ex.StackTrace.ToString()}""));</strong> </p>

<p>The test method looks like this:</p>

<pre><code>[TestMethod]
public void We_Send_System_Exception_On_Email_If_Configured_In_Settings()
{
    // arrange
    this._configurationWrapperMock.Setup(cwm =&gt; cwm.MailSupportOnException)
        .Returns(true);
    this._mailServiceMock.Setup(msm =&gt; msm.SendEmailForThrownException(It.IsAny&lt;string&gt;(), It.IsAny&lt;string&gt;()))
        .Returns(Task.FromResult(0));

    // act
    var logger = new ApiLogger(this._configurationWrapperMock.Object, this._mailServiceMock.Object);
    logger.OnActionException(
        new HttpActionContext(
            new HttpControllerContext()
            {
                Request = new HttpRequestMessage()
                {
                    Method = HttpMethod.Get,
                    RequestUri = new System.Uri(""https://www.google.bg/"")
                }
            }, 
            new ReflectedHttpActionDescriptor() { }
        ), 
        new System.Exception());

    // assert
    this._mailServiceMock.Verify(
        msm =&gt; msm.SendEmailForThrownException(It.IsAny&lt;string&gt;(), It.IsAny&lt;string&gt;()), 
        Times.Once);
}
</code></pre>

<p>The problem is that the method is never invoked, so my assert fails.</p>

<p>EDIT: I could change my question to: How do I need to re-write my method in order to make it testable?</p>
",https://stackoverflow.com/questions/47561264/unit-testing-with-moq-method-invoked-inside-of-task-run,"['c#', 'unit-testing', 'mocking', 'moq', 'assert']",8128,TRUE,3,3
Spring Boot Unit testing for Mock beans vs Mockito,"<p>I am using a spring boot 1.5.4 project where I need a clarification on testing package. </p>

<p>I am seeing Spring Boot comes with <code>@MockBean</code> which is part of <code>org.springframework.boot.test.mock.mockito</code> package. </p>

<p>My question is - Is it similar to Mockito external dependency and I can avoid using Mockito as external dependency as spring boot mock.* package has all features which Mockito has?</p>
",https://stackoverflow.com/questions/44856720/spring-boot-unit-testing-for-mock-beans-vs-mockito,"['java', 'spring', 'unit-testing', 'spring-boot']",3067,TRUE,2,2
Is testing a backend api endpoint considered unit testing?,"<p>For example, if you have a Node server using Express and you write a Jasmine test to make sure POST /someroute gives you the JSON you expect, is that still considered unit testing? I know it doesn't seem to fit the strict definition of the smallest testable part of an application. So if not, is there a certain term for this type of testing of routes?</p>
",https://stackoverflow.com/questions/45533178/is-testing-a-backend-api-endpoint-considered-unit-testing,"['unit-testing', 'express', 'testing', 'tdd', 'bdd']",2877,TRUE,2,2
Unit testing: How are 4 branches being added? &#128533;,"<p>I have a file with the entire contents of:</p>

<pre><code>import Component from '../../';
</code></pre>

<p>How can that possibly introduce 4 branches?</p>
",https://stackoverflow.com/questions/44031275/unit-testing-how-are-4-branches-being-added,"['javascript', 'unit-testing', 'webpack', 'istanbul']",43,FALSE,2,0
Unit Testing with Jersey Rest Test Framework and Mockito,"<p>Could someone help me on this.
I am writing Unit test for Rest resource using Jersey rest test framework version 2.21.(On Grizzly container).</p>

<p>When I debug the test class, am seeing mock object for myManager . But when the debug enters my ""MyResouce class, myManager object is becoming null and getting NullPointer Exception.</p>

<p>Have tried with solutions given by different people, but no luck.Could someone help me please. Am with this problem from almost three days. :(</p>

<p>My Resource class is like this.</p>

<pre><code>@Component
@Path(""/somepath"")
public class MyResource {
    @Autowired
    private MyManager myManager;

    @Path(""/somepath"")
    @GET
    @Produces(""application/json"")
    @ResponseType(String.class)
    public Response getResults(@QueryParam(""queryParam"") String number) {
        // myManager is an interface
        String str = myManager.getResult(number);
    }
}
</code></pre>

<p>And here is my testclass</p>

<pre><code>public class MyResourceTest extends JerseyTest {
    @Mock
    private MyManager myManager;

    @InjectMocks
    private MyResource myResource;

    @Override
    protected Application configure() {
        MockitoAnnotations.initMocks(this);
        return new ResourceConfig().register(MyResource.class)
                .register(new AbstractBinder() {
                    @Override
                    protected void configure() {
                        bind(myManager).to(MyManager.class);
                    }
                });
    }

    @Test
    public void getResultsTest() {
        when(myManager.getResult(anyString())).thenReturn(mock(String.class));
        String str = target(""path"").queryParam(""queryParam"",""10"").request().get(String.class);
    }
}
</code></pre>
",https://stackoverflow.com/questions/42062506/unit-testing-with-jersey-rest-test-framework-and-mockito,"['java', 'rest', 'unit-testing', 'jersey', 'jersey-test-framework']",4300,TRUE,2,1
Python unit testing for methods working on complex objects,"<p>I have inherited a relatively large (~30.000 lines) Python-based project (running on a CAD system for architects) with some messy methods that I have to bugfix at first and go on with the development. These methods place, say, bricks (or stuff like that), into a wall. So most of the code does 3D calculations on coords, vectors, etc.</p>

<p>There are no unit tests for the project currently (and I'm a complete noob for unit testing, I'm a brick-and-mortar architect).  Because of the complexity of the functions I have decided to support my work with unit testing, the question is that how can I do it most effectively. Examples I have seen before are much website-based, working mostly on text docs.</p>

<p>The incoming parameters are very complex and large objects, and I use only few of the stored data. Obviously I have to make templates out of it.</p>

<p>There are two possible ways:</p>

<ol>
<li>To save a real word data as a Python pickle and later use this as a template, and save it to disk.</li>
<li>To set up objects dynamically. Note that used objects' <code>__init__()</code> methods are mostly like this:</li>
</ol>

<p><br/></p>

<pre><code>class FirstClass:
    def __init__(): 
      self.x = 0
      self.y = 0
      self.fc = self.FirstClass()

class SecondClass:
    def __init__():
        self.blabla = 0
</code></pre>

<p>and so on, there are no complicated calculations. Obviously I can put my custom data by overwriting the initialized instance variables like this:</p>

<pre><code>objects.in_the_test_used_data = some_numbers
</code></pre>

<p>My question is which is the better method for templates, or whether there is a better approach for this et.</p>

<p>Thx</p>
",https://stackoverflow.com/questions/45635512/python-unit-testing-for-methods-working-on-complex-objects,"['python', 'unit-testing']",1405,TRUE,2,1
Unit testing angular 2 Services does not run callback after injection,"<p>So I've created unit tests for my components but want some for my individual services in isolation. However when i try to inject them(the service method being tested is not async).</p>

<pre><code>describe('SearchService', () =&gt; {
    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            providers: [
                SearchService
            ]
        });

    });


    it(""should build Url String"", () =&gt; {
        inject([SearchService], (searchService: SearchService) =&gt; {
            spyOn(searchService, 'buildURL');
            console.log(""should be logging like a boss"");
            searchService.buildURL(""test"", ""coursename"", 2);
            expect(searchService.buildURL).toHaveBeenCalled();
            expect(searchService.buildURL(""test"", ""coursename"", 2)).toBe(['1']);
            expect(searchService.buildURL(""test"", ""coursename"", 2)).toBeFalsy();
        });
    });

});
</code></pre>

<p>Inject never actually runs callback! test recognizes it statement but passes without error.</p>

<p>the console.log statement inside never runs and tests designed to fail pass, so I assume inject is failing to run. </p>
",https://stackoverflow.com/questions/46553398/unit-testing-angular-2-services-does-not-run-callback-after-injection,"['angular', 'unit-testing', 'karma-jasmine']",1433,TRUE,14,2
How to actually do unit testing in RxJS 5?,"<p>I am trying to do unit testing in RxJS 5 and I am completely unable to do so from what is explained in the documentation. I also tried to fallback on RxJS 4 which didn't work either since the <code>defer</code> operator doesn't take a scheduler.</p>

<p>How would I go about testing the following case:</p>

<pre><code>// a.js

module.exports = Rx.Observable.defer(() =&gt; Promise.resolve('test'))

// b.js

const a = require('a')

module.exports = a().repeatWhen(notifications =&gt; notifications.delay(5000))
</code></pre>

<p>I am trying to test both files.</p>

<p>Note: the real implementation of <code>a</code> doesn't always return the same value</p>
",https://stackoverflow.com/questions/45079535/how-to-actually-do-unit-testing-in-rxjs-5,"['unit-testing', 'rxjs', 'rxjs5']",424,FALSE,2,0
patching boto3.resource and resource.Table method for unit testing,"<p>Here is my class:</p>

<pre><code># Production.py
import boto3


class Production(object):
    resource = boto3.resource('dynamodb', 'us-west-2')

    def __init__(self):
        self.table = Production.resource.Table('employee')
</code></pre>

<p>I am trying to test that resource.Table is called with arg 'employee'. I wrote a unit test for it</p>

<pre><code>def test_init():
   with patch('Production.boto3.resource') as resource:
       mock_resource = MagicMock()
       resource.return_value = mock_resource
       pd = Production()
       resource.assert_called_with('dynamodb', 'us-west-2')
       table = resource.return_value.Table.return_value

       table.assert_called_with('employee')


test_init()
</code></pre>

<p>But it doesn't seem to work... Can some one help me how to test this?</p>
",https://stackoverflow.com/questions/46227469/patching-boto3-resource-and-resource-table-method-for-unit-testing,"['python-3.x', 'unit-testing']",3271,TRUE,2,1
Unit testing: allow for false-positive or bring duplication,"<p>I am testing a class that (apart from interacting with others) creates an object with fields made up of constants and values passed from caller:  </p>

<pre><code>private String createService(Long organizationId, String prototypeId,
    MedicalService medicalService)
{
    ServiceType service = new ServiceType();

    service.setClinic(organizationId.toString());
    service.setType(""0"");
    service.setPrototype(prototypeId);
    service.setCode(medicalService.getCode());
    service.setName(medicalService.getName());
    service.setIndependent(true);
    service.setRepeated(false);

    return remoteWS.createService(service);
}
</code></pre>

<p>Should I test that every field is set appropriately? </p>

<p>The reason I'm making doubt is that it would introduce duplication and decrease readability. Particularly I'm inclined to do reflection assert. </p>

<p>That would only allow to detect some ""stupid"" typing errors, e.g. writing <code>code</code> to <code>name</code> field if both are of type <code>String</code>.</p>

<p>Is this duplication reasonable?</p>
",https://stackoverflow.com/questions/45005279/unit-testing-allow-for-false-positive-or-bring-duplication,"['unit-testing', 'testing', 'tdd']",130,TRUE,2,1
Unit testing protocol extensions through structs in Swift 3,"<p>Here's the protocol oriented code i have for which i am stuck with for writing unit tests. </p>

<pre><code>protocol TestProtocol {
    func testOne()
    func testTwo()
}

extension TestProtocol {
    var testHelper: TestHelper {
        return TestHelper()
    }
    fileprivate func _one() {
        testHelper.one()
    }
    func one() {
        _one()
    }
    fileprivate func _two() {
        testHelper.two()
    }
    func two() {
        _two()
    }
}

struct TestHelper {
    var userDefaults: UserDefaults {
        return UserDefaults.standard
    }
    func one() {
        userDefaults.set(""12223334444"", forKey: ""PhoneNumberWithCountryCode"")
    }
    func two() {
        userDefaults.set(""Mark"", forKey: ""UserName"")
    }
}

class TestAboveCode { }

extension TestAboveCode: TestProtocol {
    func testOne() {
        _one()
    }
    func testTwo() {
        _two()
    }
}

class UseAboveCode {
    func use() {
        TestAboveCode().testOne()
    }
}
</code></pre>

<p>here's the problem, 
To write unit test for UseAboveCode class, i need to mock the TestHelper struct. Though i can create a mock struct and override the existing functions, i cannot set the testHelper property in the TestProtocol extension. Is there a work around for this? </p>

<p>I do know the other approach which is making the TestHelper struct implement a protocol and ultimately injecting that as a property or through a constructor. This code above looks ideal for readability and usability but someone i am not able to wrap my head around unit test. </p>

<p>Am i over thinking with this approach? Please let me know what the best approach is. </p>
",https://stackoverflow.com/questions/42241154/unit-testing-protocol-extensions-through-structs-in-swift-3,"['swift', 'unit-testing', 'dependency-injection', 'swift3', 'swift-protocols']",488,FALSE,2,0
CRUD Edit operation using a ViewModel with unit testing,"<p>First of all: I found <a href=""https://stackoverflow.com/questions/32400094/how-to-edit-using-a-viewmodel-in-mvc"">this post</a>, but I don't fully understand it, so please don't lock it as a duplicate.</p>

<p>I'm trying to do the Edit operation with a ViewModel.</p>

<p>My problem is for some reason <code>adds</code> a new row to the table instead of <code>editing</code> it. It all used to work before I went for the testing.</p>

<p>I believe it's something silly I missed but I have no idea what I'm doing wrong.</p>

<p>I'm using <code>code-first</code> if it makes any difference</p>

<p>My ViewModel:</p>

<pre><code>public class CreateViewModel
{
    public string Title { get; set; }

    [Display(Name = ""Author"")]
    public int AuthorId { get; set; }
    public DateTime? PublicationDate { get; set; }
    public float? Edition { get; set; }
    public SelectList Authors { get; set; }
}
</code></pre>

<p>My Controller functions:</p>

<pre><code>    // GET: Books/Edit/5
    public ViewResult Edit(int? id)
    {
        if (id == null)
        {
            return View(""Error"");
        }
        Book book = db.Books.FirstOrDefault(a =&gt; a.Id == id);

        var vm = new CreateViewModel()
        {
            AuthorId = book.AuthorId,
            Authors = new SelectList(db.Authors, ""Id"", ""Name""),
            PublicationDate = book.PublicationDate,
            Title = book.Title,
            Edition = book.Edition
        };

        if (book == null)
        {
            return View(""Error"");
        }
        return View(vm);
    }

    // POST: Books/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(CreateViewModel vm)
    {
        if (ModelState.IsValid)
        {
            var repo = new EFLibraryRepository();
            repo.Save(new Book(){
                AuthorId = vm.AuthorId,
                PublicationDate = vm.PublicationDate,
                Title = vm.Title,
                Edition = vm.Edition
            });
            return RedirectToAction(""Index"");
        }
        return View(""Edit"", vm);
    }
</code></pre>

<p>My mock repository: </p>

<pre><code>public class EFLibraryRepository : ILibraryRepository
{
    AuthorAndBookDbModel db = new AuthorAndBookDbModel();
    public IQueryable&lt;Author&gt; Authors { get { return db.Authors; } }

    public IQueryable&lt;Book&gt; Books { get { return db.Books; } }

    public void Delete(Book book)
    {
        db.Books.Remove(book);
        db.SaveChanges();
    }

    public void Delete(Author author)
    {
        db.Authors.Remove(author);
        db.SaveChanges();
    }

    public Book Save(Book book)
    {
        if (book.Id == 0)
        {
            db.Books.Add(book);
        }
        else
        {
            db.Entry(book).State = System.Data.Entity.EntityState.Modified;
        }
        db.SaveChanges();
        return book;
    }
    public Author Save(Author author)
    {
        if (author.Id == 0)
        {
            db.Authors.Add(author);
        }
        else
        {
            db.Entry(author).State = System.Data.Entity.EntityState.Modified;
        }
        db.SaveChanges();
        return author;
    }
}
</code></pre>

<p>The ILibraryRepository:</p>

<pre><code>public interface ILibraryRepository
{
    IQueryable&lt;Book&gt; Books { get; }
    IQueryable&lt;Author&gt; Authors { get; }

    Book Save(Book book);
    Author Save(Author author);

    void Delete(Book book);
    void Delete(Author author);
}
</code></pre>
",https://stackoverflow.com/questions/47916275/crud-edit-operation-using-a-viewmodel-with-unit-testing,"['c#', 'asp.net', 'asp.net-mvc', 'unit-testing']",58,TRUE,2,1
Unit testing multiple dispatched actions in React Redux with Jest,"<p>I have a feeling i'm missing something simple but I have an action that dispatches two actions if a condition is met.</p>

<p><strong>Action</strong></p>

<pre class=""lang-js prettyprint-override""><code>export function changeDateRange({ startDate, endDate }) {
  return function reload(dispatch, getState) {
    if (!getState().navigation.focused) {
      // If our datepicker has closed, reload the data on the page
      dispatch(load());
    }
    dispatch({
      type: types.CHANGE_DATE_RANGE,
      startDate,
      endDate
    });
  };
}
</code></pre>

<p>Then I am trying to test load() and have mocked it with a <code>Jest.fn()</code> but when I log <code>mock.calls.length</code> after dispatching <code>changeDateRange()</code> It equals <code>0</code>?</p>

<p>Setup</p>

<pre class=""lang-js prettyprint-override""><code>import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
global.mockStore = configureMockStore([thunk]);
</code></pre>

<p>Test:</p>

<pre class=""lang-js prettyprint-override""><code>import * as types from '../actionTypes';
import * as changeDateRange from './changeDateRange';
import { load } from '../reporting';

jest.mock('../reporting', () =&gt; ({
  load: () =&gt; jest.fn()
}));

describe('Reducer: changeDateRange Reducer', () =&gt; {
  it('should change date range', () =&gt; {
    const store = mockStore({
      startDate: '',
      endDate: '',
      navigation: {
        focused: false
      }
    });
    const dateRange = {
      startDate: 'yes',
      endDate: 'yes'
    };
    store.dispatch(changeDateRange(dateRange));
    expect(store.getActions()).toEqual([
      Object.assign(
        {
          type: types.CHANGE_DATE_RANGE
        },
        dateRange
      )
    ]);
    console.log(load().mock.calls.length); // === 0 ??
  });
});
</code></pre>

<p>Any ideas?</p>
",https://stackoverflow.com/questions/45003269/unit-testing-multiple-dispatched-actions-in-react-redux-with-jest,"['unit-testing', 'redux', 'jestjs', 'redux-thunk']",2099,TRUE,8,1
Cannot read property &#39;&#39; of undefined Angular 4 - unit testing,"<p>i'm learning angular 4. My app work's well but know i would like to UnitTest my components. Here's what i've done : </p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import {CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA } from '@angular/core';
import { Http,ConnectionBackend,BaseRequestOptions } from '@angular/http';
import {MockBackend} from '@angular/http/testing';

import {DxSchedulerModule, DxCheckBoxModule, DxSelectBoxModule} from 'devextreme-angular';

import { CalendrierComponent } from './calendrier.component';
import {CalendrierModule} from './calendrier.module';

import {Person} from '../models/persons.model'
import {PersonsService} from '../services/persons.services'

import {Appointment} from '../models/appointment.model'
import {AppointmentService} from '../services/appointment.service'

describe('CalendrierComponent', () =&gt; {
  let component: CalendrierComponent;
  let fixture: ComponentFixture&lt;CalendrierComponent&gt;;

  let personService:PersonsService;
  let appointmentService:AppointmentService;


  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ CalendrierComponent],
      imports:[DxSchedulerModule, DxCheckBoxModule, DxSelectBoxModule],
      providers: [AppointmentService,
        PersonsService,
        MockBackend,
        BaseRequestOptions,
        { provide: Http,
          useFactory: (backend: ConnectionBackend,
                       defaultOptions: BaseRequestOptions) =&gt; {
                         return new Http(backend, defaultOptions);
                       }, deps: [MockBackend, BaseRequestOptions] },
      ],
      schemas:[NO_ERRORS_SCHEMA]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(CalendrierComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be created', () =&gt; {
    expect(component).toBeTruthy();
  });

  it('should have a defined component', () =&gt; {
    expect(component).toBeDefined();
  });

  it('add30mnto should return an hour with 30min more', () =&gt; {
    expect(appointmentService.add30mnTo('2017-08-16T12:30:00.000Z')).toEqual('2017-08-16T13:00:00.000Z');
  });
</code></pre>

<p>and here is the service i would like to test :</p>

<pre><code>import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import {Observable} from 'rxjs/Rx';
import { Appointment } from '../models/appointment.model';
import {PersonsService} from './persons.services'

@Injectable()
export class AppointmentService {

private AppointmentUrlGet = 'http://localhost/v0/croissants';
private AppointmentUrlWrite = 'http://localhost/v0/croissant';


public handleError(error: any): Promise&lt;any&gt; {
  console.error('An error occurred', error); // for demo purposes only
  return Promise.reject(error.message || error);
}

  constructor(private http: Http, private personsService: PersonsService) {}


  add30mnTo(date : string){
    var initialdate = (this.datetotimestamp(date) + 1800) * 1000;
    var dateinit = new Date (initialdate)
    var result = dateinit.toISOString();
    return result;
  }
.
.
.
.
}
</code></pre>

<p>after having a lot of trouble(ConnectionBackend for example), i have this error : Cannot read property 'add30mnTo' of undefined.</p>

<p>I've already checked these topics : <a href=""https://stackoverflow.com/questions/38026741/jasmine-angular-unit-test-cannot-read-property-of-undefined"">Jasmine angular unit test &#39;Cannot read &#39;property&#39; of undefined</a>
<a href=""https://stackoverflow.com/questions/42039728/angular-2-unit-testing-cannot-read-property-root-of-undefined"">Angular 2 Unit Testing - Cannot read property &#39;root&#39; of undefined</a></p>

<p>but theses solutions don't work for me... Did anyone have an idea of what i've did wrong ? Thanks !!</p>
",https://stackoverflow.com/questions/45820381/cannot-read-property-of-undefined-angular-4-unit-testing,"['javascript', 'angular', 'unit-testing', 'jasmine']",5608,TRUE,1,1
Unit testing a controller with automapper mapping in it,"<p>I have an asp.net webapi project, in which I have a controller that I want to unit test. In that controller I have a mapping. The controller inherits from a base controller, of which the implementation is:</p>

<pre><code>public class BaseController : ApiController
{
    /// &lt;summary&gt;
    /// AutoMapper Mapper instance to handle all mapping.
    /// &lt;/summary&gt;
    protected IMapper GlobalMapper =&gt; AutoMapperConfig.Mapper;
}
</code></pre>

<p>I now want to unit test the controller. My automapper configuration looks like this:</p>

<pre><code>    public static class AutoMapperConfig
    {
        /// &lt;summary&gt;
        /// Provides access to the AutoMapper configuration.
        /// &lt;/summary&gt;
        public static MapperConfiguration MapperConfiguration { get; private set; }

        /// &lt;summary&gt;
        /// Provides access to the instance of the AutoMapper Mapper object to perform mappings.
        /// &lt;/summary&gt;
        public static IMapper Mapper { get; private set; }

        /// &lt;summary&gt;
        /// Starts the configuration of the mapping.
        /// &lt;/summary&gt;
        public static void Start()
        {
            MapperConfiguration = new MapperConfiguration(cfg =&gt;
            {
                cfg.AddProfile&lt;MeldingProfiel&gt;();
                cfg.AddProfile&lt;GebouwProfiel&gt;();
                cfg.AddProfile&lt;AdresProfiel&gt;();
            });

            MapperConfiguration.AssertConfigurationIsValid();

            Mapper = MapperConfiguration.CreateMapper();
        }
    }
</code></pre>

<p>How can I unit test the controller that has this automapper mapping in it?</p>
",https://stackoverflow.com/questions/44386900/unit-testing-a-controller-with-automapper-mapping-in-it,"['unit-testing', 'asp.net-web-api', 'automapper']",798,TRUE,1,1
Angular unit Testing spyOn().and.callthrough doesn&#39;t call actual funciton,"<p>I am new in unit testing with Jasmine in Angular.</p>

<p>I am currently testing a service that has a function called <strong>loadSomething(id)</strong> and I have added a console.info in it.</p>

<p>MY SERVICE:</p>

<pre><code>function loadSomething(id)
{
    console.info('this is a test message');
    return (a promise from a POST request)
}
</code></pre>

<p>And this is my test (spec) file:</p>

<pre><code>//verify that the load function exists
it('load snapshot',function(){

  expect(MyService.loadSomething(108)); //statement 1
  spyOn(MyService, 'loadSomething').and.callThrough(); //statement 2
});
</code></pre>

<p>So, I read online that the callthrough method of SpyOn calls the ACTUAL function.
However, when i run my test with the expect statement (statement 1) the console.info message is invoked (that works fine). On the other hand, when I comment out statement 1 and uncomment the SpyOn(statement 2) I do not get the console.info message anymore.</p>

<p>I would expect the exact opposite to happen.
Have I understood something wrong here?</p>

<p>(the rest of the code works fine, both the spec file and the actual service, I just don't really get this specific thing)</p>
",https://stackoverflow.com/questions/44009074/angular-unit-testing-spyon-and-callthrough-doesnt-call-actual-funciton,"['angularjs', 'unit-testing', 'jasmine', 'karma-jasmine', 'spyon']",11049,TRUE,1,1
Unit testing classes with expo sqlite calls in jest,"<p>Having trouble learning to unit test my expo/react-native app. How would I unit test adding transactions to the store in this class:</p>

<pre><code>export default class TransactionsStore {
    @observable _transactions = [];

    constructor(rootStore) {
        this.rootStore = rootStore;
    }

    @action addTransaction(t, db) {
        db.transaction(tx =&gt; {
            tx.executeSql(
                'INSERT INTO transactions (categoryId, description, date, amount, currencyCode, isReported) VALUES (?,?,?,?,?,?);',
                [t.category, t.description, t.date, t.amount, t.currency.code, t.report],
                (tx, result) =&gt; { t.id = result.insertId; }
            );
        }, error =&gt; alert(error));
        this.reloadTransactions(db);
    }
}
</code></pre>

<p>All the callbacks within callbacks make this very difficult. I guess I have to mock <code>db.transaction</code> somehow but I can't see how to do it in such a way to give a fake <code>(tx, result)</code> into that nested function of <code>executeSql</code>.</p>
",https://stackoverflow.com/questions/46533818/unit-testing-classes-with-expo-sqlite-calls-in-jest,"['javascript', 'sqlite', 'unit-testing', 'jestjs', 'expo']",1019,TRUE,1,1
Unit testing a directive that uses ComponentFactory and Injector,"<p>Using Angular 4.2, I have written a directive that builds a component on the fly and inserts it into the DOM using Angular's ComponentFactory and Injector. Here's an example of the code:</p>

<p><a href=""https://plnkr.co/edit/wO9EWWJZxEL221ktsZGE?p=preview"" rel=""nofollow noreferrer"">https://plnkr.co/edit/wO9EWWJZxEL221ktsZGE?p=preview</a></p>

<p>I want to write a spec for this directive. Normally I would build a test component and attach it to the test bed. However, the directive injects its component into the document DOM which does not exist in a test bed. How do I test for the directive's behavior?</p>

<p>Example spec (pseudo-code):</p>

<pre><code>@Component({
    template: '&lt;h3 appExample&gt;Example&lt;/h3&gt;'
})
class TestComponent {}

describe('ExampleDirective', () =&gt; {
    let fixture: ComponentFixture&lt;TestComponent&gt;;

    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            imports: [ BrowserModule ],
            declarations: [
                TestComponent,
                ExampleDirective,
                ExampleDirectiveComponent
            ]
        });

        fixture = TestBed.createComponent(TestComponent);
        fixture.detectChanges();
    });

    it('should fire directive', fakeAsync(() =&gt; {
        const template = fixture.debugElement.query(By.css('h3'));
        template.nativeElement.dispatchEvent(new Event('click'));
        fixture.detectChanges();
        tick();
        console.log('fixture', fixture.componentInstance);
    }));
});
</code></pre>

<p>The console.log shows that nothing has been attached to the fixture even though the directive was fired.</p>
",https://stackoverflow.com/questions/45745177/unit-testing-a-directive-that-uses-componentfactory-and-injector,"['angular', 'unit-testing', 'angular2-directives']",692,FALSE,1,0
Can&#39;t find module when unit testing react router 4,"<p>I'm trying to unit test a simple router system using <a href=""https://github.com/ReactTraining/react-router"" rel=""nofollow noreferrer"">react-router 4</a>, and when I try to check if the Component it should render exists, it returns <code>0</code>, failing the test.</p>

<p>This is how I setup my test:</p>

<pre><code>import React from ""react"";
import { mount } from ""enzyme"";
import { MemoryRouter } from ""react-router-dom"";

import Routes from ""./Routes"";

import Home from ""./view/Home"";

describe(""Test react router"", () =&gt; {
    it(""Should test for initial route"", () =&gt; {
        const component = mount(
            &lt;MemoryRouter initialEntries={[ '/' ]} initialIndex={0}&gt;
                &lt;Routes /&gt;
            &lt;/MemoryRouter&gt;
        )

        expect( component.find(Home).length ).toBe(1);
    })
});
</code></pre>

<p>However the end result is <code>0</code> and not <code>1</code>, even if the routing is working just fine when navigating on the page. What am i doing wrong here? Am I doing it right or is there a better aproach to test if the router is rendering what it supposed to be rendering?</p>

<p>Also, what should I be testing on a route? I know the loaded component should be tested separately, so should I just test if the url and component match what it's expected to be?</p>
",https://stackoverflow.com/questions/43359438/cant-find-module-when-unit-testing-react-router-4,"['unit-testing', 'reactjs', 'react-router']",271,FALSE,1,0
How to do Unit Testing Firebase Realtime iOS Swift?,"<p>I couldn't find a single link (hope I'm not wrong) about this specific topic. Doing unit test in your service class for Realtime Firebase in Swift.</p>

<p>I'm beginner in TDD and Unit Testing in iOS, and I do my unit test for my networking services like this:</p>

<pre><code>class SampleServiceTest: XCTestCase {

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }

    func testDisconnect() {

        let exp = expectation(description: ""SomeService does stuff and runs the callback closure"")

        let sampleService = SampleService()
        sampleService.disconnect(Auth.auth().currentUser!.uid) { (error) in
            XCTAssertNil(error)
            exp.fulfill()
        }

        waitForExpectations(timeout: 1) { error in
            if let error = error {
                XCTFail(""waitForExpectationsWithTimeout errored: \(error)"")
            }
        }
    }
}
</code></pre>

<p>But again, the question is how to do a test for a realtime connection? Purpose is, for example, a continuous receiving of chat messages. The sample script I gave will just wait for a callback with timeout. Is it possible?</p>
",https://stackoverflow.com/questions/44637264/how-to-do-unit-testing-firebase-realtime-ios-swift,"['ios', 'swift', 'unit-testing', 'tdd', 'xctest']",409,FALSE,1,0
Using moq to mock a repository for unit testing,"<p>I have the following ticket repository:</p>

<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Moq;
using SC.BL.Domain;

namespace SC.DAL
{
  public class TicketRepositoryHC : ITicketRepository
  {
    private List&lt;Ticket&gt; tickets;
    private List&lt;TicketResponse&gt; responses;
    private Mock&lt;IList&lt;Ticket&gt;&gt; ticketsMock;

    public TicketRepositoryHC()
    {
      Seed();
    }

    public TicketRepositoryHC(Mock&lt;IList&lt;Ticket&gt;&gt; ticketsMock)
    {
        this.ticketsMock = ticketsMock;
        Seed();
    }

    private void Seed()
    {
      tickets = new List&lt;Ticket&gt;();
      responses = new List&lt;TicketResponse&gt;();

      // Aanmaken eerste ticket met drie responses
      Ticket t1 = new Ticket()
      {
        TicketNumber = tickets.Count + 1,
        AccountId = 1,
        Text = ""Ik kan mij niet aanmelden op de webmail"",
        DateOpened = new DateTime(2012, 9, 9, 13, 5, 59),
        State = TicketState.Closed,
        Responses = new List&lt;TicketResponse&gt;()
      };

      tickets.Add(t1);

      TicketResponse t1r1 = new TicketResponse()
      {
        Id = responses.Count + 1,
        Ticket = t1,
        Text = ""Account is geblokkeerd"",
        Date = new DateTime(2012, 9, 9, 13, 24, 48),
        IsClientResponse = false
      };
      t1.Responses.Add(t1r1);
      responses.Add(t1r1);

      TicketResponse t1r2 = new TicketResponse()
      {
        Id = responses.Count + 1,
        Ticket = t1,
        Text = ""Account terug in orde en nieuw paswoord ingesteld"",
        Date = new DateTime(2012, 9, 9, 13, 29, 11),
        IsClientResponse = false
      };
      t1.Responses.Add(t1r2);
      responses.Add(t1r2);

      TicketResponse t1r3 = new TicketResponse()
      {
        Id = responses.Count + 1,
        Ticket = t1,
        Text = ""Aanmelden gelukt en paswoord gewijzigd"",
        Date = new DateTime(2012, 9, 10, 7, 22, 36),
        IsClientResponse = true
      };
      t1.Responses.Add(t1r3);
      responses.Add(t1r3);

      t1.State = TicketState.Closed;


      //Aanmaken tweede ticket met één response
      Ticket t2 = new Ticket()
      {
        TicketNumber = tickets.Count + 1,
        AccountId = 1,
        Text = ""Geen internetverbinding"",
        DateOpened = new DateTime(2012, 11, 5, 9, 45, 13),
        State = TicketState.Open,
        Responses = new List&lt;TicketResponse&gt;()
      };

      tickets.Add(t2);

      TicketResponse t2r1 = new TicketResponse()
      {
        Id = responses.Count + 1,
        Ticket = t2,
        Text = ""Controleer of de kabel goed is aangesloten"",
        Date = new DateTime(2012, 11, 5, 11, 25, 42),
        IsClientResponse = false
      };
      t2.Responses.Add(t2r1);
      responses.Add(t2r1);

      t2.State = TicketState.Answered;

      //Aanmaken eerste HardwareTicket
      HardwareTicket ht1 = new HardwareTicket()
      {
        TicketNumber = tickets.Count + 1,
        AccountId = 2,
        Text = ""Blue screen!"",
        DateOpened = new DateTime(2012, 12, 14, 19, 15, 32),
        State = TicketState.Open,
        //Responses = new List&lt;TicketResponse&gt;(),
        DeviceName = ""PC-123456""
      };

      tickets.Add(ht1);
    }

    #region 'ITicketRepository' implementatie
    public Ticket CreateTicket(Ticket ticket)
    {
      ticket.TicketNumber = tickets.Count + 1;
      tickets.Add(ticket);

      return ticket; //return van ticket testen, niet ReadTicket gebruiken
    }

    public IEnumerable&lt;Ticket&gt; ReadTickets()
    {
      return tickets;
    }

    public Ticket ReadTicket(int ticketNumber)
    {
      return tickets.Find(t =&gt; t.TicketNumber == ticketNumber);
    }

    public void UpdateTicket(Ticket ticket)
    {
      // Do nothing! All data lives in memory, everything references the same objects!!
    }

    public void DeleteTicket(int ticketNumber)
    {
      this.responses.RemoveAll(r =&gt; r.Ticket.TicketNumber == ticketNumber);
      this.tickets.Remove(ReadTicket(ticketNumber));
    }

    public IEnumerable&lt;TicketResponse&gt; ReadTicketResponsesOfTicket(int ticketNumber)
    {
      return tickets.Find(t =&gt; t.TicketNumber == ticketNumber).Responses;
    }

    public TicketResponse CreateTicketResponse(TicketResponse response)
    {
      response.Id = responses.Count + 1;
      responses.Add(response);
      return response;
    }
    #endregion
  }
}
</code></pre>

<p>Now, I want to write the following Unit Test (the name of the Unit Test is ""TicketHasToBeReadCorrectly, simply I want to test if the ticket that has been added to the repository can be read correctly:</p>

<pre><code>namespace TicketRepositoryTest
{
    [TestClass]
    public class TicketRepositoryTest
    {
        [TestMethod]
        public void TicketMoetCorrectGelezenWorden()
        {
            //Arrange

            var ticketsMock = new Mock&lt;IList&lt;Ticket&gt;&gt;();

            ITicketRepository ticketRepo = new TicketRepositoryHC(ticketsMock);

            //Act

            Ticket ticket = new Ticket() {
                //TicketNumber = 2,
                AccountId = 1,
                Text = ""Ik kan mij niet aanmelden op de webmail"",
                DateOpened = new DateTime(2012, 9, 9, 13, 5, 59),
                State = TicketState.Open,
                Responses = new List&lt;TicketResponse&gt;()
            };

            var returnTicket = ticketRepo.CreateTicket(ticket);


            //Assert
            ticketsMock.Verify(l =&gt; l.Add(It.IsAny&lt;Ticket&gt;()));
            Assert.ReferenceEquals(ticket, returnTicket);
            Assert.IsTrue(ticket.TicketNumber != default(int));

        }
    }
}
</code></pre>

<p>But this test fails with the following message:</p>

<blockquote>
  <p>Test Name:    TicketMoetCorrectGelezenWorden Test
  FullName: TicketRepositoryTest.TicketRepositoryTest.TicketMoetCorrectGelezenWorden
  Test
  Source:   .Eg_SupportCenter\TicketRepositoryTest\TicketRepositoryTest.cs
  : line 19 Test Outcome:   Failed Test Duration:   0:00:00,0388466</p>
  
  <p>Result StackTrace:     at Moq.Mock.ThrowVerifyException(MethodCall
  expected, IEnumerable<code>1 setups, IEnumerable</code>1 actualCalls, Expression
  expression, Times times, Int32 callCount)    at
  Moq.Mock.VerifyCalls(Interceptor targetInterceptor, MethodCall
  expected, Expression expression, Times times)    at
  Moq.Mock.Verify[T](Mock<code>1 mock, Expression</code>1 expression, Times times,
  String failMessage)    at Moq.Mock<code>1.Verify(Expression</code>1 expression)<br>
  at
  TicketRepositoryTest.TicketRepositoryTest.TicketMoetCorrectGelezenWorden()
  in
  .\Eg_SupportCenter\TicketRepositoryTest\TicketRepositoryTest.cs:line
  41 Result Message:     Test method
  TicketRepositoryTest.TicketRepositoryTest.TicketMoetCorrectGelezenWorden
  threw exception:  Moq.MockException:  Expected invocation on the mock
  at least once, but was never performed: l => l.Add(It.IsAny())
  No setups configured. No invocations performed.</p>
</blockquote>

<p>Could anyone tell me what I'm doing wrong?
TicketRepository with Mock:</p>

<pre><code> public class TicketRepositoryHC : ITicketRepository
  {
    private List&lt;Ticket&gt; tickets;
    private List&lt;TicketResponse&gt; responses;
    private Mock&lt;IList&lt;Ticket&gt;&gt; ticketsMock;

        public TicketRepositoryHC()
    {
      Seed();
    }

        public TicketRepositoryHC(Mock&lt;IList&lt;Ticket&gt;&gt; ticketsMock)
        {
            this.ticketsMock = ticketsMock;
            Seed();
        }
</code></pre>
",https://stackoverflow.com/questions/42748851/using-moq-to-mock-a-repository-for-unit-testing,"['c#', 'unit-testing', 'moq']",2022,FALSE,1,1
QT Unit Testing moc &quot;unresolved external symbol&quot; for QMetaObject,"<p>I'm trying to add unit tests to a project of mine for the first time.</p>

<p>I can run mock tests alright (without using my project's classes) and run the application alright. But if I instantiate objects from the project I get an unresolved external symbol of the QMetaObject. If I recall correctly, this means the moc of the object isn't being included on the project.</p>

<p>How do I fix this? I have the same issue using googletests. The guide also doesn't help on this. I've tried installing the qt unit testing plugin, same result.</p>

<p>I've uploaded a mock project that follows the same structure that I'm using in the aforementioned project, fetch it here: <a href=""https://github.com/quimnuss/QtUnitTestingTest"" rel=""nofollow noreferrer"">https://github.com/quimnuss/QtUnitTestingTest</a></p>

<p>I'm using a static build of qt on windows, but I guess that's irrellevant. Using QtCreator as IDE and NMAke build.</p>

<p>I've also tried add the HelloWorld.lib, but taking a look at the Makefile.release it isn't used.</p>

<p>Somebody has an idea of what I'm doing wrong?</p>

<p>Here's the unit testing .pro:</p>

<pre><code>QT       += widgets network testlib

TARGET = tst_someunittesttest
CONFIG   += console
CONFIG   -= app_bundle

TEMPLATE = app

INCLUDEPATH += $$PWD/../HelloWorld

include($$PWD/../HelloWorld/helloworldCommon.pri)

LIBS += -L""$$OUT_PWD/../HelloWorld/release""
LIBS += -lHelloWorld

message(""Searching libs here $$LIBS"")

SOURCES += tst_someunittesttest.cpp
DEFINES += SRCDIR=\\\""$$PWD/\\\""
</code></pre>

<p>The first error's complete message:</p>

<pre><code>tst_someunittesttest.obj : error LNK2001: unresolved external symbol ""public: virtual struct QMetaObject const * __cdecl HelloWorld::metaObject(void)const "" (?metaObject@HelloWorld@@UEBAPEBUQMetaObject@@XZ)
</code></pre>
",https://stackoverflow.com/questions/41510411/qt-unit-testing-moc-unresolved-external-symbol-for-qmetaobject,"['c++', 'qt', 'unit-testing']",1168,TRUE,1,1
can we check the validation of uitextfield while Unit Testing?,"<p>Suppose we have some validation in our <code>ViewController</code> ( say vc1 ) for a <code>UItextfield</code> in <code>shouldChangeCharactersInRange</code> method, as user only can enter the numbers not the alphabets or other special character.</p>

<p>I just want to know that in our <code>XCTestCase</code> class, is this possible in unit testing, to check for a particular <code>uitextfield</code>, is allowing some characters (in my case only numbers) or not?</p>
",https://stackoverflow.com/questions/47389161/can-we-check-the-validation-of-uitextfield-while-unit-testing,"['ios', 'unit-testing', 'xctest']",3066,TRUE,8,2
Unit Testing a Class-based DSC resource with Pester,"<p>I am having a problem with unit testing a class-based DSC resource. I am trying to Mock a couple of functions in the class and I get a cast error.</p>

<pre><code>PSInvalidCastException: Cannot convert the ""bool TestVMExists(string vmPath,     
string vmName)"" value of type ""System.Management.Automation.PSMethod"" to type
""System.Management.Automation.ScriptBlock"".
</code></pre>

<p>My test code is this:</p>

<pre><code>using module 'C:\Program Files\WindowsPowerShell\Modules\xVMWareVM\xVMWareVM.psm1'

$resource = [xVMWareVM]::new()

   Describe ""Set"" {

    Context ""If the VM does not exist"" {

        Mock xVMWareVM $resource.TestVMExists {return $false}
        Mock xVMWareVM $resource.CreateVM

        It ""Calls Create VM once"" {
            Assert-MockCalled $resource.CreateVM -Times 1
        }
    }
}
</code></pre>

<p>Does anyone know how to achieve this?</p>

<p>Thanks in advance</p>
",https://stackoverflow.com/questions/41703468/unit-testing-a-class-based-dsc-resource-with-pester,"['unit-testing', 'powershell', 'dsc', 'pester']",537,TRUE,1,1
How to write Unit Testing with Dagger 2 Subcomponent,"<p>I'm just starting to use Dagger 2 in my Android application, And I'm trying to write Unit Tests that their Modules are defined as Subcomponents.</p>

<p>I've read Google's post about <a href=""https://google.github.io/dagger/testing.html"" rel=""nofollow noreferrer"">Testing with Dagger</a>. And this very helpful <a href=""https://medium.com/@fabioCollini/android-testing-using-dagger-2-mockito-and-a-custom-junit-rule-c8487ed01b56"" rel=""nofollow noreferrer"">Medium post</a> as well. But I only found examples on how to test with Components but not Subcomponents. And I can't seem to get it to work.</p>
",https://stackoverflow.com/questions/44832404/how-to-write-unit-testing-with-dagger-2-subcomponent,"['android', 'unit-testing', 'junit', 'mockito', 'dagger-2']",292,FALSE,1,1
Fluent Validation unit testing SetValidator with a When clause,"<p>I'm trying to unit test the ability to set child validator depending on a property value.</p>

<pre><code>RuleFor(x =&gt; x.Property2)
    .SetValidator(new Property2Validator())
    .When(x =&gt; x.Property1 == 1);
</code></pre>

<p>In my unit test I have the following assertion</p>

<pre><code>validatorUnderTest.ShouldHaveChildValidator(x =&gt; x.Property2, typeof(Property2Validator));
</code></pre>

<p>However this always fail as the validator is only attached whilst the validation is taking place. If I remove the 'When' clause it picks it up fine.</p>
",https://stackoverflow.com/questions/44043431/fluent-validation-unit-testing-setvalidator-with-a-when-clause,"['c#', 'unit-testing', 'fluentvalidation']",900,FALSE,1,0
Module is not available in angularjs + Jasmine Unit testing,"<p>Module is defined as </p>

<pre><code>var $manage = angular.module('manage', [....]);
</code></pre>

<p>Controller is defined as</p>

<pre><code>    $manage.line.events.controller('eventsController', [..., function(...){
$scope.page = ""events"";
}]);
</code></pre>

<p>My simple unit test case is</p>

<pre><code>describe('Module: manage', function() {
  beforeEach(module('manage'));
  var scope, ctrl, rootScope;
  beforeEach(inject(function($rootScope, $controller) {
      scope = $rootScope.$new();
      ctrl = $controller('eventsController', {
          $scope: scope
      });
  }));
  it(""test page"", function () {
        expect(scope.page).toEqual('events');
    });
});
</code></pre>

<p>Here, i am getting a error like</p>

<p>Failed to instantiate module ampleManage due to.... manage is not available.</p>

<p>I have integrated angular-mocks.js also. Tried so many possibilities but not working for me.</p>

<p>Basic need is .</p>

<p>Need to access controller/scope in test case. </p>
",https://stackoverflow.com/questions/42852629/module-is-not-available-in-angularjs-jasmine-unit-testing,"['angularjs', 'unit-testing', 'karma-jasmine']",489,FALSE,1,0
Getting BeanInstantiationException while unit testing RestController with Pageable parameter,"<p>I am developing a RESTful service application using Spring Boot 1.5.4.</p>

<p>One method(findAll) in my resource class takes Pageable parameter and uses it to call service method. I am getting <strong>BeanInstantiationException</strong> while unit testing this method.</p>

<p>This is my Resource class - </p>

<pre><code>@RestController
@RequestMapping(""/api/v1/users"")
public class UserResource {

    private final UserService userService;

    @Autowired
    public UserResource(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("""")
    public ResponseEntity&lt;List&lt;User&gt;&gt; findAll(Pageable pageable) {
        log.debug(""REST request to get a page of Users"");
        Page&lt;User&gt; page = userService.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, ""/api/v1/users"");
        return new ResponseEntity&lt;&gt;(page.getContent(), headers, HttpStatus.OK);
    }
}
</code></pre>

<p>This is my Service class - </p>

<pre><code>@Service
@Transactional
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;

    @Autowired
    public UserServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    @Transactional(readOnly = true)
    public Page&lt;User&gt; findAll(Pageable pageable) {
        return userRepository.findAll(pageable);
    }
}
</code></pre>

<p>This is my Test class -</p>

<pre><code>@RunWith(SpringRunner.class)
@WebMvcTest(UserResource.class)
public class UserResourceTest {

    private static final ObjectMapper mapper = new ObjectMapper();

    @Autowired
    private MockMvc mvc;

    @MockBean
    private UserService userService;

    private static final Long DEFAULT_ID = 1L;
    private static final String DEFAULT_EMAIL = ""test@test.com"";
    private static final String DEFAULT_FIRSTNAME = ""john"";
    private static final String DEFAULT_LASTNAME = ""doe"";
    private static final String DEFAULT_PASSWORD = ""ABCDEFGHJIABCDEFGHJIABCDEFGHJIABCDEFGHJIABCDEFGHJIABCDEFGHJI"";
    private static final UserStatus DEFAULT_STATUS = UserStatus.ACTIVE;
    private static final String DEFAULT_PHONE = ""12345679"";

    public static User createUserWithOutId() {
        User user = new User();
        user.setEmail(DEFAULT_EMAIL);
        user.setFirstName(DEFAULT_FIRSTNAME);
        user.setLastName(DEFAULT_LASTNAME);
        user.setPassword(DEFAULT_PASSWORD);
        user.setStatus(DEFAULT_STATUS);
        user.setPhone(DEFAULT_PHONE);
        return user;
    }

    public static User createUserWithId() {
        User user = createUserWithOutId();
        user.setId(DEFAULT_ID);
        return user;
    }

    @Test
    public void findAll_WhenUsersExist_ShouldReturnUsersList() throws Exception {
        final User user = createUserWithId();
        List&lt;User&gt; users = Arrays.asList(user);
        Page&lt;User&gt; page = new PageImpl&lt;&gt;(users, new PageRequest(0, 10), users.size());
        when(userService.findAll(any(PageRequest.class)))
                .thenReturn(page);
        mvc.perform(get(""/api/v1/users"").accept(MediaType.APPLICATION_JSON_VALUE))
                .andExpect(status().isOk());
    }
}
</code></pre>

<p>Stack-trace of the Exception - </p>

<pre><code>Tests run: 7, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.76 sec &lt;&lt;&lt; FAILURE! - in bd.com.ronnie.accountservice.web.rest.UserResourceTest
findAll_WhenUsersExist_ShouldReturnUsersList(bd.com.ronnie.accountservice.web.rest.UserResourceTest)  Time elapsed: 0.041 sec  &lt;&lt;&lt; ERROR!
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.domain.Pageable]: Specified class is an interface
        at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:99)
        at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.createAttribute(ModelAttributeMethodProcessor.java:141)
        at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.createAttribute(ServletModelAttributeMethodProcessor.java:81)
        at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:101)
        at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
        at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:158)
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128)
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
        at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
        at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
        at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
        at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
        at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
        at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
        at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
        at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
        at bd.com.ronnie.accountservice.web.rest.UserResourceTest.findAll_WhenUsersExist_ShouldReturnUsersList(UserResourceTest.java:97)
</code></pre>
",https://stackoverflow.com/questions/45048767/getting-beaninstantiationexception-while-unit-testing-restcontroller-with-pageab,"['java', 'unit-testing', 'spring-boot']",488,FALSE,1,1
How to inject dependence in Unit testing with cpputest,"<p>I'm writing an Unit Test (in <em>cpputest</em>) where I try to perform an ""dependence injection"" to a function call. This means when the Unit Test have to call the real function which is placed within the file under test, the function call should be redirected to a ""fake"" implementation. Actually I'm assigning function pointer to the real function and overwriting it with the ""fake implementation"". It's constructed as follow:</p>

<pre><code>============ myfile.h =========================
 int8 my_function_FAKE (int8 address)     // Declaration of my_function_FAKE
==============================================

================= myfile.c ====================
#include ""myfile.h""

static int8 my_function (int8 address)   // The original function
{
   return value;
}


#IF DEFINED (UNIT_TEST)
int8 my_function_FAKE (int8 address)   // the ""fake"" of the original function 
{
   switch (address)
   {
      case 10: return 11
      case 20: return 21
      case 30: return 31
   }
}
#ENDIF

======================TEST ENVIRONMENT =======================
==============================================================

========FAKE.h===============
extern int8(*Function)(int8);
=========================

 ========FAKE.c==========
 #include ""myfile.h""
 #include ""FAKE.h""

 int8 (*Function)(int8) = my_function;
 =========================

=======Unit Test File======
Function = my_function_FAKE; // Injecting the fake implementation within unit test file
===========================
</code></pre>

<p>I'm getting the compiler error:</p>

<pre><code>FAKE.c: error C2065: 'my_function' : undeclared identifier
FAKE.c: error C2099: 'my_function' : initializer is not a constant 
</code></pre>

<p>I tried already some combinations but each time the same error. The solution is maybe simple, but I'm overlooking it. So, what I'm doing wrong here? </p>
",https://stackoverflow.com/questions/43051064/how-to-inject-dependence-in-unit-testing-with-cpputest,"['unit-testing', 'mocking', 'cpputest']",246,FALSE,1,1
Unit testing a scoped function used as a filter,"<p>I need to write a scoped function within my controller that acts as a filter. </p>

<pre><code>  $scope.filterR = function(s) {

    return function(c) {
        for (var prop in c) {
          if (c[prop].toSomething() &gt;= 0) {
            return c;
            break;
          }
        }
    }
  }
</code></pre>

<p>This is how I'm using it.</p>

<pre><code>&lt;div ng-repeat=""c in cus | filter: filterR(s)""&gt;
        &lt;/div&gt;
</code></pre>

<p>The trouble I'm facing is how to test this specific routine in karma-jasmine.</p>

<p>My current test looks like this,</p>

<pre><code>describe('check x', function () {
    it('check abc', function () {
      var $scope = {};

      var controller = $controller('SController', {
        $scope: $scope
       });
       expect($scope.filterResults('some_data')).toEqual(
         some_data
       );
    });
</code></pre>

<p>The filter works fine but writing test for it giving me an issue. Any help is appreciated.</p>
",https://stackoverflow.com/questions/42320300/unit-testing-a-scoped-function-used-as-a-filter,"['angularjs', 'filter', 'scope', 'karma-runner', 'karma-jasmine']",22,TRUE,1,1
Angular Unit Testing : How to run a basic Test,"<p>Am new on angular unit testing.</p>

<p>I wanna implement a first running test so i developed this :</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';

describe('AppComponent', () =&gt; {
  let component: AppComponent;
  let fixture: ComponentFixture&lt;AppComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ AppComponent ],
    }).compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('first test', () =&gt; {
    expect('1').toBe('1');
  });
});
</code></pre>

<p>Like you see my first test is to assert that ""1"" is ""1"" , i don't know why i'm facing a problem of getting it successfull , since it throws me such an error :</p>

<pre><code>Error: Template parse errors:   Can't bind to 'min' since it isn't a known property of 'dx-progress-bar'.
    1. If 'dx-progress-bar' is an Angular component and it has 'min' input, then verify that it is part of this module.
    2. If 'dx-progress-bar' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
    3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. (""
        width=""100%""
        [class.complete]=""progressBar.value == maxValue""
        [ERROR -&gt;][min]=""0""
        [max]=""maxValue""
        [statusFormat]=""wordProgression""    ""): ng:///DynamicTestModule/AppComponent.html@15:4
</code></pre>

<p>It's true that i'm using DevExtreme widgets in my app component , but i haven't even tried to test it. i'm just starting by evident test cases.</p>

<p>I need to know how should i fix it?</p>

<p><strong>Suggestions ??</strong></p>
",https://stackoverflow.com/questions/45505935/angular-unit-testing-how-to-run-a-basic-test,"['angular', 'unit-testing', 'typescript', 'jasmine', 'karma-runner']",414,TRUE,1,1
Unit testing assert that json response contains a list,"<p>When writing a unit test in phoenix framework how do you check if a json response contains a list.</p>

<p>Existing test is below which fails because <code>children</code> gets populated. I just want the test to tell me that my json response contains <code>children</code> and <code>children</code> is a list.</p>

<pre><code>test ""shows chosen resource"", %{conn: conn} do
  parent = Repo.insert! %Parent{}
  conn = get conn, parent_path(conn, :show, parent)
  assert json_response(conn, 200)[""data""] == %{""id"" =&gt; parent.id,
    ""children"" =&gt; []}
end
</code></pre>
",https://stackoverflow.com/questions/45196291/unit-testing-assert-that-json-response-contains-a-list,"['unit-testing', 'elixir', 'phoenix-framework']",1889,TRUE,1,2
Dependency injection in CodeIgniter&#39;s controller for easier unit testing,"<p>I am trying to make PHPUnit and CodeIgniter cooperate. The problem is that I have no idea how to use DI in the controller.
e.g.:
</p>

<pre><code>//Non-viewing method called in the form when user click ""register"" button on the registration view.
public function register(){
    //fetchInput is a private method returning an array of wanted data fetched from user input. 
    $insertData = $this-&gt;fetchInput_register();
    $insertData[""permissions""] = ""guest"";

    $this-&gt;load-&gt;model(""Users_model"");
    $this-&gt;Users_model-&gt;insert($insertData);
    redirect(""signing"");
}
</code></pre>

<p>And here is the problem. This method loads the Users_model. Because this is a controller we are supposed to use such methods as ""load"". But this method loads the whole new part of the code. </p>

<p>How am I supposed to unit test this method? I can't use Users_model because it mediates with a database. Should I mock the Users_model? But then I should mock the load method too. I have a feeling that I am doing this in a very wrong way.</p>

<p>P.S. This method is error unfriendly, I know that.</p>
",https://stackoverflow.com/questions/47635204/dependency-injection-in-codeigniters-controller-for-easier-unit-testing,"['php', 'codeigniter', 'unit-testing', 'dependency-injection', 'phpunit']",728,FALSE,1,0
Angular 1.5 Component Unit Testing with Karma Jasmine Failed,"<p>I am trying to unit test an Angular Component with Karma Jasmine for the very first time.</p>

<p>My <code>index.html</code> looks like :</p>

<pre><code>&lt;body ng-app=""heroApp""&gt;
  &lt;!-- components match only elements --&gt;
&lt;div ng-controller=""MainCtrl as ctrl""&gt;
  &lt;b&gt;Hero&lt;/b&gt;&lt;br&gt;
  &lt;hero-detail hero=""ctrl.hero""&gt;&lt;/hero-detail&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>And <code>index.js</code> looks like :</p>

<pre><code>(function(angular) {
  'use strict';
    angular.module('heroApp', []).controller('MainCtrl', function MainCtrl() {
        this.hero = {
            name: 'Miles Bronson'
        };
    });
})(window.angular);
</code></pre>

<p>And the <strong>component</strong> <code>heroDetail.js</code> looks like :</p>

<pre><code>(function(angular){
    'use strict';

    function HeroDetailController(){

    }

    angular.module('heroApp').component('heroDetail',{
        template:'&lt;span&gt;Name: {{$ctrl.hero.name}}&lt;/span&gt;',
        controller:HeroDetailController,
        bindings:{
            hero: '='
        }
    });

})(window.angular);
</code></pre>

<p>Now my karma spec file looks like :</p>

<pre><code>describe('Component:heroDetailComponent',function(){
    beforeEach(function(){
        module('heroApp');
    });

    var element,
        scope;
    beforeEach(inject(function($rootScope,$compile){
        scope = $rootScope.$new();
        scope.outside = ""Miles Bronson"";
        element = angular.element('&lt;hero-detail hero=""{{outside}}""&gt;&lt;/hero-detail&gt;');
        element = $compile(element)(scope);
        scope.$apply();
    }));

    it('should render the text',function(){
        var span = angular.find('span');
        expect(span.text()).toBe('Name: Miles Bronson')
    });

});
</code></pre>

<p>But this <strong>failed</strong>. <code>Saying :</code></p>

<pre><code>Chrome 55.0.2883 (Windows 8.1 0.0.0) Component:heroDetailComponent should render the text FAILED
        Error: [$parse:syntax] Syntax Error: Token '{' invalid key at column 2 of the expression [{{outside}}] starting at [{outside}}].
        http://errors.angularjs.org/1.6.1/$parse/syntax?p0=%7B&amp;p1=invalid%20key&amp;p2=2&amp;p3=%7B%7Boutside%7D%7D&amp;p4=%7Boutside%7D%7D
            at bower_components/angular/angular.js:68:12
            at AST.throwError (bower_components/angular/angular.js:14893:11)
            at AST.object (bower_components/angular/angular.js:14882:16)
            at AST.primary (bower_components/angular/angular.js:14771:22)
            at AST.unary (bower_components/angular/angular.js:14759:19)
            at AST.multiplicative (bower_components/angular/angular.js:14746:21)
            at AST.additive (bower_components/angular/angular.js:14737:21)
            at AST.relational (bower_components/angular/angular.js:14728:21)
            at AST.equality (bower_components/angular/angular.js:14719:21)
            at AST.logicalAND (bower_components/angular/angular.js:14711:21)
        Error: Declaration Location
            at window.inject.angular.mock.inject (bower_components/angular-mocks/angular-mocks.js:3118:25)
            at Suite.&lt;anonymous&gt; (test/controllers/main-controller-spec.js:30:16)
            at test/controllers/main-controller-spec.js:23:1
        TypeError: angular.find is not a function
            at Object.&lt;anonymous&gt; (test/controllers/main-controller-spec.js:39:28)
Chrome 55.0.2883 (Windows 8.1 0.0.0): Executed 3 of 3 (2 FAILED) (0.641 secs / 0.089 secs)
</code></pre>

<p><strong>What am I doing wrong ?</strong>  Please help.</p>

<p>Also , I am declaring an <code>outside</code> variable here and testing the same. </p>

<p><strong>How can I take the variable from the controller and test it without locally declaring it ?</strong></p>
",https://stackoverflow.com/questions/41740946/angular-1-5-component-unit-testing-with-karma-jasmine-failed,"['javascript', 'angularjs', 'unit-testing', 'karma-jasmine']",375,FALSE,1,0
unit testing of AngularJS code deployed under JBoss 7.1EAP,"<p>We all know that one of the best combination for Unit testing for AngularJS code is NodeJS, Jasmine and Karma js framework .</p>

<p>However challenge with our project is that client doesn’t want to use two containers i.e. NodeJS for testing and Jboss for deployment. Reason is the way Angular JS components are packaged for nodeJS is very different from Jboss. Also another angle to this problem is that angular components should be tested in a continuous integration environment. If you have two containers it makes whole CI/CD cycle complex.</p>

<p>Hence we are trying to find out a way on to how to execute these unit test cases with only Jasmine with JBoss 7.1EAP. And without using Nodes and Karma.</p>

<p>Please let us know if someone has faced this issue and let us know the steps for the resolution.</p>

<p>Regards
Debashish</p>
",https://stackoverflow.com/questions/42396800/unit-testing-of-angularjs-code-deployed-under-jboss-7-1eap,"['angularjs', 'jboss7.x']",31,FALSE,1,0
Unit testing exceptions with RequestFixture and HandlingResult in Ratpack,"<p>So I know how to properly check when an exception is thrown, on my handler unit tests.</p>

<p>However, what is the correct approach when I want to make sure an exception was not thrown?</p>

<p>This is the best I've come up with so far:</p>

<pre><code>def ""No exception is thrown""() {
    given:
    def noExceptionThrown = false

    when:
    def result =  RequestFixture.handle(new TestEndpoint(), { fixture -&gt; fixture.uri(""path/a)})

    then:
    try {
        result.exception(CustomException)
    } catch(ratpack.test.handling.HandlerExceptionNotThrownException e) {
        noExceptionThrown = (e != null)
    }

    noExceptionThrown
}
</code></pre>
",https://stackoverflow.com/questions/44400189/unit-testing-exceptions-with-requestfixture-and-handlingresult-in-ratpack,['ratpack'],365,TRUE,1,1
Unit Testing Bot Framework Dialog with LUIS and Moq,"<p>I'm trying to unit testing a method from my dialog, this method is called once the user says a keyword that is known by LUIS. Here the code flow,</p>

<p>""I want to reset my <strong>password</strong>"", password is the entity that is linked to CustomerService intent.</p>

<pre><code>    [LuisIntent(""CustomerService"")]
    public async Task customerServiceRequest(IDialogContext context, LuisResult result)
    {
        try
        {

            var entity = result.Entities.SingleOrDefault(c =&gt; c.Type == ""ServiceKeyword"" &amp;&amp; customerSupportKeywords.Contains(c.Entity.ToLower()));

            if (!ReferenceEquals(entity, null))
            {
                switch (entity.Entity.ToLower())
                {
                    case ""password"":

                        PromptDialog.Choice(context, AfterUserHasChosenAsync, new string[] { ""SMS"", ""Email"" }, ""¿How would you like reset your password?"", attempts: 100);

                        break;
                    default:
                        break;
                }
            }
        }
        catch (exception ex)
        {
        }
    }
</code></pre>

<p>. When I select Email as a via to reset, the bot ask me to enter my email and this input is validated against a regex.</p>

<pre><code>    private async Task AfterUserHasChosenAsync(IDialogContext context, IAwaitable&lt;string&gt; result)
    {
        try
        {
            string userChoice = await result;

            switch (userChoice)
            {
                case ""Email"":
                    context.Call(AskForEmailToVerifyDialog(), AskForEmailToVerifyDialogStep1);
                    break;
                case ""SMS"":
                    context.Call(AskForCellNumberToVerifyDialog(), AskForCellNumberToVerifyDialogStep1);
                    break;
                default:
                    await context.PostAsync(""Something was wrong"");
                    context.Done(true);
                    break;
            }
        }
        catch (TooManyAttemptsException)
        {
            await context.PostAsync(AnswerNotFoundMsg);
            context.Done(true);
        }
        catch (Exception ex)
        {
        }
    }
</code></pre>

<p>.      </p>

<pre><code>private IDialog&lt;ContactMedioObject&gt; AskForEmailToVerifyDialog()
    {
        try
        {

            return Chain.From(() =&gt; new PromptDialog.PromptString(""Please enter your current email"", """", 1).
            ContinueWith&lt;string, ContactMedioObject&gt;(async (context, result) =&gt;
            {
                var email = await result;

                return Chain.Return(new ContactMedioObject() { Email = email });

            }));

        }
        catch (Exception ex)
        {
            throw new ApplicationException(ex.Message);
        }
    }
</code></pre>

<p>.</p>

<pre><code>private async Task AskForEmailToVerifyDialogStep1(IDialogContext context, IAwaitable&lt;ContactMedioObject&gt; result)
{
    try
    {
        var Cell = await result;

        if (!Cell.isValidEmail)
        {
            PromptDialog.Choice(context, OnResumeConfirmEmail, new string[] { ""Yes"", ""No"" }, ""Would you like to try again?"", attempts: 9999);
        }
        else
        {
                await context.PostAsync($""................."");
                context.Done(true);

        }
    }
    catch (Exception ex)
    {
    }
}
</code></pre>

<p>I already unit tested customerServiceRequest following the same sintax from botbuilder repository <a href=""https://github.com/Microsoft/BotBuilder/blob/b6cd3ff85e8dc57ac586a11db489a0c75c635ae2/CSharp/Tests/Microsoft.Bot.Builder.Tests/LuisTests.cs"" rel=""nofollow noreferrer"">https://github.com/Microsoft/BotBuilder/blob/b6cd3ff85e8dc57ac586a11db489a0c75c635ae2/CSharp/Tests/Microsoft.Bot.Builder.Tests/LuisTests.cs</a></p>

<p>But I cannot mock in the same way for AfterUserHasChosenAsync and AskForEmailToVerifyDialogStep1, Any idea how i can test these two method taking in account that AskForEmailToVerifyDialogStep1 returns a promptdialog if it is a bad email adress and a PostAsync if all was OK.?</p>
",https://stackoverflow.com/questions/44763827/unit-testing-bot-framework-dialog-with-luis-and-moq,"['c#', 'unit-testing', 'moq', 'botframework']",630,FALSE,1,0
Unit Testing for Code Coverage of Lambda Expression Condition,"<p>I am using SonarQube for static code analysis and it raises an issue for not able to check for the alternate condition for the <code>if</code> condition for 3rd party library:</p>

<pre><code>CountDownLatch connectedSignal = new CountDownLatch(1);
zookeeper = new ZooKeeper(connectionString,this.sessionTimeout, event -&gt; {
if (event.getState() == KeeperState.SyncConnected) {
      connectedSignal.countDown();
}});

connectedSignal.await();
</code></pre>

<p>Error from Sonarqube:
""1 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage."" It's because I am not covering for the negative if condition in my unit test cases. Question is, how to generate a negative test case in my unit test case for the above if condition?</p>
",https://stackoverflow.com/questions/42495297/unit-testing-for-code-coverage-of-lambda-expression-condition,"['java', 'unit-testing', 'lambda']",2028,TRUE,1,1
RxJavaHooks cannot be resolved in my android unit testing,"<p>In my android unit testing file, I am doing this import:</p>

<blockquote>
  <p>import rx.plugins.RxJavaHooks;</p>
</blockquote>

<p>as I need to use RxJavaHooks.</p>

<p>In my gradle file, i have added the dependency for RxJava and RxAndroid:</p>

<blockquote>
  <p>compile ""io.reactivex:rxandroid:$RXANDROID_VERSION""</p>
  
  <p>compile ""io.reactivex:rxjava:$RXJAVA_VERSION""</p>
</blockquote>

<p>Still, I get an error that RxJavaHooks cannot be resolved. Can someone help me with this. Thanks</p>
",https://stackoverflow.com/questions/46146095/rxjavahooks-cannot-be-resolved-in-my-android-unit-testing,"['android', 'unit-testing', 'rx-java']",650,TRUE,1,1
Unit testing a REST API in Java and Spring,"<p>I have a simple Java Spring REST API application and i don't know how can i unit test it. I have read the documentations of JUnit and Mockito, but i couldn't figure it out.</p>

<p>Here is the post method in the StudentController class</p>

<pre><code>@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    public void insertStudent(@RequestBody Student student){
        studentService.insertStudent(student);
    }
</code></pre>

<p>And here is the insertStudent method in the StudentService class</p>

<pre><code>public void insertStudent(Student student) {
        studentDao.insertStudent(student);
    }
</code></pre>

<p>I use MySQL for database. Should i use database too for unit test? I mean i don't want any integration test. I want only unit test. I use supertest in Node.js and it takes care for all, can i do that with JUnit or Mockito too?</p>
",https://stackoverflow.com/questions/46619820/unit-testing-a-rest-api-in-java-and-spring,"['java', 'spring', 'rest', 'unit-testing', 'junit']",14745,TRUE,1,3
Unit Testing - How to test long running external processes,"<p>I have a method which calls another a method from another class which in turn executes numerous private methods within the second class. One method writes a file which is then picked up by an external process, the external process runs between 5 to 30 mins depending on what needs processed, another file is then produced which is picked up by my application which reads it and returns data into the initial method which was called.</p>

<p>I know what I described is not a ""Unit"" but the method is public, so my question is what would I need to test in this method and how could I mock the call to the method within the second class?  Or do I just let the method run normally whether it be 5 mins or 30 mins?</p>

<pre><code>class A
{
    public List&lt;DataClass&gt; MethodUnderTest()
    {
        List&lt;string&gt; requiredData;
        SecondClass B = New SecondClass();
        requiredData = B.GenerateFile();
        //B.GenerateFile() Executes a number of private methods within the SecondClass, 
        //This can be treated as a service call.  This runs between 5 and 30 mins
        return requiredData.Select(r =&gt; new DataClass{
                                     Property1 = r.Substring(0,2),
                                     Property2 = r.Substring(3,5),
                                     Property3 = r.Substring(9,10)
                                     }).ToList();
    }
}
</code></pre>
",https://stackoverflow.com/questions/45310456/unit-testing-how-to-test-long-running-external-processes,"['c#', 'unit-testing']",1487,TRUE,1,3
Spring Boot maven multimodule project - unit testing (application context),"<p>I am beginner with spring framework. I have a problem with configuring unit tests in spring boot, more precisely with loading spring context while running unit tests. I work with maven multimodule project (in team) and looking for the right solution to do this.
Part of my project structure is as follows:</p>

<ul>
<li>commons (module, packaging:jar, utils module)
<br>+--- src
<br>+--- pom.xml </li>
<li>proposal (module, packaging:pom)

<ul>
<li>proposal-api (submodule: interfaces, dto, packaging:jar)</li>
<li>proposal-mapping (submodule: entities)</li>
<li>proposal-service (submodule: services, spring data repositories, dto - entity&lt;->dto mappers, depends on proposal-api and proposal-mapping packaging:jar)
<br>+--- src
<br>&emsp;&emsp;+---main
<br>&emsp;&emsp;&emsp;&emsp;+--- java
<br>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;+---com.company.proposal.service
<br>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;+--- DeviceRepositoryService.java
<br>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;+--- 
DeviceMapper.java
<br>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;+--- 
ProposalRepositoryService.java
<br>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;+---
ProposalMapper.java
<br>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;+--- 
and much more classes...
<br>&emsp;&emsp;+--- test
<br>&emsp;&emsp;&emsp;&emsp;+--- java
<br>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;+---com.company.proposal.service
<br>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;+---
DeviceRepositoryServiceTest.java
<br>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;+---
ProposalRepositoryServiceTest.java
<br>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;+---
...
<br>+--- pom.xml</li>
<li>proposal-starter (submodule: autoconfiguration classes, packaging:jar)
<br>+--- src
<br>&emsp;&emsp;+---main
<br>&emsp;&emsp;&emsp;&emsp;+--- java
<br>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;+---com.company.proposal.configuration
<br>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;+--- ProposalAutoConfiguration.java
<br>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;+--- RemoteReportProcessorAutoConfiguration.java
<br>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;+--- other configuration classes...
<br>&emsp;&emsp;&emsp;&emsp;+---resources
<br>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;+---META-INF
<br>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;+--- spring.factories
<br>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;+---application.properties<br>
<br>+--- pom.xml</li>
</ul></li>
<li>entry-point (module, packaging: pom)

<ul>
<li>entry-point-api (submodule, packaging: jar)</li>
<li>entry-point-service (submodule, packaging: jar)</li>
<li>entry-point-starter (submodule, packaging: war deployed on wildfly)</li>
</ul></li>
<li>other-modules ...</li>
<li>pom.xml (root pom)</li>
</ul>

<hr>

<p>Example unit test written by me (DeviceRepositoryServiceTest.java):</p>

<pre><code>@RunWith(SpringRunner.class)
public class DeviceRepositoryServiceTest {

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @MockBean
    private DeviceRepository deviceRepository;

    @Autowired
    private DeviceMapper deviceMapper;

    private DeviceRepositoryService deviceRepositoryService;

    private final String imei = ""123456789123456"";
    private final String producer = ""samsung"";
    private final String model = ""s5"";

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        deviceRepositoryService = new DeviceRepositoryService(deviceRepository, deviceMapper);
    }

    @org.springframework.boot.test.context.TestConfiguration
    static class TestConfiguration {
        @Bean
        public DeviceMapper deviceMapper() {
            return new DeviceMapperImpl();
        }
    }

    @Test
    public void test_should_create_device() {
        given(deviceRepository.findByImei(imei)).willReturn(null);
        when(deviceRepository.save(any(Device.class))).thenAnswer((Answer) invocation -&gt; invocation.getArguments()[0]);
        DeviceSnapshot device = deviceRepositoryService.createOrFindDeviceByImei(imei, producer, model);
        assertThat(device.getImei()).isEqualTo(imei);
        assertThat(device.getProducer()).isEqualTo(producer);
        assertThat(device.getModel()).isEqualTo(model);
        verify(deviceRepository, times(1)).save(any(Device.class));
    }

    @Test
    public void test_should_return_device() {
        Device testDevice = createTestDevice();
        given(deviceRepository.findByImei(imei)).willReturn(testDevice);
        DeviceSnapshot actualDevice = deviceRepositoryService
                .createOrFindDeviceByImei(testDevice.getImei(), testDevice.getProducer(), testDevice.getModel());
        assertThat(actualDevice.getImei()).isEqualTo(testDevice.getImei());
        assertThat(actualDevice.getProducer()).isEqualTo(testDevice.getProducer());
        assertThat(actualDevice.getModel()).isEqualTo(testDevice.getModel());
        verify(deviceRepository, times(0)).save(any(Device.class));
        verify(deviceRepository, times(1)).findByImei(testDevice.getImei());
    }

    @Test
    public void test_should_find_device() {
        Device device = createTestDevice();
        given(deviceRepository.findOne(device.getId())).willReturn(device);
        DeviceSnapshot actualDevice = deviceRepositoryService.findDeviceById(device.getId());
        DeviceSnapshot expectedDevice = deviceMapper.toDeviceSnapshot(device);
        assertThat(actualDevice).isEqualTo(expectedDevice);
        verify(deviceRepository, times(1)).findOne(device.getId());
    }

    @Test
    public void test_should_find_device_by_pparams() {
        Device device = createTestDevice();
        Long proposalId = 1L, providerConfigId = 2L;
        given(deviceRepository.findByProposalParams(proposalId, providerConfigId)).willReturn(device);
        DeviceSnapshot actualDevice = deviceRepositoryService.findDeviceByProposalParams(proposalId, providerConfigId);
        DeviceSnapshot expectedDevice = deviceMapper.toDeviceSnapshot(device);
        assertThat(actualDevice).isEqualTo(expectedDevice);
        verify(deviceRepository, times(1)).findByProposalParams(proposalId, providerConfigId);
    }

    @Test
    public void test_should_throw_not_found_1() {
        given(deviceRepository.findOne(anyLong())).willReturn(null);
        this.thrown.expect(DeviceNotFoundException.class);
        deviceRepositoryService.findDeviceById(1L);
    }

    @Test
    public void test_should_throw_not_found_2() {
        given(deviceRepository.findByProposalParams(anyLong(), anyLong())).willReturn(null);
        this.thrown.expect(DeviceNotFoundException.class);
        deviceRepositoryService.findDeviceByProposalParams(1L, 1L);
    }

    private Device createTestDevice() {
        return Device.builder()
                .id(1L)
                .imei(imei)
                .model(model)
                .producer(producer)
                .build();
    }
}
</code></pre>

<p>As you can see I use @TestConfiguration annotation to define context, but because class <code>DeviceRepositoryService</code> is quite simple - only 2 dependencies so context definition is also simple. I also have to test class <code>ProposalRepositoryService</code> which looks as follows in short:</p>

<pre><code>@Slf4j
@Service
@AllArgsConstructor
@Transactional
public class ProposalRepositoryService implements ProposalService {

    private final ProposalRepository proposalRepository;
    private final ProposalMapper proposalMapper;
    private final ProposalRepositoryProperties repositoryProperties;
    private final ImageProposalRepository imageProposalRepository;
    private final ProviderConfigService providerConfigService;
    ...
}
</code></pre>

<p>In above class is more dependencies and the thing is I don't want to write bunch of configuration code for every test (TestConfiguration annotation). Eg. If I add some dependency to some service I would have to change half of my unit tests classes, also a lot of code repeats itself. I have also example when unit test code is getting ugly because of configuration definition:</p>

<pre><code>@TestPropertySource(""classpath:application-test.properties"")
public class RemoteReportProcessorRepositoryServiceTest {

    @Autowired
    private RemoteReportProcessorRepositoryService remoteReportProcessorRepositoryService;

    @TestConfiguration //here, I don't want to write bunch of configuration code for every test
    static class TestConfig {

        @Bean
        @Autowired
        public RemoteReportProcessorRepositoryService remoteReportProcessorRepositoryService(RemoteReportMailService remoteReportMailService,
                                                                                             FtpsService ftpsService,
                                                                                             RemoteDailyReportProperties remoteDailyReportProperties,
                                                                                             RemoteMonthlyReportProperties remoteMonthlyReportProperties,
                                                                                             DeviceRepository deviceRepository,
                                                                                             ProposalRepository proposalRepository) {
            return new RemoteReportProcessorRepositoryService(ftpsService, remoteReportMailService, remoteDailyReportProperties, remoteMonthlyReportProperties, deviceRepository, proposalRepository);
        }

        @Bean
        @Autowired
        public FtpsManagerService ftpsManagerService(FTPSClient ftpsClient, MailService mailService, FtpsProperties ftpsProperties) {
            return new FtpsManagerService(ftpsClient, ftpsProperties, mailService);
        }

        @Bean
        public FTPSClient ftpsClient() {
            return new FTPSClient();
        }

        @Bean
        @Autowired
        public MailService mailService(MailProperties mailProperties, JavaMailSender javaMailSender, PgpProperties pgpProperties) {
            return new MailManagerService(mailProperties, javaMailSender, pgpProperties);
        }

        @Bean
        public JavaMailSender javaMailSender() {
            return new JavaMailSenderImpl();
        }

        @Bean
        @Autowired
        public RemoteReportMailService remoteReportMailService(RemoteReportMailProperties remoteReportMailProperties,
                                                               JavaMailSender javaMailSender,
                                                               Session session,
                                                               PgpProperties pgpProperties) {
            return new RemoteReportMailManagerService(remoteReportMailProperties, javaMailSender, session, pgpProperties);
        }

        @Bean
        @Autowired
        public Session getJavaMailReceiver(RemoteReportMailProperties remoteReportMailProperties) {
            Properties properties = new Properties();
            properties.put(""mail.imap.host"", remoteReportMailProperties.getImapHost());
            properties.put(""mail.imap.port"", remoteReportMailProperties.getImapPort());
            properties.setProperty(""mail.imap.socketFactory.class"", ""javax.net.ssl.SSLSocketFactory"");
            properties.setProperty(""mail.imap.socketFactory.fallback"", ""false"");
            properties.setProperty(""mail.imap.socketFactory.port"", remoteReportMailProperties.getImapPort().toString());
            properties.put(""mail.imap.debug"", ""true"");
            properties.put(""mail.imap.ssl.trust"", ""*"");
            return Session.getDefaultInstance(properties);
        }
    }
...
}
</code></pre>

<p>So, my question is how to configure spring context for unit testing in spring boot maven multimodule project the right way, without writing bunch of configuration code?
I also will be grateful for the links to the articles when is describe in detail how to deal with maven multimodule projects.</p>
",https://stackoverflow.com/questions/47677016/spring-boot-maven-multimodule-project-unit-testing-application-context,"['java', 'maven', 'unit-testing', 'spring-boot', 'applicationcontext']",7396,TRUE,1,1
Unit Testing JDBC when the app accesses different environments,"<p>I am needing help unit testing my utility. It is to be used as an internal utility that performs CRUD operations for two different apps that use SQL Databases. The utility is able to switch between any environment for the applications (DEV, INT, PERF, STAGE, or PROD) and perform operations against each. This is not a typical application where you specify the one environment at run time, the utility needs to access all environments while running. </p>

<p>So in order for the unit tests to have good coverage they need to test things on each environment (Some environments have different behavior). </p>

<p>Normally if I was testing JDBC stuff I would create a local copy of my Dev database and run my tests against that. But since there are two applications each with a DEV, INT, PERF, STAGE, and PROD environment I would need to create 10 local databases. This option seems like it could become pretty messy, and my fellow developers would probably not be too happy about having to do that much database setup just to get the tests to run. </p>

<p>Running the unit tests against the live versions of the database is absolutely not an option as any dummy data has the potential to crash multiple systems. </p>

<p>I was looking into several different mocking frameworks but was having trouble finding something that would play nicely with JDBC or not require an excessive amount of setup. </p>

<p>So my question is: are there any good frameworks for accomplishing this, or has anyone found a solution for a similar situation? </p>
",https://stackoverflow.com/questions/42495683/unit-testing-jdbc-when-the-app-accesses-different-environments,"['java', 'unit-testing', 'jdbc', 'junit']",87,FALSE,1,1
Unit Testing - Should all library dependencies be wrapped/mocked,"<p>I am writing a class that will read/write Json files (C#). </p>

<p>I am already mocking the file system for unit testing, and I am now wondering if I should also wrap and mock the the serializer object that is being passed into the class on creation.</p>

<p>I understand that the file system has to be mocked, as otherwise I would have to create files for tests and this would make them integration tests. </p>

<p>Should I also be wrapping the serializer in an interface and mocking it? If so, should I also be wrapping/mocking every dependency in other classes that I write? If I am using many methods from an external class wrapping them in interfaces seems like a big time sink.</p>

<p>Edit:</p>

<pre><code>public class Sources
{
    private readonly IDirectory _directory;
    private readonly IFile _file;

    public Sources(IDirectory directory, IFile file)
    {
        _directory = directory;
        _file = file;
    }

    public LibrarySource GetSource(string filePath)
    {
        using (var streamReader = _file.OpenText(filePath))
        using (var jsonTextReader = new JsonTextReader(streamReader.StreamReaderInstance))
        {
            JsonSerializer serializer = new JsonSerializer();
            var sourceDto = serializer.Deserialize&lt;LibrarySourceDto&gt;(jsonTextReader);
            return SourceMapper.Map(sourceDto);
        }
    }
}
</code></pre>

<p>In this code, I am creating the JsonSerializer object within the class. This is a dependency, but I am not sure if it should be wrapped/mocked and injected in the class constructor or just left as is. If I wrap it in and interface and find that I need to use more methods from the class, editing the interface itself could become time consuming.</p>
",https://stackoverflow.com/questions/45880456/unit-testing-should-all-library-dependencies-be-wrapped-mocked,"['c#', 'unit-testing', 'mocking']",441,TRUE,1,1
Unit Testing xUnit Asserting 2 Collections with Moq Interface,"<p>Good day everyone,</p>

<p>I'm new in xunit and even in unit testing. I have a code here and I'm trying to assert two collection of list. But I have no idea how to assert and pass this test. Here's my code</p>

<pre><code>    [Theory]
    [InlineData(1)]
    public void GetAllStudents_Exempt1(int number)
    {
        // arrange
        var studentRepo = new Mock&lt;IStudentRepository&gt;();
        var listOfStudents = new List&lt;Student&gt; { new Student { StudentId = 1, Firstname = ""Firstname1"", Lastname = ""Firstname1"" },
        new Student{StudentId=2, Firstname=""Firstname2"",Lastname=""Lastname2""} };

        var getAllStudentDetailsExempt1 = studentRepo.Setup(s =&gt; s.GetStudents()).Returns(listOfStudents.Where(x =&gt; x.StudentId != number));

        var studentService = new StudentService(studentRepo.Object);

        // act
        var getStudentsDetails = studentService.ListOfStudentsExempt1(1);

        // assert
        // I don't have any idea how to assert
    }
</code></pre>
",https://stackoverflow.com/questions/47308096/unit-testing-xunit-asserting-2-collections-with-moq-interface,"['c#', 'unit-testing', 'tdd', 'xunit']",185,TRUE,1,1
Java: Unit Testing a method that returns an object,"<p>I am unsure how to unit test a method that takes in parameters as a string and returns an object based on that parameter. I cannot provide the method as the instructions I received was to use black box testing. (Method has bot been provided.)</p>
",https://stackoverflow.com/questions/43796004/java-unit-testing-a-method-that-returns-an-object,"['java', 'eclipse', 'unit-testing', 'oop', 'junit']",464,TRUE,-2,1
Integration Testing Java application with C++ unit testing framework,"<p>I have a Client/Server application written in Java (client) and C++ (server).</p>

<p>I was wondering if there was a way of using Gtest (or any other testing framework, not necessarily in C++, as long as it's not a Java framework) as a base framework to perform tests on the Java side.</p>

<p>So basically, what I want to achieve is in the following <strong>pseudo-code</strong>:</p>

<pre><code>// inside MyClass.java

public class MyClass{
    public int myMethod(){
        return 42;
    }
}

//-------------------\\
// inside MyTest.cpp \\

TEST_F(MyJavaClassTest, meaning_of_life)
{
    ASSERT_EQUALS(MyClass.myMethod(), 42);
}

//--------\\
// Output \\

[ RUN      ] MyJavaClassTest.meaning_of_life
[       OK ] MyJavaClassTest.meaning_of_life (0 ms)
</code></pre>
",https://stackoverflow.com/questions/44778646/integration-testing-java-application-with-c-unit-testing-framework,"['java', 'c++', 'unit-testing']",217,TRUE,0,1
j-unit testing Immutable Binary Search Tree add methods,"<p>I have been attempting to build an immutable binary search tree data structure. Now that I have gotten so far in the development I am attempting to test the methods i have created. So far it is going well.</p>

<p>My add method as it stands:</p>

<pre><code>@Override
public Set&lt;T&gt; add(T t) {
    if (t.compareTo(x) == 0) {
        return new Add&lt;T&gt;(x, left, right);
    } else {
        if (t.compareTo(x) &lt; 0) {
            return new Add&lt;T&gt;(x, left.add(t), right);
        } else {
            return new Add&lt;T&gt;(x, left, right.add(t));
        }
    }
}
</code></pre>

<p>The toString which I think is causing the issue:</p>

<pre><code>@Override
public String toString(){
    return """";
}
</code></pre>

<p>and the unit test:</p>

<pre><code>@Test
public void SetAddElements(){
    activeSet = newSet.add(1);
    assertEquals(""The element(s) were not added!"", 1 , activeSet.add(1));
}
</code></pre>

<p>However, my .add() method appears to fail my unit test. From what I have deduced the toString method of my Empty class returns white space which means instead of the result of my unit test returning (expected: &lt;1>, ) it returns (expected: &lt;1>, actual: &lt;1 >). A minor difference but enough for the test to fail. </p>

<p><a href=""https://i.stack.imgur.com/sa2vL.png"" rel=""nofollow noreferrer"">junit test results and error report</a></p>

<p>I have attempted to remove the toString method but obviously this just returns the default toString and attemoted to research using api and such but came up with nothing. I am struggling to phrase the question in an accurate representation of the problem. Any help would be greatly appreciated.</p>
",https://stackoverflow.com/questions/42610799/j-unit-testing-immutable-binary-search-tree-add-methods,"['java', 'unit-testing', 'junit', 'tostring']",327,FALSE,0,1
Python Unit Testing using Doctest not working as expected,"<p>I have created a python module to generate weather data(Latitude, Longitude, Elevation and other details) by taking particular location as input.</p>

<p>Updated it as per standards and ""pycodestyle"" package for checking PEP8 standards does not throw any error or warnings.</p>

<p>My Code is given below :</p>

<pre><code>def fetch_location_info(input_list, err_file):

    # URL which gives us Latitude, Longitude values
    LatLong_URL = (
     'http://maps.googleapis.com/maps/api/geocode/json?sensor=false&amp;address='
     )

    # URL which gives us Elevation values
    Elevation_URL = (
     'https://maps.googleapis.com/maps/api/elevation/json?locations='
     )

    # Initializing Error Logs with relevant title for writing error records
    err_line_header = ""Logging Location Data Errors""
    print(err_line_header, file=err_file)

    # Insert a new line in the error file after the Error Header
    print(""\n"", file=err_file)

    # Fetch and Extract Location details from google maps
    input_info = []

    for location in input_list:
        temp_info = {'Location': location}
        latlong_response = requests.get(LatLong_URL + location).json()

        if latlong_response.get('results'):
            for latlong_results in latlong_response.get('results'):
                latlong = (
                    latlong_results
                    .get('geometry', '0')
                    .get('location', '0')
                    )

                temp_info['Latitude'] = latlong.get('lat', '0')
                temp_info['Longitude'] = latlong.get('lng', '0')

                elevation_response = requests.get(
                    Elevation_URL
                    + str(temp_info['Latitude'])
                    + ','
                    + str(temp_info['Longitude'])
                    ).json()

                if elevation_response.get('results'):
                    for elevation_results in elevation_response.get('results'):
                        temp_info['Elevation'] = (
                            elevation_results.get('elevation', '0'))

                        input_info.append(temp_info)
                        break
                else:
                    print(""Elevation_URL is not fetching values for {}""
                          .format(location),
                          file=err_file
                          )
                break
        else:
            print(""LatLong_URL is not fetching values for {}""
                  .format(location),
                  file=err_file
                  )

    print(""\n"", file=err_file)
    return input_info
</code></pre>

<p>Now as a next step, I am trying to do Unit Testing using doctest. <em>I chose to keep the test cases in a separate file. So I created the following <strong>.txt file</em></strong> and kept in the same directory as the code.</p>

<pre><code>This is a doctest based regression suite for Test_Weather.py
Each '&gt;&gt;' line is run as if in a python shell, and counts as a test.
The next line, if not '&gt;&gt;' is the expected output of the previous line.
If anything doesn't match exactly (including trailing spaces), the test fails.

&gt;&gt;&gt; from Test_Weather import fetch_location_info
&gt;&gt;&gt; fetch_location_info([""Sydney,Australia""], open('data/error_log.txt', 'w'))
print(input_info)
</code></pre>

<p>As seen above, the expected condition should return the contents of the list / dataframe / variable that is created within the function being tested. For a try I just tried to print the contents of the list but my unit test output throws error like below since the expected value and got value is not matching :</p>

<blockquote>
  <blockquote>
    <p>PS C:\Users\JKC> python -m doctest testcases.txt
    **********************************************************************  File ""testcases.txt"", line 7, in testcases.txt Failed example:
        fetch_location_info([""Sydney,Australia""], open('data/error_log.txt', 'w')) </p>
  </blockquote>
  
  <p>Expected:</p>
  
  <blockquote>
<pre><code>print(input_info) 
</code></pre>
  </blockquote>
  
  <p>Got:</p>
  
  <blockquote>
<pre><code>[{'Location': 'Sydney,Australia', 'Latitude': -33.8688197, 'Longitude': 151. 2092955, 'Elevation': 24.5399284362793}]
</code></pre>
  </blockquote>
</blockquote>

<p>So here as you can see that the Test Case worked fine but since I am not able to print the contents of the list, it is failing the test case. </p>

<p><strong>My question is How can I display the contents of list in the expected section of the unit test case ?</strong> </p>

<p>If I am not wrong, do I need to literally mention the output value in the expected section of the unit test case ?</p>

<p>Any inputs will be helpful</p>
",https://stackoverflow.com/questions/47292288/python-unit-testing-using-doctest-not-working-as-expected,"['python', 'python-3.x', 'unit-testing', 'doctest']",455,TRUE,-1,1
Angular 4 unit testing OKTA SignIn not defined error,"<p>I am trying to write unit tests in Angular 4. In our application OKTA Sign In is being used. How to mock OKTA Sign in? I am getting an error OktaSignIn not defined</p>
",https://stackoverflow.com/questions/47195079/angular-4-unit-testing-okta-signin-not-defined-error,"['angular', 'unit-testing', 'karma-runner', 'okta']",498,TRUE,0,1
How to do unit testing of Visitors in Jsqlparser?,"<p>I have implemented the Visitors of JSqlparser to parse SQL queries. The code is working absolutely fine. I am not sure how to do unit testing for those visitors. For example I have the following sql statement:</p>

<pre><code>Select a.a1, a.a2 from foo as a
</code></pre>

<p>To parse it I have implemented StatementVisitor interface and my code goes like this: </p>

<pre><code>public class StmntVisitorImpl implements StatementVisitor {


@Override
public void visit(Select select) {
    LOG.debug(""Begin Select visit : ""+select.toString());
    SelectVisitor selectVisitor = new SelectVisitorImpl();      
    select.getSelectBody().accept(selectVisitor);
    if(select.getWithItemsList()!=null &amp;&amp; !select.getWithItemsList().isEmpty()){
        select.getWithItemsList().stream()
        .forEach(wth -&gt; wth.accept(selectVisitor));             
    }               
}
@Override
public void visit(Delete delete) {}
@Override
public void visit(Update update) {}
@Override
public void visit(Insert insert) {}
@Override
public void visit(Replace replace) {}
@Override
public void visit(Drop drop) {}
}
</code></pre>

<p>Then I am calling it in another class as follows:</p>

<pre><code>String sql = ""Select a.a1, a.a2 from foo as a"";
CCJSqlParserManager parserManager = new CCJSqlParserManager();
StatementVisitor statementVisitor = new StmntVisitorImpl ();
Statement sqlStatement =  parserManager.parse(new StringReader(sql));
sqlStatement.accept(statementVisitor);
</code></pre>

<p>I want to write unit test cases for my StmntVisitorImpl, SelectVisitorImpl and other classes implementing the Visitor interfaces given by JSqlparser. How should I do it?</p>
",https://stackoverflow.com/questions/41887920/how-to-do-unit-testing-of-visitors-in-jsqlparser,"['java', 'unit-testing', 'visitor-pattern', 'jsqlparser']",748,TRUE,0,1
Angular 4 unit testing mock backend creates undefined answer,"<p>I am trying to test this service with Angular tests</p>

<pre><code>export class LoginService implements OnInit {
  private authUrl = 'http://localhost:8080/login';
  private headers = new Headers({'Content-Type': 'application/json'});
  constructor(private http: Http) {}

  ngOnInit() {
  }

  login(username: string, password: string) {

      let _sub = this.http.post(this.authUrl, JSON.stringify({username: username, password: password}))
      .map((response: Response) =&gt; {
        let token = response.json()['Token'];
        let role = response.json()['Role'];
        if (token) {
          localStorage.setItem('currentUser', JSON.stringify({username: username, token: token, role: role}));
          return true;
        } else {
          return false;
        }
      }).catch((error: any) =&gt; Observable.throw(error.json().error || 'Server error'));
      return _sub;
  }
  getToken(): String {
    let currentUser = JSON.parse(localStorage.getItem('currentUser'));
    let token = currentUser &amp;&amp; currentUser.token;
    return token ? token : '';
  }
  logout(): void {
    localStorage.removeItem('currentUser');
  }
  isLoggedIn(): boolean {
    let token: String = this.getToken();
    return token &amp;&amp; token.length &gt; 0;
  }
</code></pre>

<p>i have created a mockbackend response that should be a json but the response is undefined</p>

<pre><code>describe('LoginService', () =&gt; {

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [HttpModule],
      providers: [
      MockBackend,
      BaseRequestOptions,
        { provide: XHRBackend, useClass: MockBackend },
        LoginService,
      ]
    });
  });


  it('should set the token,user and role', inject([LoginService,XHRBackend], (service,mockBackend)=&gt;{

        const mockResponse= {
            role:'mockRole',
            user:'mockUser',
            token:'mockToken'
        };
        mockBackend.connections.subscribe((connection)=&gt;{
                 connection.mockRespond(new Response(new ResponseOptions({
                       status:200,
                       body:JSON.stringify(mockResponse)
                 })));
        }); 
        console.log(mockBackend);
        service.login('mockuser','mockpassword').subscribe((response)=&gt;
          {console.log(response.json);}
        );
        expect(service.isLoggedIn()).toEqual(true);
  }));
</code></pre>

<p>As far as i can tell from logs the mockbackend is correctly injected in the login service and the response gets registered</p>
",https://stackoverflow.com/questions/45210014/angular-4-unit-testing-mock-backend-creates-undefined-answer,"['angular', 'unit-testing']",485,TRUE,0,1
Microsoft Fakes unit testing with Windows Forms application(EXE),"<p>Microsoft Fakes library can replace calls to assemblies which we can not modify, <a href=""https://msdn.microsoft.com/en-us/library/hh549175(v=vs.110).aspx"" rel=""nofollow noreferrer"">please refer docs</a>. 
I want to unit test my Windows Forms application. </p>

<p><em>Can we use Microsoft Fakes library to stub/shim calls from my EXE?</em></p>
",https://stackoverflow.com/questions/42092022/microsoft-fakes-unit-testing-with-windows-forms-applicationexe,"['c#', '.net', 'winforms', 'microsoft-fakes']",215,FALSE,0,0
Mocking file system for unit testing file watcher library,"<p>I am currently unit testing a wrapper I've written around <a href=""https://www.npmjs.com/package/chokidar"" rel=""nofollow noreferrer"" title=""chokidar"">Chokidar</a>, which is a file system watcher, which is itself a wrapper around native fs.watch functionality. I write my tests with mocha/chai. </p>

<p>I know there is this wonderful library <a href=""https://www.npmjs.com/package/mock-fs"" rel=""nofollow noreferrer"" title=""mock-fs"">mock-fs</a>, the caveat however is that it says at the bottom</p>

<blockquote>
  <p>The following fs functions are not currently mocked (if your tests use these, they will work against the real file system): fs.FSWatcher, fs.unwatchFile, fs.watch, and fs.watchFile. Pull requests welcome.</p>
</blockquote>

<p>So it will not help me unit testing my watcher. </p>

<p>Currently I have it set up with true read/writes to the fs, without mocking, but it's tedious and timing dependent (which makes it hardware dependent). </p>

<p>Would anybody be able to advise me on perhaps better approaches?</p>
",https://stackoverflow.com/questions/42933991/mocking-file-system-for-unit-testing-file-watcher-library,"['node.js', 'unit-testing']",1213,TRUE,0,1
Unit testing AngularJs with Jasmine: then - catch testing issue,"<p>I have a following piece of code (simplified):</p>

<pre><code>angular
.module('myApp')
.controller('MyController', MyController);

function MyController(wordService) {

    getWord();

    function getWord() {

        return wordService.getNextWord()
           .then(doSomethingWithWord)
           .catch(doSomethingFailure);

        function doSomethingWithWord(response) {
            //    ... something
        }

        function doSomethingFailure() {
            //    ... failing
        }
    }
}
</code></pre>

<p>And I have to test it.
I'm struggling with this over a day now and I can't get it working :(</p>

<p>How to test this code?</p>
",https://stackoverflow.com/questions/44543815/unit-testing-angularjs-with-jasmine-then-catch-testing-issue,"['javascript', 'angularjs', 'unit-testing', 'jasmine', 'karma-jasmine']",228,FALSE,0,1
Unit testing react-redux connected components with Mocha/Chai,"<p>I'm trying to test a connected component, which I've exported both as a connected component and as a plain one as per the suggestion <a href=""https://stackoverflow.com/a/35578985/3019008"">here</a> by Ashwin Van Dijk. </p>

<p>All my tests for dumb components work fine, and the app runs fine (the connected component works).</p>

<p>The component is pretty straightforward-just displaying a list retrieved from state:</p>

<pre><code>import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../actions';
import Plot from './plot';
import Spinner from 'react-spinkit';

export class Dashboard extends Component {
    componentWillMount() {
        this.props.fetchMessage();
        this.props.fetchPlots();
    }

    render() {
        const plots = this.props.plots;
        if (plots === undefined) {
            return (
                &lt;div className=""dashboard loading""&gt;
                    &lt;Spinner name=""three-bounce"" /&gt;
                &lt;/div&gt;
            );
        } 

        return (
            &lt;div className='container-fluid dashboard'&gt;
               **(all my stuff lives here)**
            &lt;/div&gt;
        );
    }
}

function mapStateToProps(state) {
    return {
        message: state.auth.message,
        plots: state.auth.plots
    }
}

export default connect(mapStateToProps, actions)(Dashboard);
</code></pre>

<p>The test doesn't even run-it gives me a funny looking error about css:</p>

<pre><code>C:\Users\BaruchKogan\Documents\Visual Studio 2017\Projects\TrellisReact\node_modules\loaders.css\loaders.css:14
@-webkit-keyframes scale {
^
SyntaxError: Invalid or unexpected token
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:542:28)
    at Module._extensions..js (module.js:579:10)
    at Object.require.extensions.(anonymous function) [as .js] (C:\Users\BaruchKogan\Documents\Visual Studio 2017\Projects\TrellisReact\node_modules\babel-register\lib\node.js:152:7)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.&lt;anonymous&gt; (C:\Users\BaruchKogan\Documents\Visual Studio 2017\Projects\TrellisReact\node_modules\react-spinkit\dist\index.js:40:3)
    at Module._compile (module.js:570:32)
    at Module._extensions..js (module.js:579:10)
    at Object.require.extensions.(anonymous function) [as .js] (C:\Users\BaruchKogan\Documents\Visual Studio 2017\Projects\TrellisReact\node_modules\babel-register\lib\node.js:152:7)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.&lt;anonymous&gt; (C:/Users/BaruchKogan/Documents/Visual Studio 2017/Projects/TrellisReact/src/components/dashboard.js:5:1)
    at Module._compile (module.js:570:32)
    at loader (C:\Users\BaruchKogan\Documents\Visual Studio 2017\Projects\TrellisReact\node_modules\babel-register\lib\node.js:144:5)
    at Object.require.extensions.(anonymous function) [as .js] (C:\Users\BaruchKogan\Documents\Visual Studio 2017\Projects\TrellisReact\node_modules\babel-register\lib\node.js:154:7)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.&lt;anonymous&gt; (C:/Users/BaruchKogan/Documents/Visual Studio 2017/Projects/TrellisReact/test/components/dashboard_test.js:2:1)
    at Module._compile (module.js:570:32)
    at loader (C:\Users\BaruchKogan\Documents\Visual Studio 2017\Projects\TrellisReact\node_modules\babel-register\lib\node.js:144:5)
    at Object.require.extensions.(anonymous function) [as .js] (C:\Users\BaruchKogan\Documents\Visual Studio 2017\Projects\TrellisReact\node_modules\babel-register\lib\node.js:154:7)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at C:\Users\BaruchKogan\Documents\Visual Studio 2017\Projects\TrellisReact\node_modules\mocha\lib\mocha.js:220:27
    at Array.forEach (native)
    at Mocha.loadFiles (C:\Users\BaruchKogan\Documents\Visual Studio 2017\Projects\TrellisReact\node_modules\mocha\lib\mocha.js:217:14)
    at Mocha.run (C:\Users\BaruchKogan\Documents\Visual Studio 2017\Projects\TrellisReact\node_modules\mocha\lib\mocha.js:469:10)
    at loadAndRun (C:\Users\BaruchKogan\Documents\Visual Studio 2017\Projects\TrellisReact\node_modules\mocha\bin\_mocha:360:22)
    at rerun (C:\Users\BaruchKogan\Documents\Visual Studio 2017\Projects\TrellisReact\node_modules\mocha\bin\_mocha:387:5)
    at C:\Users\BaruchKogan\Documents\Visual Studio 2017\Projects\TrellisReact\node_modules\mocha\bin\_mocha:395:7
    at StatWatcher.&lt;anonymous&gt; (C:\Users\BaruchKogan\Documents\Visual Studio 2017\Projects\TrellisReact\node_modules\mocha\lib\utils.js:174:9)
    at emitTwo (events.js:106:13)
    at StatWatcher.emit (events.js:191:7)
    at StatWatcher._handle.onchange (fs.js:1501:10)
</code></pre>

<p>Any thoughts?</p>
",https://stackoverflow.com/questions/46512193/unit-testing-react-redux-connected-components-with-mocha-chai,"['reactjs', 'mocha.js', 'react-redux', 'chai']",251,TRUE,0,1
iOS XCTest Unit testing - setting up a Principal Class,"<p>I am trying to have a class that is only instanciated once in all of my unit tests.</p>

<p>Note: Stackoverflow code markdown does not work, for some reason?</p>

<p>The question:</p>

<ol>
<li><p>I have created a class:</p>

<pre><code>import XCTest
class PrincipalTest: NSObject {
  override init() {

  } 
}
</code></pre></li>
<li><p>In <code>Info.plist</code> I have set: ""Principal class"": ProjectName.PrincipalClas</p></li>
</ol>

<p>How do you do it?</p>
",https://stackoverflow.com/questions/43065996/ios-xctest-unit-testing-setting-up-a-principal-class,"['ios', 'swift']",795,FALSE,0,1
I can&#39;t get Live Unit Testing to see .runsettings,"<p>I'm trying out ""Live unit Testing"" in VS2017, and ran into a problem. It looks like Live unit Testing doesn't pick up the settings in my .runsettings file.</p>

<p>When I'm in my code, my tests fail. Red cross next to the code, and red test in Test Explorer. But when I don't touch the code, and run the same tests from the Test Explorer, the tests go green (but still red cross next to code).</p>

<p>Am I missing something, is it not possible with .runsettings file, or is this a bug? </p>

<p>Additional info:</p>

<ul>
<li>I'm testing a C# class library (project and test project created with vs2015)</li>
<li>I removed Microsoft.VisualStudio.QualityTools.UnitTestFramework from the test project</li>
<li>I added MSTest.TestFramework 1.1.11 </li>
<li>and MSTest.TestAdapter 1.1.12 to the test project</li>
<li>Using .NET Framework 4.6.1</li>
</ul>
",https://stackoverflow.com/questions/42667546/i-cant-get-live-unit-testing-to-see-runsettings,"['c#', 'unit-testing', 'visual-studio-2017']",440,FALSE,0,1
Unit-Testing: Where to start writing my First Tests,"<p>My question is, where is an easy place in the codebase to begin writing unit testing for so I can get my feet wet and develop some basic skills?</p>

<p>The details: 
I am a recently hired junior dev and I have been tasked with adding unit testing to my company's projects. I've installed NUnit, watched tutorials, done the basic samples, and am reading through the official docs. I can see the value of automated unit testing, plus think it's a good way to get familiar with my company's source code.</p>

<p>We have 2 online platforms, a ""brochure"" site to attract clients and our ""database"" site. both written in Written in Javascript, jQuery, C#, .NET, connecting to MSSQL via Entity framework. 
The ""brochure"" site doesn't have to much user functionality built in. They click links to get to pages of information. And there is a contact request form where they submit basic info so we can contact them. Very simple website. 
The ""database"" is more complex. Registered users can grab any number of combination of data from different databases, there are access rights involved with various levels of registration. Lots of filtering based on users selections. </p>

<p>There aren't currently any tests written for either but they are both in production. Where would be a good place to begin?
I think I should begin on the simple ""brochure"" site to learn on, but I do see the testing as being more important in the long-term for the ""database"" site. </p>

<p>Should I try and test controllers, ajax get/post functions, views?
I think what I'm hoping for is someone to say ""these 1,2,3 are simple tests to write, start there"" If I'm wrong on this thinking please let me know. Thank you.     </p>
",https://stackoverflow.com/questions/43899455/unit-testing-where-to-start-writing-my-first-tests,"['c#', 'jquery', '.net', 'unit-testing', 'nunit']",182,TRUE,0,2
"Unit testing react component on change with Jest, Enzyme","<p>I have the following abbreviated react component</p>



<pre class=""lang-jsx prettyprint-override""><code>   render() {
        return (
            &lt;div className={styles.srchBoxContaner}&gt;
                &lt;input
                    className={styles.incSrchTextBox}
                    type=""text"" name=""search"" placeholder=""Search..""
                    onChange={this.onChange}
                /&gt;
            &lt;/div&gt;
        );
    }
</code></pre>

<p>Now I want to unit test this, specifically I want to simulate an input and make sure onChange is called</p>

<p>How do I do this using Enzyme, and Jest.  So far this is what I have come up with</p>

<pre class=""lang-jsx prettyprint-override""><code>it('calls \'onPerformIncrementalSearch\' when the user types in something', () =&gt; {
    const incrementalSearchWrapper = mount(&lt;IncrementalSearch /&gt;);

    const onChangeSpy = sinon.spy(IncrementalSearch.prototype, 'onChange');

    //find the input element
    const searchInput = incrementalSearchWrapper.find('#search');
    searchInput.simulate('change', { target: { value: 'new search value' } });
    expect(IncrementalSearch.prototype.onChange.called).toEqual(true);
    onChangeSpy.restore();
});
</code></pre>

<p>However this does not seem to work.</p>
",https://stackoverflow.com/questions/45498927/unit-testing-react-component-on-change-with-jest-enzyme,"['reactjs', 'unit-testing', 'jestjs', 'jsx', 'enzyme']",916,TRUE,0,1
"Unit testing $q promise within Angular service - Karma, Jasmine","<p>I am trying to unit test an Angular service with Karma and Jasmine. I'm making I've seen a number of tutorials on how to unit test a service call from a controller, but I wish to unit test within the service itself.  <code>UsersService.findById()</code> makes an async call to find an ID within an ID, but I can't figure out how to write a passing test. I'm close, but I need a little help. Here is the function within UsersService</p>

<p><strong>users.service.js</strong></p>

<pre><code>        Users.findById = function(id){
            var deferred = $q.defer();

            deferred.resolve(userList.find(function(user){
                return user.id == id;
            }));

            return deferred.promise;
        };
</code></pre>

<p>Here is the spec:</p>

<p><strong>users.service.spec.js</strong></p>

<pre><code>describe(""Users Factory"", function(){
    var UsersService, $q, $rootScope, $provide, deferred, mockedDeferred;

    var userList = [
        { id: 1, name: ""Richard Hendricks"", email: ""richard@piedpiper.com"", phone: 4085550011, pokemon: { isPresent: true, name: ""eevee""}, icon: { isPresent: false, name: null} },
        { id: 2, name: ""Erlich Bachman"", email: ""erlich@aviato.com"", phone: 4155552233, pokemon: { isPresent: true, name: ""celebi""}, icon: { isPresent: false, name: null} },
        { id: 3, name: ""Gavin Belson"", email: ""gavin@hooli.com"", phone: 9165554455, pokemon: { isPresent: true, name: ""snorlax""}, icon: { isPresent: false, name: null} }
    ];

    var singleUser = { id: 2, name: ""Erlich Bachman"", email: ""erlich@aviato.com"", phone: 4155552233, pokemon: { isPresent: true, name: ""celebi""}, icon: { isPresent: false, name: null} };

    function mockQ(){
        deferred = $q.defer();
        spyOn(UsersService, ""findById"");
        return deferred;
    }

    beforeEach(angular.mock.module(""testing_app""));
    beforeEach(angular.mock.module(function(_$provide_){
        $provide = _$provide_;
    }));

    beforeEach(inject(function(_UsersService_, _$q_, _$rootScope_){
        UsersService = _UsersService_;
        $q = _$q_;
        $rootScope = _$rootScope_;
    }));

    describe(""Users.findById()"", function(){

        beforeEach(function(){
            mockedDeferred = mockQ();
        });

        it(""should exist"", function(){
            expect(UsersService.findById).toBeDefined();
        });

        it(""should equal singleUser"", function(){
            UsersService.findById(2);
            deferred.resolve(userList.find(function(user){
                return user.id == 2;
            }));
            expect(UsersService.findById).toHaveBeenCalled();
            expect(deferred.promise).toEqual(singleUser);
        });
    });
});
</code></pre>

<p>Here's what I have in my console:</p>

<p><a href=""https://i.stack.imgur.com/rFQ3W.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/rFQ3W.png"" alt=""Erlich Bachman, this is your mom. You are not my baby""></a></p>

<p>I'm close, but how do I get the promise to equal the <code>singleUser</code> variable?</p>
",https://stackoverflow.com/questions/42755643/unit-testing-q-promise-within-angular-service-karma-jasmine,"['javascript', 'angularjs', 'unit-testing', 'jasmine', 'karma-jasmine']",1553,TRUE,0,1
how to handle New Server func in unit testing,"<p>for me , unit testing has workload. so i use gotests to generate Boilerplate testing code case. </p>

<p>server.go</p>

<pre><code> func NewServer(cfg *Config, l net.Listener, driver Driver, db store.Store) *Server {
    s := &amp;Server{
        cfg:      cfg,
        listener: l,
        leader:   """",
        driver:   driver,
        db:       db,
    }

    s.server = &amp;http.Server{
        Handler: s.createMux(),
    }

    return s
}
</code></pre>

<p>gotests generate server_test.go:</p>

<pre><code>func TestNewServer(t *testing.T) {
    fakeCfg := &amp;Config{
        Listen:   ""hello"",
        LogLevel: ""debug"",
    }
    type args struct {
        cfg    *Config
        l      net.Listener
        leader string
        driver Driver
        db     store.Store
    }
    tests := []struct {
        name string
        args args
        want *Server
    }{
        {
            name: ""test"",
            args: args{
                cfg: fakeCfg,
            },
            want: &amp;Server{
                cfg: fakeCfg,
                server: &amp;http.Server{
                    Handler: nil,
                },
            },
        },
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            if got := NewServer(tt.args.cfg, tt.args.l, tt.args.driver, tt.args.db); !reflect.DeepEqual(got, tt.want) {
                t.Errorf(""NewServer() = %v, want %v"", got, tt.want)
            }
        })
    }
}
</code></pre>

<p>unit test result:</p>

<pre><code>$ go test -v -run TestNewServer
=== RUN   TestNewServer
=== RUN   TestNewServer/test
--- FAIL: TestNewServer (0.00s)
    --- FAIL: TestNewServer/test (0.00s)
        server_test.go:47: NewServer() = &amp;{cfg:0xc4201f5580 listener:&lt;nil&gt; leader: server:0xc4201d6840 driver:&lt;nil&gt; db:&lt;nil&gt; Mutex:{state:0 sema:0}}, want &amp;{cfg:0xc4201f5580 listener:&lt;nil&gt; leader: server:0xc4201d6790 driver:&lt;nil&gt; db:&lt;nil&gt; Mutex:{state:0 sema:0}}
FAIL
exit status 1
FAIL    github.com/Dataman-Cloud/swan/api       0.017s
</code></pre>

<p>because the initial server struct is not one step. i can't correct get server attribute in &amp;Server{} section.</p>

<p>anyone can do me a favor, give me a hint?howto write test on this situation?</p>
",https://stackoverflow.com/questions/45478213/how-to-handle-new-server-func-in-unit-testing,"['testing', 'go']",61,TRUE,0,2
Unit testing in Cake2: How to mock AppModel function?,"<p>I want to test my CategoriesController and for that I need to mock a method of the AppModel. I stick to the <a href=""https://book.cakephp.org/2.0/en/development/testing.html#using-mocks-with-testaction"" rel=""nofollow noreferrer"">Cake docs</a> but I think my case is slightly different since the Category model has no relation to the AppModel but inherits from it.</p>

<p>app/Model/AppModel.php includes:</p>

<pre><code>&lt;?php
App::uses('Model', 'Model');

class AppModel extends Model
{

    public function storeId()
    {
        return Configure::read('storeId');
    }
}
</code></pre>

<p>app/Test/Case/Controller/CategoriesControllerTest.php includes:</p>

<pre><code>&lt;?php
App::uses('Controller', 'Controller');
App::uses('AppModel', 'Model');

class CategoriesControllerTest extends ControllerTestCase
{
    public $fixtures = [...]
    public function testView() {
            $Categories = $this-&gt;generate('Categories', [
                'models' =&gt; [
                    'AppModel' =&gt; [
                        'storeId'
                    ],
                ]
            ]);
            $Categories-&gt;AppModel
                -&gt;method('storeId')
                -&gt;will($this-&gt;returnValue(17));

            $result = $this-&gt;testAction('/categories/view/1700007',
                ['return' =&gt; 'vars']
            );  
    }
}
</code></pre>

<p>This results in an error </p>

<blockquote>
  <p>Error: Call to a member function method() on null in...</p>
</blockquote>

<p>The background:
I need to mock the storeId method because during the view() call in the CategoriesController a query is manipulated by a method in the AppModel, which uses the storeId() function to determine which is the active store.</p>
",https://stackoverflow.com/questions/46059651/unit-testing-in-cake2-how-to-mock-appmodel-function,"['php', 'unit-testing', 'cakephp', 'cakephp-2.x']",155,FALSE,0,0
how to do unit testing using junit using java,"<p>How we can do PHPUnit testing in wordpress website ? Including theme and plugin everything.</p>

<p>I have setup the phpunit and included wp-load.php file to get all functions and classes access.</p>

<p>Is this correct way ? or There is any better way of doing the Unit Testing in wordpress.</p>
",https://stackoverflow.com/questions/41933124/how-to-do-unit-testing-using-junit-using-java,"['java', 'unit-testing']",36,FALSE,0,0
Symfony3 unit testing forms always valid when invalid data,"<p>I use Symfony3 and forms. I have a formType and I want to test it.
I follow this article : 
<a href=""http://symfony.com/doc/current/form/unit_testing.html"" rel=""nofollow noreferrer"">http://symfony.com/doc/current/form/unit_testing.html</a></p>

<p>My formType is the following :</p>

<pre><code>namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\GreaterThanOrEqual;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Required;

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $aOption)
    {

        $builder-&gt;add('name', TextType::class, array(
            'constraints' =&gt; array(
                new NotBlank(),
                new Length(array('min' =&gt; 3)),
            ),
        ))
            -&gt;add('age', IntegerType::class, array(
                'constraints' =&gt; array(
                    new GreaterThanOrEqual(array('value' =&gt; 18)),
                    new Required()),

            ));
    }
}
</code></pre>

<p>The name must have more than 3 chars and the age must be greater than 18.
I want to test with phpunit, with invalid data to submit. The age I submut is invalid because it is less than 18, and the name is invalid because it contains 1 char. My test class is the following : </p>

<pre><code>namespace Tests\AppBundle\Controller;

use AppBundle\Form\UserType;
use Symfony\Component\Form\Test\TypeTestCase;
use Symfony\Component\Form\Extension\Validator\ValidatorExtension;
use Symfony\Component\Form\Form;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Validator\ValidatorInterface;

class UserTypeTest extends TypeTestCase
{
    private $validator;
    protected function getExtensions()
    {
        $this-&gt;validator = $this-&gt;createMock(ValidatorInterface::class);
        // use getMock() on PHPUnit 5.3 or below
        // $this-&gt;validator = $this-&gt;getMock(ValidatorInterface::class);
        $this-&gt;validator
            -&gt;method('validate')
            -&gt;will($this-&gt;returnValue(new ConstraintViolationList()));
        $this-&gt;validator
            -&gt;method('getMetadataFor')
            -&gt;will($this-&gt;returnValue(new ClassMetadata(Form::class)));
        return array(
            new ValidatorExtension($this-&gt;validator),
        );
    }
    public function testIndex()
    {
        $formData = array(
            'name' =&gt; 'a',
            'age'  =&gt; '4'
        );
        $formBuilder = $this-&gt;factory-&gt;createBuilder(UserType::class);
        $form = $formBuilder-&gt;getForm();
        $form-&gt;submit($formData);
        $this-&gt;assertTrue($form-&gt;isSynchronized());
        $this-&gt;assertFalse($form-&gt;isValid());

    }
}
</code></pre>

<p>When I want to run the tests with invalid data to submit, I have failure :</p>

<pre><code>./vendor/bin/phpunit tests/AppBundle/Controller/UserTypeTest.php  
Failed asserting that true is false.
</code></pre>

<p>Why the form is always valid ?</p>
",https://stackoverflow.com/questions/46502638/symfony3-unit-testing-forms-always-valid-when-invalid-data,"['php', 'forms', 'symfony', 'unit-testing']",1188,TRUE,0,1
Unit testing an angular directive similar to ng-if,"<p>I have a service and a directive packaged together that remove DOM elements if certain criteria are not met.</p>

<p>The service performs a check against a string passed in and the directive simply removes the DOM element it's attached to if the check fails.</p>

<p>This works in IE11, Edge, Chrome and FireFox. However, I can't seem to replicate this in any tests.</p>

<p><a href=""https://jsbin.com/fucolavima/edit?html,js,console,output"" rel=""nofollow noreferrer"">Working code in this JSBin</a></p>

<p>Here's an example of the service and its provider</p>

<pre><code>class PermissionService {
    constructor(permissions) {
        this.permissions = permissions;
    }

    addPermissions(permissions) {
        this.permissions = this.permissions.concat(permissions);
    }

    has(permission) {
        return this.permissions.indexOf(permission) !== -1;
    }
}

class PermissionProvider {
    constructor() {
        let _permissions = [];

        this.setPermissions = (permissions) =&gt; {
            _permissions = _permissions.concat(permissions);
        };

        this.$get = () =&gt; {
            return new PermissionService(_permissions);
        }
    }
}
</code></pre>

<p>And the directive with an example of how it is setup in an angular module.</p>

<pre><code>angular.module('PermissionTest', [])
  .directive('hasPermission', ['permission', '$compile', (service, $compile) =&gt; {
    return {
      restrict: 'A',
      priority: 1,
      terminal: true,
      compile: (element, attrs) =&gt; {
        let permission = attrs.hasPermission;

        if (service.has(permission)) {
            attrs.$set('hasPermission', null);
            return (scope, element) =&gt; {
                $compile(element)(scope);
            }
        } else {
            element.remove();
        }
      }
    }
  }])
  .provider('permission', PermissionProvider)
  .config(['permissionProvider', (provider) =&gt; {
    provider.setPermissions(['yes']);
  }]);
</code></pre>

<p>Using the directive, I can now remove elements from the DOM easily</p>

<pre><code>&lt;!-- Is not removed --&gt;
&lt;div has-permission=""yes""&gt;Is not removed&lt;/div&gt;

&lt;!-- Is removed --&gt;
&lt;div has-permission=""no""&gt;Is removed&lt;/div&gt;
</code></pre>

<p>I have the following test setup that I would expect to pass, but does not. I suspect it is due to the directive recompiling itself, though I think this should occur in the <code>scope.$digest()</code>. Any help debugging this would be helpful. </p>

<pre><code>let provider;
let service;

describe('directive: has-permission', () =&gt; {
    beforeEach(module('permissionChecker', (permissionProvider) =&gt; {
        provider = permissionProvider;
        provider.setPermissions(['crm.check.r', 'crm.check.c']);
    }));

    beforeEach(inject((permission) =&gt; {
        service = permission;
    }));
});

describe('if directive is not valid', () =&gt; {
    let scope;
    let element;

    beforeEach(inject(($rootScope, $compile) =&gt; {
        scope = $rootScope.$new();

        element = `&lt;div&gt;
            &lt;div has-permission=""crm.not.r""&gt;&lt;/div&gt;
            &lt;div has-permission=""crm.check.r""&gt;&lt;/div&gt;
        &lt;/div&gt;`;

        element = $compile(element)(scope);

        scope.$digest();
    }));

    it('should remove one child element', () =&gt; {
        let test = angular.element(element).children();
        expect(test.length).toBe(1);
    });
});
</code></pre>
",https://stackoverflow.com/questions/46872535/unit-testing-an-angular-directive-similar-to-ng-if,"['javascript', 'angularjs', 'unit-testing', 'karma-jasmine']",370,TRUE,0,1
Unit testing on startAt endAt timestamp query wrong results,"<p>am trying to do some unit testing on retrieving data from firebase using angularfire.</p>

<p>Here is my function to test:</p>

<pre><code>function panelsByCompleted(firstDay, lastDay){
  var panels = firebase.database().ref().child(""panels"").orderByChild(""qa/completed"").startAt(firstDay).endAt(lastDay); 
  return $firebaseArray(panels);
}
</code></pre>

<p>This is the test:</p>

<pre><code>describe(""panelsByCompleted"", function () {

        var startedTimestamp = 1509494400;
        var completedTimestamp = 1512086340;

        var panel1 = {
          id: ""panel1"",
          area: ""PROJ1AREA1"",
          qa: {
            completed: 1510380000
          }
        };

        var panel2 = {
          id: ""panel2"",
          area: ""PROJ1AREA1"",
          qa: {
            completed: 1511164800
          }
        };
        //11/21/2017 @ 4:00pm (UTC)
        var panel3 = {
          id: ""panel3"",
          area: ""PROJ1AREA2"",
          qa: {
            completed: 1511280000
          }
        };

        beforeEach(function () {
          panelsRef.set({
            ""PROJ1AREA1PANEL1"": panel1,
            ""PROJ1AREA1PANEL2"": panel2,
            ""PROJ1AREA2PANEL1"": panel3
          });
        });

        it(""returns all panels completed in date range"", function () {
          var result = panelsService.panelsByCompleted(startedTimestamp, completedTimestamp);

          scope.$apply();
          expect(result.length).toEqual(3);
          expect(result[0]).toEqual(jasmine.objectContaining(panel1));
          expect(result[1]).toEqual(jasmine.objectContaining(panel2));
          expect(result[2]).toEqual(jasmine.objectContaining(panel3));
        });
      });
</code></pre>

<p>result.length equals 0, It should get result.length equals 3.</p>

<p>Any ideas whats wrong? </p>
",https://stackoverflow.com/questions/47470210/unit-testing-on-startat-endat-timestamp-query-wrong-results,"['javascript', 'unit-testing', 'firebase', 'jasmine']",59,FALSE,0,0
How to properly define expected results in Unit Testing?,"<p>I'm learning unit testing with Jasmine but I'm confused how I should define my expected results.</p>

<pre><code>describe(""getMovieSuggestions"", function() {

  it(""should return movie suggestions"", function() {
     parameters = parameters;

    expect(getMovieSuggestions(parameters)).toBe(expectedResult);
  });
});
</code></pre>

<p>In this case, how should I define <code>expectedResult</code>?</p>

<p>I see tutorials that would literally just do <code>expectedResult = getMovieSuggestions(parameters)</code>.</p>

<p>Wouldn't that defeat the purpose of having tests?</p>
",https://stackoverflow.com/questions/46841197/how-to-properly-define-expected-results-in-unit-testing,"['javascript', 'unit-testing', 'jasmine', 'mocha.js', 'karma-jasmine']",254,FALSE,0,1
Angular 2 Unit Testing - Cannot read property &#39;root&#39; of undefined,"<p><strong>Error Description</strong></p>

<p>Angular version: 2.3.1</p>

<p>My unit test fails to create the component - I know this issue is related to the <code>[routerLink]</code> and <code>[routerLinkActive]</code> directives because removing them from the template allows the test to create the component.</p>

<p><strong>TEMPLATE</strong></p>

<pre><code>&lt;nav class=""navbar navbar-default navbar-fixed-top"" role=""navigation""&gt;
&lt;div class=""container-fluid""&gt;
&lt;div class=""navbar-header""&gt;
  &lt;button class=""navbar-toggle"" data-toggle=""collapse"" data-target=""#iotahoe-top-navigation""&gt;
    &lt;span class=""sr-only""&gt;Toggle navigation&lt;/span&gt;
    &lt;span class=""icon-bar""&gt;&lt;/span&gt;
    &lt;span class=""icon-bar""&gt;&lt;/span&gt;
    &lt;span class=""icon-bar""&gt;&lt;/span&gt;
  &lt;/button&gt;
  &lt;a class=""navbar-brand"" [routerLink]=""['/']""&gt;IoTahoe&lt;/a&gt;
&lt;/div&gt;
&lt;div class=""collapse navbar-collapse"" id=""iotahoe-top-navigation""&gt;
  &lt;ul *ngIf=""isAuthenticated()"" class=""nav navbar-nav navbar-right""&gt;
    &lt;li [routerLinkActive]=""['active']""&gt;&lt;a [routerLink]=""['/dashboard']""&gt;Dashboard&lt;/a&gt;&lt;/li&gt;
    &lt;li [routerLinkActive]=""['active']""&gt;&lt;a [routerLink]=""['/browse']""&gt;Browse&lt;/a&gt;&lt;/li&gt;
    &lt;li [routerLinkActive]=""['active']""&gt;&lt;a [routerLink]=""['/admin']""&gt;Admin&lt;/a&gt;&lt;/li&gt;
    &lt;li [routerLinkActive]=""['active']""&gt;&lt;a (click)=""onLogout()"" style=""cursor: pointer;""&gt;Logout&lt;/a&gt;&lt;/li&gt;
  &lt;/ul&gt;
&lt;/div&gt;
</code></pre>

<p>
</p>

<p><strong>TYPESCRIPT</strong></p>

<pre><code>import { Component, OnInit } from '@angular/core';
import { AuthenticationService } from   '../../authentication/authentication.service';
import { Router } from '@angular/router';

@Component({
moduleId: module.id.toString(),
selector: 'app-top-navbar',
templateUrl: './top-navbar.component.html',
styleUrls: ['./top-navbar.component.css']
})
export class TopNavbarComponent implements OnInit {

constructor(private authenticationService: AuthenticationService, private router: Router) { }

ngOnInit() {
}

isAuthenticated() {
    return this.authenticationService.isLoggedIn;
}

onLogout() {
    this.authenticationService.logout().subscribe(() =&gt; {
        return this.router.navigate(['/login']);
    });
}

}
</code></pre>

<p><strong>TEST SPEC</strong></p>

<pre><code>/* tslint:disable:no-unused-variable */
import {async, ComponentFixture, TestBed, inject} from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import {DebugElement, CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA, Component} from '@angular/core';
import { RouterTestingModule } from '@angular/router/testing';
import { Location, CommonModule } from '@angular/common';
import { TopNavbarComponent } from './top-navbar.component';
import { AuthenticationService } from '../../authentication/authentication.service';
import { Router } from '@angular/router';
import {ReactiveFormsModule} from ""@angular/forms"";

@Component({
template: ''
})
class DummyComponent {
}


describe('TopNavbarComponent', () =&gt; {
let component: TopNavbarComponent;
let fixture: ComponentFixture&lt;TopNavbarComponent&gt;;
let authenticationService: AuthenticationService;

beforeEach(async(() =&gt; {
    const authenticationServiceStub = {
        isLoggedIn: false
    };

    const routerStub = {
        navigate: jasmine.createSpy('navigate'),
        navigateByUrl: jasmine.createSpy('navigateByUrl')
    };

    TestBed.configureTestingModule({
        declarations: [ TopNavbarComponent, DummyComponent ],
        imports:[CommonModule, ReactiveFormsModule,     RouterTestingModule.withRoutes(
            [
                { path: '/', component:DummyComponent },
                { path: '/login', component:DummyComponent },
                { path: '/dashboard', component:DummyComponent },
                { path: '/browse', component:DummyComponent },
                { path: '/admin', component:DummyComponent }
            ])],
        providers: [
            { provide: AuthenticationService, useValue: authenticationServiceStub },
            { provide: Router, useValue: routerStub }
            ]
    }).compileComponents();
}));

beforeEach(() =&gt; {
    fixture = TestBed.createComponent(TopNavbarComponent);
    component = fixture.componentInstance;
    authenticationService = TestBed.get(AuthenticationService);
    fixture.detectChanges();
});

it('should create', () =&gt; {
    expect(component).toBeTruthy();
});
});
</code></pre>

<p><strong>ERROR</strong></p>

<blockquote>
  <p>zone.js:155 Uncaught Error: Error in package:407:9:6 caused by: Cannot
  read property 'root' of undefined
      at ViewWrappedError.Error (native)
      at ViewWrappedError.ZoneAwareError (localhost:9876/base/src/test.ts:133296:33)
      at ViewWrappedError.BaseError [as constructor] (localhost:9876/base/src/test.ts:35630:16)
      at ViewWrappedError.WrappedError [as constructor] (localhost:9876/base/src/test.ts:35695:16)
      at new ViewWrappedError (localhost:9876/base/src/test.ts:68018:16)
      at DebugAppView._rethrowWithContext (localhost:9876/base/src/test.ts:108242:23)
      at DebugAppView.create (localhost:9876/base/src/test.ts:108142:18)
      at DebugAppView.View_TopNavbarComponent_Host0.createInternal (/DynamicTestModule/TopNavbarComponent/host.ngfactory.js:16:19)
      at DebugAppView.AppView.createHostView (localhost:9876/base/src/test.ts:107700:21)
      at DebugAppView.createHostView (localhost:9876/base/src/test.ts:108156:52)
      at ComponentFactory.create (localhost:9876/base/src/test.ts:49830:25)
      at initComponent (localhost:9876/base/src/test.ts:6425:53)
      at ZoneDelegate.invoke (localhost:9876/base/src/test.ts:132727:26)
      at ProxyZoneSpec.onInvoke (localhost:9876/base/src/test.ts:95802:39)
      at ZoneDelegate.invoke (localhost:9876/base/src/test.ts:132726:32)Zone.runTask @
  zone.js:155ZoneTask.invoke @ zone.js:345data.args.(anonymous function)
  @ zone.js:1376</p>
</blockquote>
",https://stackoverflow.com/questions/42039728/angular-2-unit-testing-cannot-read-property-root-of-undefined,"['unit-testing', 'angular']",10636,TRUE,6,2
Spring: unable to use property placeholders in Unit Testing,"<p>i'm developing an spring 4.0 REST application and it works fine, but when i try to make some test it fails at reading propety values from placeholders (they work fine if i run the app normally)</p>

<p>Some of the properties of the app come from files and other from database so i have configured an PropertiesPropertySource to read them from db. I was unable to config it by xml, so i did it in a @Configuration class:</p>

<pre><code>public class AppConfig {
    private static final Logger logger = LoggerFactory.getLogger(AppConfig.class);

    @Inject
    private org.springframework.core.env.Environment env;

    @Autowired  
    private DataSource dataSource;

    @PostConstruct
    public void initializeDatabasePropertySourceUsage() {
        MutablePropertySources propertySources = ((ConfigurableEnvironment) env).getPropertySources();
        try {                
            DatabaseConfiguration databaseConfiguration = new DatabaseConfiguration(dataSource, ""[TABLE]"", ""property"", ""value"");
            CommonsConfigurationFactoryBean commonsConfigurationFactoryBean = new CommonsConfigurationFactoryBean(databaseConfiguration);
            Properties dbProps = (Properties) commonsConfigurationFactoryBean.getObject();
            PropertiesPropertySource dbPropertySource = new PropertiesPropertySource(""dbPropertySource"", dbProps);           
            propertySources.addFirst(dbPropertySource);        
        } catch (Exception e) {
            logger.error(""Error during database properties setup:""+e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}
</code></pre>

<p>In the test class i load the context config with this annotation:
@ContextConfiguration(classes = {TestConfig1.class,AppConfig.class,TestConfig2.class})</p>

<p>As i'm mixing XML and java configurations i had to create the TestConfigX classes which load the XMLs with this annotation:
@ImportResource([PATH TO config xml])</p>

<ul>
<li>TestConfig1 has the DatasourceBean definition and it works fine</li>
<li>AppConfig config the PropertiesPropertySource to read the placeholders from DB</li>
<li>TestConfig2 config the rest of the app, which uses the placeholders ( @Value=${XXXX}), but is unable to read the values: Could not resolve placeholder XXXX</li>
</ul>

<p>If i omit TestConfig2 i can use the placeholders from DB in the test without problem. But obviously i´m not testing anything.</p>

<p>What i'm doing wrong?</p>
",https://stackoverflow.com/questions/44305467/spring-unable-to-use-property-placeholders-in-unit-testing,"['java', 'spring', 'junit', 'properties']",401,FALSE,0,0
Issue when unit testing a service using Thymeleaf template Engine,"<p>I got a nullPointerException when unit testing my service and i do not understand why? I m using Spring boot.
This is my simple service which provide Templating. I autowired TemplateEngine Component.</p>

<pre><code>@Service
public class TicketTemplatingService implements ITemplatingService{

    @Autowired
    private TemplateEngine templateEngine;

    /**
     * This method will return a ticket template
     */
    @Override
    public String buildHtmlTemplating(Object object, String templateName) {
        Ticket ticket= (Ticket)object;
        //Build the template
        Context context = new Context();
        context.setVariable(""id"", ticket.getId());
        context.setVariable(""date"", ticket.getDate());        
        return  templateEngine.process(templateName, context);
    }

}
</code></pre>

<p>The unit test of this class is below:</p>

<pre><code>@SpringBootTest
@RunWith(SpringRunner.class)
@ActiveProfiles(""test"")
public class TemplatingServiceTest {


    @InjectMocks
    private TicketTemplatingService ticketTemplatingService;

    @Mock
    private TemplateEngine templateEngine;

    @Before
    public void setup(){
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testHtmlTemplateReturnTheHtmlTemplate(){
        Ticket ticket= new Ticket();
        ticket.setId(1L);
        Date date=new Date();
        ticket.setDate(date);

        Context context=new Context();
        context.setVariable(""id"", 1L);
        context.setVariable(""date"", date);

        //Mock the process method of the templateEngine bean
        when(templateEngine.process(""TemplateName"", refEq(context))).thenReturn(""Html template result"");

        //Now we can test the method
        String htmlTemplate=ticketTemplatingService.buildHtmlTemplating(ticket, ""TemplateName"");
        assertThat(htmlTemplate).isEqualTo(""Html template result"");
    }
}
</code></pre>

<p>In this test class, the templateEngine variable mocked return null, and then i got nullPointerException when doing this ""when(templateEngine.process(""TemplateName"", refEq(context))).thenReturn(""Html template result"");""</p>

<p>Please can you help me? i really do not unsderstand why.</p>
",https://stackoverflow.com/questions/43656246/issue-when-unit-testing-a-service-using-thymeleaf-template-engine,"['unit-testing', 'spring-boot', 'mockito']",11790,TRUE,6,3
I need help Unit Testing JsonResults in MVC.Net site,"<p>I am getting an error trying to Unit Test a JsonResult in my MVC.Net application.</p>

<p>I see that I am retrieving data using dynamic in my test, but when I do an Assert.AreEqual I get an error.</p>

<p>What am I doing wrong?  How can I fix this?</p>

<p>I have included the code I use in my unit test as well as the error that I am getting (see images below):</p>

<p><strong>CODE USED IN UNIT TEST</strong></p>

<pre><code>   [TestMethod]
   public void getStatusesInfoTESTTest()
   {
       const int statusID = 12;
       MasterDataController controller = new MasterDataController();
       var result = controller.getStatusInfoTEST(statusID) as JsonResult;
       dynamic data = result.Data;
       Assert.AreEqual(""TESTING 123"", data.MasterDataDescription);
    }
</code></pre>

<p><strong>ERROR I GET:</strong></p>

<p><a href=""https://i.stack.imgur.com/HRQUb.png"" rel=""nofollow noreferrer"">IMAGE OF ERROR I GET</a></p>

<p><strong>ERROR MESSAGE:</strong></p>

<p><em>An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll but was not handled in user code</em> </p>

<p><strong>IMAGE OF THE DATA I GET BACK</strong>
<a href=""https://i.stack.imgur.com/SVXUP.png"" rel=""nofollow noreferrer"">IMAGE OF RETURNED DATA</a></p>

<p>Thanks for your help,
mrotor</p>
",https://stackoverflow.com/questions/43644808/i-need-help-unit-testing-jsonresults-in-mvc-net-site,"['c#', 'asp.net-mvc', 'unit-testing']",35,FALSE,0,1
Unit Testing that ModelBinder applied to MVC ActionResult parameter?,"<p>I have a controller like:</p>

<p><code>public ActionResult Index([ModelBinder(typeof(MyBinder))]int? MyId)</code></p>

<p>I'd like to create a unit test <code>via Nunit+Moq+AutoFixture</code> to ensure that the MyId parameter is decorated with MyBinder, seems like a valid unit test given that if it is removed, the code will stop working as expected.  Obviously testing of the actual Custom Model Binder is done separately.</p>

<p>I expected it would be similar to testing that a property is decorated with specific attribute, such as below, but can't find how to access parameter in this way:</p>

<pre><code>private readonly PropertyInfo _SomeProp = typeof(AddressViewModel).GetProperty(""SomeProp"");&lt;br&gt;
_SomeProp.Should().BeDecoratedWith&amp;lt;DisplayAttribute&amp;gt;();
</code></pre>
",https://stackoverflow.com/questions/42527789/unit-testing-that-modelbinder-applied-to-mvc-actionresult-parameter,"['c#', 'asp.net-mvc', 'unit-testing', 'nunit', 'moq']",221,TRUE,0,1
Mock a C function when unit testing with unity,"<p>I have a C project with 2 modules - A and B.
B has a function that calls a function from A.</p>

<pre><code>int B_func() {
  if (1 == A_func()) {return 1;}
  return 2;
 }
</code></pre>

<p>I use unity to test these modules.</p>

<pre><code>TEST(B, test_b) {
  TEST_ASSERT_EQUAL(1, B_func())
}
</code></pre>

<p>When I test module B, I want to mock A_func so it will use my implementation and change the return value. Is there a way to do this without changing the source code of module B?</p>
",https://stackoverflow.com/questions/46390942/mock-a-c-function-when-unit-testing-with-unity,"['c', 'unit-testing', 'unity-test-framework']",782,TRUE,0,1
Unit testing a PHP file with no method defined,"<p>I have a PHP file that will only connect to DB and displays the resultset in an HTML table. How do we create a unit test script for such PHP file?
Thanks a lot in advance.</p>
",https://stackoverflow.com/questions/44271423/unit-testing-a-php-file-with-no-method-defined,"['php', 'unit-testing', 'testing', 'methods']",47,FALSE,0,1
Aurelia Unit Testing error due to aurelia.setRoot(&#39;shell/shell&#39;);,"<p>I'm trying to implement unit test on login method but I'm getting <strong>""Cannot read property 'setRoot' of undefined""</strong> error.</p>

<p>Here is my Login Method:</p>

<pre><code>import { inject, Aurelia, NewInstance, computedFrom } from 'aurelia-framework';
import { Router } from 'aurelia-router';
import { Server, User } from 'backend/server';
import { ValidationRules, ValidationController, validateTrigger } from 'aurelia-validation';
import { ValidationRenderer } from 'resources/validation-renderer';
</code></pre>

<p>@inject(Aurelia, Router, Server, NewInstance.of(ValidationController), NewInstance.of(User))</p>

<pre><code>constructor(aurelia, router, server, validationController, user) {
        this.router = router;
        this.aurelia = aurelia;
        this.validationController = validationController;
        this.server = server;
        this.user = user;
    }


 activate() {
    this.validationController.validateTrigger = validateTrigger.blur;
    this.validationController.addRenderer(new ValidationRenderer());

    ValidationRules
        .ensure(u =&gt; u.email)
        .required()
        .matches(/^(([^&lt;&gt;()\[\]\\.,;:\s@""]+(\.[^&lt;&gt;()\[\]\\.,;:\s@""]+)*)|("".+""))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)
        .ensure('password')
        .required()
        .on(this.user);
}


logUserIn()
{
 let promise = new Promise((resolve, reject) =&gt; 
{

        this.loggingIn = true;
        this.messageColor = 'green';
        this.message = 'Authenticating...';
        this.loginSuccess = false;
        this.validationController.validate().then(errors =&gt; {
            if (!errors.valid) {
                this.loggingIn = false;
                return ({error: true});
            }
            return this.server.authenticate(this.user.email, this.user.password);
        }).then(result =&gt; {
            if (!result.error) {
                this.messageColor = 'green';
                this.message = 'Login Successful';
                this.loginSuccess = true;
                this.aurelia.setRoot('shell/shell');
                resolve(result);
            } else {
                this.message = '';
                resolve();
            }
        }).catch(err =&gt; {
            if(!this.loginSuccess)
            {
                this.messageColor = 'red';
                this.message = err.message;
            }
            this.loggingIn = false;
            resolve(err);
        });
    });
    return promise;
}
</code></pre>

<hr>

<p>My unit test code:
<strong>login.spec.js</strong>:   </p>

<pre><code>describe('Login Unit Test', () =&gt; {
var login = new Login();
login.validationController = new ValidationController();
login.server = new Server();
it(""shouldn't allow login"", (done) =&gt; {
console.log(login.messageColor);
  login.logUserIn().then((result) =&gt; {
    console.log(login.messageColor);
    console.log(login.message);
    expect(login.messageColor).toBe('red');
    done();
  });
});
it(""Should log in"", (done) =&gt; {   
  login.user = {email:'a@b.com', password:'abc'};
    console.log(login.user.email);    
  console.log(login.user.password); 
  login.logUserIn().then((result) =&gt; {
    console.log(login.messageColor);
    console.log(login.message);
    expect(login.messageColor).toBe('green');
    done();
    });     
});
});
</code></pre>

<hr>

<p>Here is the error that i'm getting
<em><a href=""https://i.stack.imgur.com/WtOBd.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/WtOBd.png"" alt=""emphasized text""></a></em></p>

<p>I would really appreciate any help. 
Thanks.</p>
",https://stackoverflow.com/questions/42490904/aurelia-unit-testing-error-due-to-aurelia-setrootshell-shell,"['unit-testing', 'karma-jasmine', 'aurelia']",207,FALSE,0,1
Configure database connection in unit testing project&#39;s app.config file,"<p>I want to configure the visual studio unit test project so that it connects to my sql server database.</p>

<p>I tried to extract the connection string from my project's web.config file:</p>

<pre><code>  &lt;connectionStrings&gt;
    &lt;add name=""myConnection"" connectionString=""Data Source=MyDataSource;Initial Catalog=MY_DB;User Id=USER;Password=PASSWORD;"" providerName=""System.Data.SqlClient"" /&gt;
  &lt;/connectionStrings&gt;
</code></pre>

<p>and to use it inside the unit testing project's app.config file:</p>

<pre><code>&lt;appSettings&gt;
    &lt;add key=""myConnection"" value=""Data Source=MyDataSource;Initial Catalog=MY_DB;User Id=USER;Password=PASSWORD;""/&gt;
&lt;/appSettings&gt;    
</code></pre>

<p>However the connection doesn't work, I would like to know how I can fix this.</p>
",https://stackoverflow.com/questions/44453232/configure-database-connection-in-unit-testing-projects-app-config-file,"['c#', 'asp.net', 'visual-studio', 'selenium-webdriver']",1084,FALSE,0,1
Unit testing controller action which redirects to another action,"<p>I am following TDD approach to develop my MVC website. I have a <code>PaymentController</code> which is going to have an action method <code>MakePayment</code> which I am testing using a test method as given below:</p>

<pre><code>[TestMethod]
public void MakePaymentLoad()
{
    PaymentController payController = new PaymentController();
    ViewResult payResult = payController.MakePayment() as ViewResult;
    Assert.IsNotNull(payResult);
}

[TestMethod]
public void MakePaymentResult()
{
    PaymentController payController = new PaymentController();
    Payment payment = new Payment {
        BillerId = 1,
        PayAmt = 1.0,                
        PayDt = DateTime.Now,
        ConfCode = null,
        BillAccount = ""123"",
        PayStatus = 1,
        FeeStatus = 1,
        Platform =1
    };
    ViewResult payResult = payController.MakePayment(payment) as ViewResult;
    PaymentResult result = payResult.Model as PaymentResult;
    Assert.IsNotNull(result.ConfCode);            
}
</code></pre>

<p>In the above given test methods <code>MakePaymentLoad</code> only checks if the view is rendered and <code>MakePaymentResult</code> checks out if the confirmation code is present in the view model.</p>

<p>My action methods are given below:</p>

<pre><code>[HttpPost]
public ActionResult MakePayment(Payment payment)
{
    PaymentResult payResult = new PaymentResult {
        ConfCode = ""123""
    };
    if (true)
    {
        TempData[""ConfCode""] = ""123"";
        return RedirectToAction(""Confirmation"");
    }
    return View(payment);
}

public ViewResult MakePayment()
{            
    return View();
}

public ActionResult Confirmation()
{
    PaymentResult result = new PaymentResult {
        ConfCode = Convert.ToString(TempData[""ConfCode""])
    };
    return View(result);
}
</code></pre>

<p>The <code>MakePaymentLoad</code> passes as it only check if the view is rendered whereas <code>MakePaymentResult</code> fails miserably as the result of action method is null because of the use <code>RedirectToAcion</code> inside <code>MakePayment's</code> post version. Please let me know how to fix this. </p>
",https://stackoverflow.com/questions/41892024/unit-testing-controller-action-which-redirects-to-another-action,"['asp.net-mvc', 'tdd']",490,TRUE,0,1
"Unit testing errors for ngModel, custom pipe and modal","<p>Trying to test my Angular application, but when trying to create my component I get multiple errors. </p>

<ol>
<li>Can't bind to 'ngModel' since it isn't a known property of 'input'.</li>
<li>The pipe 'sortOnLike' could not be found.</li>
<li>'app-edit-message-modal' is not a known element:

<ol>
<li>If 'app-edit-message-modal' is an Angular component, then verify that it is part of this module.</li>
<li>If 'app-edit-message-modal' is a Web Component then add ""CUSTOM_ELEMENTS_SCHEMA"" to the '@NgModule.schemas' of this component to suppress this message. </li>
</ol></li>
</ol>

<p>Answers to similar errors haven't helped me much.</p>

<p><strong>dashboard.spec.ts</strong></p>

<pre class=""lang-ts prettyprint-override""><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Router } from ""@angular/router"";
import { MockAF } from ""../../providers/mockAf"";
import { AF } from ""../../providers/af"";
import { DashboardComponent } from './dashboard.component';

describe('DashboardComponent', () =&gt; {
  let component: DashboardComponent;
  let fixture: ComponentFixture&lt;DashboardComponent&gt;;
  let routerStub;

  beforeEach(async(() =&gt; {
    routerStub = {
      navigate: jasmine.createSpy('navigate')
    };
    TestBed.configureTestingModule({
      declarations: [ DashboardComponent ],
      providers: [
        { provide: AF, useClass: MockAF },
        { provide: Router, useValue: routerStub },
      ],
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(DashboardComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
 });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p>Snippets from HTMLfile:</p>

<p><strong>dashboard.component.html</strong></p>

<pre class=""lang-html prettyprint-override""><code>&lt;figure class=""highlight""&gt;
   &lt;input type=""textarea"" class=""message-text"" [(ngModel)]=""newMessage""
   (keyup.enter)=""sendMessage()""&gt;
   &lt;a class=""send-message"" (click)=""sendMessage()""&gt;SEND&lt;/a&gt;
&lt;/figure&gt;


&lt;a *ngIf=""isMe(message.email)"" type='edit' class='edit-text' style=""cursor: 
    pointer;"" (click)=""show(message.$key, message.message)""&gt;Edit&lt;/a&gt;
&lt;!-- Modal (popup) for editing messages belonging to you --&gt;
&lt;app-edit-message-modal&gt;
// modal form 
&lt;/app-edit-message-modal&gt;


&lt;div *ngFor=""let message of afService.messages | async | 
    sortOnLike:'votes':false""&gt;
</code></pre>

<p>snippets from <strong>dashboard.component.ts</strong></p>

<pre class=""lang-ts prettyprint-override""><code>import { Component, OnInit, AfterViewChecked, ElementRef, ViewChild } from 
  '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { AF } from '../../providers/af';
import { FirebaseListObservable, AngularFire } from 'angularfire2';
import { Bubble } from './bubble';
import { EditMessageModalComponent } from '../edit-message-modal/edit-
   message-modal.component';

show(key: string, message: string): void {
  this.modalMessage = message;
  this.modalMessageKey = key;
  this.modal.show();
}

hide(): void {
  this.modalMessage = null;
  this.modalMessageKey = null;
  this.modal.hide();
</code></pre>

<p>}</p>

<p><strong>app.module.ts</strong></p>

<pre class=""lang-ts prettyprint-override""><code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule, Routes }   from '@angular/router';
import { AngularFireModule } from 'angularfire2';
import { AppComponent } from './app.component';
import { RegistrationPageComponent } from './registration-page/registration-
  page.component';
import { LoginPageComponent } from './login-page/login-page.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { AF } from '../providers/af';
import { FrontscreenComponent } from './frontscreen/frontscreen.component';
import { StudentDashboardComponent } from './student-dashboard/student-
  dashboard.component';
import { LecturerDashboardComponent } from './lecturer-dashboard/lecturer-
  dashboard.component';
import { firebaseConfig } from './config';
import { EditCourseModalComponent } from './edit-course-modal/edit-course-
  modal.component';
import { EditMessageModalComponent } from './edit-message-modal/edit-
  message-modal.component';
import { SortOnLikePipe } from './sort-on-like.pipe'

@NgModule({
declarations: [
  AppComponent,
  RegistrationPageComponent,
  LoginPageComponent,
  DashboardComponent,
  FrontscreenComponent,
  StudentDashboardComponent,
  LecturerDashboardComponent,
  EditCourseModalComponent,
  EditMessageModalComponent,
],
imports: [
  BrowserModule,
  FormsModule,
  HttpModule,
  AngularFireModule.initializeApp(firebaseConfig),
  RouterModule.forRoot(routes),
  SortOnLikePipe
],
providers: [AF],
bootstrap: [AppComponent],

})
export class AppModule { }
</code></pre>
",https://stackoverflow.com/questions/43598192/unit-testing-errors-for-ngmodel-custom-pipe-and-modal,"['unit-testing', 'angular', 'karma-jasmine']",758,TRUE,-1,1
Unit Testing with jest enzyme returns SyntaxError: Unexpected token,"<p>I'm trying to run a unit test on React. I'm using jest and enzyme.</p>

<p>Here's my .babelrc</p>

<pre><code>{
    ""presets"": [""es2015"", ""react"", ""airbnb""]
}
</code></pre>

<p>My test file:</p>

<pre><code>import React from 'react';
import { shallow, mount, render } from 'enzyme';

import Home from './Home/Home.js';

describe('Home', function() {
    it('should render without throwing an error', function() {
        expect(shallow(&lt;Home /&gt;).contains(&lt;div className=""columns is-mobile""&gt;&lt;/div&gt;)).toBe(true);
    });
});
</code></pre>

<p>when I run <code>npm test</code></p>

<p>I get the following error:</p>

<pre><code>FAIL  client\components\Home.test.js
  ● Test suite failed to run

    C:\Users\KeOt777\Kevin Ruiz - Front End Software Engineer\video_portal_api-master\client\components\Home\Home.css:1
    ({""Object.&lt;anonymous&gt;"":function(module,exports,require,__dirname,__filename,global,jest){.columns {
                                                                                             ^

    SyntaxError: Unexpected token .

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:305:17)
      at Object.&lt;anonymous&gt; (client/components/Home/Home.js:4:1)
      at Object.&lt;anonymous&gt; (client/components/Home.test.js:4:13)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        2.373s
Ran all test suites.
npm ERR! Test failed.  See above for more details.
</code></pre>

<p>Can anyone help me see why my test is failing to run?</p>
",https://stackoverflow.com/questions/46920423/unit-testing-with-jest-enzyme-returns-syntaxerror-unexpected-token,"['node.js', 'unit-testing', 'enzyme', 'jestjs']",387,FALSE,-1,1
Unit testing a flask application: how to handle AssertionErrors?,"<p>Here is my test_server.py file:</p>

<pre><code>from flask_testing import TestCase
class TestServer(TestCase):

    def create_app(self):
        import server
        app = server.run()
        return app

    def test_1(self):pass

    def test_2(self):pass
</code></pre>

<p>server.run does many things and ends by returning the app:</p>

<pre><code>import flask
app = flask.Flask(__name__)
def run():
    #many things that don't seem related to the issue
    import views
    views.run(app=app)
    return app
</code></pre>

<p>views.run declares many of the the @app.route endpoints. Here is a minimal case:</p>

<pre><code>import flask
def run(app):
    @app.route(""/"", methods=['GET'])
    def index():
        return flask.render_template('index.html')
</code></pre>

<p>If I comment one of the two tests, everything goes fine. If I leave both of them I get:</p>

<blockquote>
  <p>AssertionError: View function mapping is overwriting an existing endpoint function: index</p>
</blockquote>

<p>From what I understand about how this works the problem is caused because views.run is called twice. However I don't see any reason why it is the same instance that is used for both calls.</p>

<p>When tested ""by hand"" the server works fine, the problem only comes when using unit tests. The code above uses flask_testing but I had the same issue sooner with unittest.</p>

<p>What am I doing wrong?</p>
",https://stackoverflow.com/questions/47221033/unit-testing-a-flask-application-how-to-handle-assertionerrors,"['python', 'unit-testing', 'flask']",254,FALSE,0,0
c++ unit testing with CATCH ambiguous symbol std::size_t,"<p>I have this simple code, and I don't understand why it gives me the red squiggly line under TEST_CASE("""") saying it is an AMBIGUOUS SYMBOL std::size_t. It compiles fine but that red line is anoying and I don't understand it.</p>

<pre><code>#include &lt;catch.hpp&gt;

namespace Tests
{
   namespace Applications
   {
      TEST_CASE("""") &lt;----- AMBIGUOUS SYMBOL std::size_t
      {

      }
   }
}
</code></pre>

<p>EDIT:
I use Visual Studio as my IDE and it seems to be a problem with VS because I tried it with CLion and no squiggly warnings. I would prefer working with VS so I hope anybody can help me.</p>
",https://stackoverflow.com/questions/44734823/c-unit-testing-with-catch-ambiguous-symbol-stdsize-t,"['symbols', 'ambiguous', 'catch-unit-test']",259,FALSE,0,0
Angular Unit Testing with Karma Jasmine : Test Imported librariries,"<p>Am new on Angular unit testing .</p>

<p>I started by generating the basic unit test for each of my component : the test of the component creation :</p>

<p><strong>MyComponent.spec.ts</strong> </p>

<pre><code>beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ MyComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
</code></pre>

<p>To make that test works , as i notice , i should declare and imprts all my used libs and files.</p>

<p>in my case : i'm using <strong>DevExtreme</strong> UI Widgets in all my projet parts , i imported it globally:</p>

<p><strong>app.module.ts :</strong> (last import)</p>

<pre><code>import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { SharedModule } from './../shared/shared.module';
import { LoginComponent } from './login/login.component';
import { WelcomeComponent } from './welcome/welcome.component';
import { AppComponent } from './app.component';
import { CustomerModule } from './customer/customer.module';
import { ApplicationParametersComponent } from './superAdministrator/application-parameters/application-parameters.component';
import { InscriptionComponent } from './inscription/inscription.component';

import { DevExtremeModule } from 'devextreme-angular';


@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    WelcomeComponent,
    ApplicationParametersComponent,
    InscriptionComponent
  ],
  imports: [
    AppRoutingModule,
    SharedModule,
    CustomerModule,
    DevExtremeModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code></pre>

<p>fo exaple in my component i'm using a <strong>dataGrid</strong> widget from the <strong>DevExtremeModule</strong>:</p>

<p><strong>MyComponent.ts :</strong> </p>

<pre><code>import {Component, OnInit} from '@angular/core';
import {Response, Http} from '@angular/http';
import {Inject, Injectable} from '@angular/core';
import {BehaviorSubject, Observable} from 'rxjs/Rx';
import {Router} from '@angular/router';
import {Input, ContentChildren, ViewChild, QueryList} from '@angular/core';
import {HttpService} from './../../../shared/service';
import {SessionService} from './../../../shared/service';
import {Customer, TableState, StateCustomer} from './../../../model';
import {DxDataGridComponent} from 'devextreme-angular';


@Component({
  selector: 'app-MyComponent',
  templateUrl: './MyComponent.component.html',
  styleUrls: ['./MyComponent.component.css']
})
export class MyComponentComponent implements OnInit {
  @ViewChild(DxDataGridComponent) grid: DxDataGridComponent;

  customersList: Customer[];
  error: string;
  StateCustomer = StateCustomer; 
  Customer = Customer; /
  private dataGridConfig: any;

  constructor(private http: HttpService,
              private sessionService: SessionService,
              private router: Router,
  ) {
    this.tableStateSave = this.tableStateSave.bind(this);

    const url = this.http.wsCustomer
      .concat('getAll/')
      .concat('0/')
      .concat('999999/')
      .concat('null/')
      .concat('null');
    this.http.get(url)
      .map((response: Response) =&gt; response.json().map((jsonItem) =&gt; Customer.parseJson(jsonItem)))
      .subscribe(
        (customers: Customer[]) =&gt; this.customersList = customers,
        (error: Response) =&gt; console.error(error)
      );

    // Récupération état grid
    const urlStateGrid = this.http.wsSession
      .concat('tableStateLoad/')
      .concat(TableState.convertIdStringTableToInt('customersTable')
        .toString());
    this.http.get(urlStateGrid, false)
      .map((result: Response) =&gt; JSON.parse(result.json()))
      .subscribe(
        (tableConfig: any) =&gt; {
          this.dataGridConfig = tableConfig;
          this.tableStateLoad = this.tableStateLoad.bind(this);
        }
      );
  }

  create(): void {
    this.router.navigate(['/customer-detail']);
  }

  view(customer: Customer): void {
    this.router.navigate(['/customer-detail/'.concat(customer.id.toString())]);
  }

  delete(customer: Customer): void {
    const url = this.http.wsCustomer
      .concat('delete/')
      .concat(customer.id.toString())
      .concat('/')
      .concat(customer.version.toString()
      );

    this.http.delete(url).subscribe(
      this.customersList.splice(this.customersList.indexOf(customer), 1);
      () =&gt; null,
      (error: Response) =&gt; console.error(error)
    );
  }

  tableStateSave(gridState: object): void {

    this.saveState(gridState);
  }

  manualSave() {
    const detectedState = this.grid.instance.state();

    this.saveState(detectedState);
  }
  saveState(state) {
    const url = this.http.wsSession.concat('tableStateSave');
    const tableState = new TableState();
    tableState.idTable = TableState.convertIdStringTableToInt('customersTable');
    tableState.state = JSON.stringify(state);

    this.http.put(url, tableState, false).subscribe(
      () =&gt; null,
      (error: Response) =&gt; console.error(error)
    );
  }


  tableStateLoad(): any {
    return this.dataGridConfig;
  }
}
</code></pre>

<p><strong>MyComponent.html:</strong></p>

<pre><code>&lt;button (click)=""create()"" id=""buttonCreate"" class=""btn btn-secondary rightFloat""&gt;Créer&lt;/button&gt;&lt;br&gt;&lt;br&gt;
&lt;button (click)=""manualSave()"" class=""btn btn-secondary""&gt;Save state&lt;/button&gt;

&lt;dx-data-grid
    id=""customersTable""
    [dataSource]=""customersList""
    [allowColumnReordering]=""true""
    [allowColumnResizing]=""true""
    [columnAutoWidth]=""true""
    [columnMinWidth]=""50""
    [showBorders]=""true""
    [rowAlternationEnabled]=""true""
    [hoverStateEnabled]=""true""
    (onRowRemoving)=""delete($event.data)""
    (onRowClick)=""view($event.data)""
&gt;
    &lt;dxo-column-chooser [enabled]=""true""&gt;&lt;/dxo-column-chooser&gt;
    &lt;dxo-column-fixing [enabled]=""true""&gt;&lt;/dxo-column-fixing&gt;
    &lt;dxo-search-panel [visible]=""true"" placeholder=""Rechercher""&gt;&lt;/dxo-search-panel&gt;
    &lt;dxo-selection mode=""single""&gt;&lt;/dxo-selection&gt;

    &lt;dxo-state-storing [enabled]=""true"" type=""custom"" savingTimeout=""900000"" [customSave]=""tableStateSave"" [customLoad]=""tableStateLoad""&gt;&lt;/dxo-state-storing&gt;

    &lt;dxo-paging [pageSize]=""10""&gt;&lt;/dxo-paging&gt;
    &lt;dxo-pager [showPageSizeSelector]=""true"" [allowedPageSizes]=""[10, 20, 50, 100]"" [showInfo]=""true""&gt;&lt;/dxo-pager&gt;
    &lt;dxo-editing mode=""row"" [allowDeleting]=""true""&gt;&lt;/dxo-editing&gt;
    &lt;dxo-export [enabled]=""true"" fileName=""Mes clients""&gt;&lt;/dxo-export&gt;
    &lt;dxo-filter-row [visible]=""true""&gt;&lt;/dxo-filter-row&gt;
    &lt;dxo-group-panel [visible]=""true""&gt;&lt;/dxo-group-panel&gt;
    &lt;dxo-grouping #expand [autoExpandAll]=""true""&gt;&lt;/dxo-grouping&gt;

    &lt;dxi-column dataField=""id"" caption=""Id"" [width]=""30""&gt;&lt;/dxi-column&gt;
    &lt;dxi-column dataField=""name1"" caption=""Nom 1"" [width]=""150""&gt;&lt;/dxi-column&gt;
    &lt;dxi-column dataField=""name2"" caption=""Nom 2"" [width]=""150""&gt;&lt;/dxi-column&gt;
    &lt;dxi-column dataField=""email"" caption=""Email"" [width]=""300""&gt;&lt;/dxi-column&gt;
    &lt;dxi-column dataField=""dateCreated"" caption=""Date création"" [width]=""100"" dataType=""date"" format=""dd/MM/yyyy""&gt;&lt;/dxi-column&gt;
    &lt;dxi-column dataField=""dateUpdated"" caption=""Date modification"" [width]=""100"" dataType=""date"" format=""dd/MM/yyyy""&gt;&lt;/dxi-column&gt;
    &lt;dxi-column dataField=""state"" caption=""Etat"" [width]=""30"" cellTemplate=""cellTemplate_stateCustomer""&gt;&lt;/dxi-column&gt;

    &lt;div *dxTemplate=""let data of 'cellTemplate_stateCustomer'""&gt;
        &lt;span *ngIf=""data.value == StateCustomer.BLOCKED""&gt;{{ Customer.getStateCustomer(StateCustomer.BLOCKED) }}&lt;/span&gt;
        &lt;span *ngIf=""data.value == StateCustomer.ALLOWED""&gt;{{ Customer.getStateCustomer(StateCustomer.ALLOWED) }}&lt;/span&gt;
    &lt;/div&gt;
</code></pre>

<p>When running my test (spec file)</p>

<p>I god errors about the devExtreme syntax , i think that relative to my devExtreme module import , and generally any other library , </p>

<p>My error is the following :</p>

<blockquote>
  <p>Can't bind to 'dxTemplateOf' since it isn't a known property of 'div'.
  (""tate"" caption=""Etat"" [width]=""30""
  cellTemplate=""cellTemplate_stateCustomer"">
        ]*dxTemplate=""let data of 'cellTemplate_stateCustomer'"">
            
        [ERROR ->]
            http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:1690:21
  &lt;- src/test.ts:114544:34)
        at TemplateParser.Array.concat.TemplateParser.parse (<a href=""http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:12814:0"" rel=""nofollow noreferrer"">http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:12814:0</a>
  &lt;- src/test.ts:125668:19)
        at JitCompiler.Array.concat.JitCompiler._compileTemplate (<a href=""http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:26966:0"" rel=""nofollow noreferrer"">http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:26966:0</a>
  &lt;- src/test.ts:139820:39)
        at <a href=""http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:26886:47"" rel=""nofollow noreferrer"">http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:26886:47</a>
  &lt;- src/test.ts:139740:62
        at Set.forEach (native)
        at JitCompiler.Array.concat.JitCompiler._compileComponents (<a href=""http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:26886:0"" rel=""nofollow noreferrer"">http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:26886:0</a>
  &lt;- src/test.ts:139740:19)
        at <a href=""http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:26787:0"" rel=""nofollow noreferrer"">http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:26787:0</a>
  &lt;- src/test.ts:139641:19
        at Object.then (<a href=""http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:1679:32"" rel=""nofollow noreferrer"">http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:1679:32</a>
  &lt;- src/test.ts:114533:148)
        at JitCompiler.Array.concat.JitCompiler._compileModuleAndAllComponents
  (<a href=""http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:26785:0"" rel=""nofollow noreferrer"">http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:26785:0</a>
  &lt;- src/test.ts:139639:26)
        at JitCompiler.Array.concat.JitCompiler.compileModuleAndAllComponentsAsync
  (<a href=""http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:26717:0"" rel=""nofollow noreferrer"">http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:26717:0</a>
  &lt;- src/test.ts:139571:37)     Error: Template parse errors:   Can't bind
  to 'dxTemplateOf' since it isn't a known property of 'div'. (""tate""
  caption=""Etat"" [width]=""30""
  cellTemplate=""cellTemplate_stateCustomer"">
        ]*dxTemplate=""let data of 'cellTemplate_stateCustomer'"">
            
        [ERROR ->]
            http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:1690:21
  &lt;- src/test.ts:114544:34)
        at TemplateParser.Array.concat.TemplateParser.parse (<a href=""http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:12814:0"" rel=""nofollow noreferrer"">http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:12814:0</a>
  &lt;- src/test.ts:125668:19)
        at JitCompiler.Array.concat.JitCompiler._compileTemplate (<a href=""http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:26966:0"" rel=""nofollow noreferrer"">http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:26966:0</a>
  &lt;- src/test.ts:139820:39)
        at <a href=""http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:26886:47"" rel=""nofollow noreferrer"">http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:26886:47</a>
  &lt;- src/test.ts:139740:62
        at Set.forEach (native)
        at JitCompiler.Array.concat.JitCompiler._compileComponents (<a href=""http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:26886:0"" rel=""nofollow noreferrer"">http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:26886:0</a>
  &lt;- src/test.ts:139740:19)
        at <a href=""http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:26787:0"" rel=""nofollow noreferrer"">http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:26787:0</a>
  &lt;- src/test.ts:139641:19
        at Object.then (<a href=""http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:1679:32"" rel=""nofollow noreferrer"">http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:1679:32</a>
  &lt;- src/test.ts:114533:148)
        at JitCompiler.Array.concat.JitCompiler._compileModuleAndAllComponents
  (<a href=""http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:26785:0"" rel=""nofollow noreferrer"">http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:26785:0</a>
  &lt;- src/test.ts:139639:26)
        at JitCompiler.Array.concat.JitCompiler.compileModuleAndAllComponentsSync
  (<a href=""http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:26709:0"" rel=""nofollow noreferrer"">http://localhost:9877webpack:///~/@angular/compiler/@angular/compiler.es5.js:26709:0</a>
  &lt;- src/test.ts:139563:42)     Expected undefined to be truthy.
        at Object. (<a href=""http://localhost:9877webpack:///src/app/customer/customers-list/customers-list.component.spec.ts:25:22"" rel=""nofollow noreferrer"">http://localhost:9877webpack:///src/app/customer/customers-list/customers-list.component.spec.ts:25:22</a>
  &lt;- src/test.ts:232248:27)
        at ZoneDelegate.invoke (<a href=""http://localhost:9877webpack:///~/zone.js/dist/zone.js:391:0"" rel=""nofollow noreferrer"">http://localhost:9877webpack:///~/zone.js/dist/zone.js:391:0</a> &lt;-
  src/polyfills.ts:1546:26)
        at ProxyZoneSpec.Array.concat.ProxyZoneSpec.onInvoke (<a href=""http://localhost:9877webpack:///~/zone.js/dist/proxy.js:79:0"" rel=""nofollow noreferrer"">http://localhost:9877webpack:///~/zone.js/dist/proxy.js:79:0</a> &lt;-
  src/test.ts:228722:39)
        at ZoneDelegate.invoke (<a href=""http://localhost:9877webpack:///~/zone.js/dist/zone.js:390:0"" rel=""nofollow noreferrer"">http://localhost:9877webpack:///~/zone.js/dist/zone.js:390:0</a> &lt;-
  src/polyfills.ts:1545:32)</p>
</blockquote>

<p>I need a general solution for such problems , because i think that i should find a way to import properly my modules to my test files similarly to my project components :</p>

<p><strong>Any suggestions ??</strong></p>
",https://stackoverflow.com/questions/45472773/angular-unit-testing-with-karma-jasmine-test-imported-librariries,"['javascript', 'angular', 'unit-testing', 'karma-jasmine', 'devextreme']",1094,FALSE,0,0
how to do unit testing for react-native applications,"<p>Hi this is a sample class which I want to write unit for </p>

<pre><code>export default class testProject extends Component {

 _sum(a, b) {
      return a + b;
  } 

render() {
   return (
       &lt;View&gt;
            &lt;Text&gt;Business Finance&lt;/Text&gt;
       &lt;/View&gt;
          );
         }
}
</code></pre>

<p>what tools do I need to test both UI and the Bussiness logic :) thank you</p>
",https://stackoverflow.com/questions/46072675/how-to-do-unit-testing-for-react-native-applications,"['unit-testing', 'react-native']",132,TRUE,0,2
Unit testing conditional if/else statements w/ Mocha/Chai,"<p>Quick question, I can not find any documentation online in regards to testing a simple function with several if/else statements such as this fizzBuzz example...</p>

<pre><code>module.exports =
function fizzBuzz(num) {
    for (let i; i &lt;= num; i++) {
        if (i % 3 === 0 &amp;&amp; i % 5 === 0) {
            return 'FIZZBUZZ';
        } else if (i % 3 === 0) {
            return 'FIZZ';
        } else if (i % 5 === 0) {
            return 'BUZZ';
        } else {
            return 'Your number is' + i;
        }
    }
}
</code></pre>

<p>Here is my Chai...</p>

<pre><code>const assert = require('chai').assert;
const expect = require('chai').expect;
const fizzBuzz = require('../fizzBuzz.js');

describe.only('fizzBuzz', function () {
    describe('Smoke tests', function () {
        it('should exist', function () {
            expect(fizzBuzz).to.exist;
        })
        it('Should be a function', function() {
            expect(fizzBuzz).to.be.a('function');
        })
    })
})
</code></pre>

<p>What would be the syntax for checking each if/else statement? I would like to check to make sure on certain conditions, the function returns a string, and others returns a number. As well as when it returns a string, does it match which word should be returned. I am very new to Mocha/Chai.</p>

<p>Thank you in advance guys,</p>

<p>Brittany</p>
",https://stackoverflow.com/questions/45496877/unit-testing-conditional-if-else-statements-w-mocha-chai,"['javascript', 'syntax', 'conditional-statements', 'mocha.js', 'chai']",4294,TRUE,0,1
Unit testing Coverage report not showing on SonarQube Dashboard,"<p>Our Sonar Build Environment details as follows:</p>
<pre><code>* SonarQube Server Version - 5.6.6 (64-Bit). 
* Sonar Client Build Operating System – Ubuntu 14.04.5 LTS (64-Bit). 
* Sonar-scanner- Version - 3.0.3.778.
* sonar-cxx-plugin-0.9.7.jar
* Source Code Language: C++
* gcovr Version - 3.3
</code></pre>
<p><strong>Current Problem:</strong></p>
<p>We have Unit testing coverage report (Gcovr - .XML based - CoverageReport.xml) file, Sonar doesn’t show any error message in log, also it is not showing coverage information on SonarQube Dashboard.
My sonar-project.properties file has below information to import my coverage report.</p>
<pre><code>sonar.cxx.coverage.reportPath=VE_L/CoverageReport.xml
</code></pre>
<p>Sonar Scanner Log not showing any error. Whereas I can see import successful.</p>
<pre><code>10:28:23.717 INFO  - Scanner found '1' report files
10:28:23.717 INFO  - Parser will parse '1' report files
10:28:23.921 INFO  - Added report '/home/srinivas.ghs/Jenkins/workspace/VE_Engine/MORE_SERVICE/VideoMaker/Development/DREAM/VE_L/CoverageReport.xml' (parsed by: CoberturaParser) to the coverage data
10:28:24.080 INFO  - Project 'scm.team.videoeditor' Cycles:0 Feedback cycles:0 Tangles:0 Weight:0.0
10:28:24.081 INFO  - Sensor CxxSquidSensor (done) | time=11057ms
</code></pre>
<p>Note: I have Configured Unit Tests Coverage &amp; Integration Tests Coverage Wedgits.</p>
<p>So could you help me to display my unit testing coverage report on SonarQube Dashboard.</p>
",https://stackoverflow.com/questions/44581340/unit-testing-coverage-report-not-showing-on-sonarqube-dashboard,"['c++', 'jenkins', 'sonarqube', 'code-coverage']",1534,FALSE,0,1
Mocking library functions when unit testing chef custom resource,"<p>I have created a very simple custom resource in Chef, and inside that resource is some simple logic. The logic in question calls out to some custom helper methods.</p>

<p>I can build the resource, and execute it as part of a recipe - but if I would like to unit test the behaviour within the resource itself to ensure the flow is correct. As such, I want to be able to mock the behaviour of those helper functions so that I can direct the resource behaviour. Unfortunately, I can't get this to work.</p>

<p>My recipe looks like this:</p>

<pre><code>my_resource 'executing' do
    action :execute
end
</code></pre>

<p>The resource looks like this:</p>

<pre><code>action :execute do
  if my_helper?(node['should_be_true'])
    converge_by ""Updating"" do
      my_helper_method
    end
  end
end

action_class do
  include CustomResource::Helpers
end
</code></pre>

<p>The functions are simple:</p>

<pre><code>module CustomResource
  module Helpers
    def my_helper?(should_be_true)
      should_be_true
    end

    def my_helper_method
      hidden_method
    end

    def hidden_method
      3
    end
  end
end
</code></pre>

<p>When I try to mock the behaviour of these in my ChefSpec tests, I get errors:</p>

<pre><code>it 'executes' do
  allow(CustomResource::Helpers).to receive(:my_helper?).and_return(true)
  expect(CustomResource::Helpers).to receive(:my_helper_method)
  expect { chef_run }.to_not raise_error
end


Failure/Error: expect(CustomResource::Helpers).to receive(:my_helper_method)

   (CustomResource::Helpers).my_helper_method(*(any args))
       expected: 1 time with any arguments
       received: 0 times with any arguments
</code></pre>

<p>Any ideas what I'm doing wrong in my mocking?</p>

<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/46766889/mocking-library-functions-when-unit-testing-chef-custom-resource,"['unit-testing', 'mocking', 'chef-infra', 'chefspec']",976,TRUE,0,2
Unit Testing a method which uses object instances internally,"<p>While writing the unit testing for class B, how can i test the method -> <code>checkValidity()</code>. The method internally initializes class C instance and invokes methods on that object.</p>

<p>How can we check with <code>Mockito</code>/<code>Powermock</code>?</p>

<pre><code>public class B {

 public List&lt;Object&gt; checkValidity(){

   C c=new C();

   if(c.isTrue()){
    .....
   }

   switch(c.getVal()){

       case 1: ...
       case 2: ..
       default : ...

   }



 }

 return list;

}

class C {

  public boolean isTrue(){
    ....
  }


  public int getVal(){
    ....
  }

}
</code></pre>

<p>Regards</p>
",https://stackoverflow.com/questions/44111327/unit-testing-a-method-which-uses-object-instances-internally,"['java', 'unit-testing', 'junit', 'mockito', 'powermock']",1757,TRUE,0,2
Unit Testing .NET Core Web API Controllers with JWT Claims,"<p>I'm attempting to test a controller method that utilizes JWT claims to get the user name of the client like so:</p>

<pre><code>[Authorize]
[Route(""api/[controller]"")]
public class ApprovalsController : Controller
{
  // POST api/approvals
    [HttpPost]
    public IActionResult Post([FromBody]ApprovalViewModel value)
    {
        // ...

        // Incoming approval VM converted here
        Approval newApproval = TinyMapper.Map&lt;Approval&gt;(value);

        // Values set server-side here.
        newApproval.Id = -1;
        newApproval.Created = DateTime.Now;

        // Claim queried here
        newApproval.CreatedBy = User.FindFirst(ClaimTypes.Name).Value; 

        // Submission to context
        _approvalRepo.Insert(newApproval);
        _approvalRepo.Update();

        // ...
    }
</code></pre>

<p>But I've had the darnedest luck in trying to conceive of a way to unit test the above controller using Moq and XUnit. Many of the questions I've searched for involve directly setting the ControllerBase.User attribute of the controller, but in <strong>Aspnetcore.MVC</strong> (1.1.1), User has been set as <em>read-only</em>.</p>

<p>What is it that I'm to do, here?</p>
",https://stackoverflow.com/questions/43429568/unit-testing-net-core-web-api-controllers-with-jwt-claims,"['c#', 'unit-testing', 'jwt', 'asp.net-core-webapi']",6879,TRUE,6,1
Unit testing Django Rest API with JWT Authorization fails,"<p>I have the following problem:
whenever I run my unit tests to test my Django REST API, I get an 401 Unauthorized, even though I paste in the correct Token for the User object I created during the test. However, I expect the response to be a 200..</p>

<p>Here's the code:</p>

<pre><code>class TestWebApi(APITestCase):

  def setUp(self):
      self.factory = APIRequestFactory()
      self.client = Client()
      self.user = User.objects.create_user('testuser', None, '12345a')
      Employee.objects.create(name='Test', surname='Employee1', role=""frontend"", account=User.objects.get(username='testuser'))

  def test_api_employee(self):
      user = self.user
      token = json.loads(self.client.post('/api/get_jwt_token/', data={'username': 'testuser', 'password': '12345a'}).content)['token']
      response = self.client.get('/api/v2/employees/', HTTP_Authorization=""JWT {0}"".format(token))
      employees = Employee.objects.all()
      serializer = EmployeeSerializer(employees, many=True)
      self.assertEqual(response.status_code, status.HTTP_200_OK)
      json_response = response.json()
      self.assertEqual(json_response, serializer.data)
</code></pre>

<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/47455032/unit-testing-django-rest-api-with-jwt-authorization-fails,"['django', 'rest', 'unit-testing', 'django-rest-framework', 'jwt']",203,FALSE,0,1
C++14 unit testing (de)allocation of a private member,"<p>I have a <code>deactivate()</code> method, which should, amongst other things, deallocate a private member of the class (ultimately a <code>std::vector</code>'s <code>resize(0)</code> + <code>shrink_to_fit()</code> - but that's not important).  </p>

<p>How can I go about unit testing that the member was deallocated by the <code>deactivate</code> method, given that the test has no way to access the private member to check it?</p>

<p>I am trying to avoid dependency injection, because the code is performance critical and I am wary of indirections via references/pointers and potential loss of inlining optimisations.  But if there is some magic that avoids these disadvantages, I am all for it!</p>

<p>I am not averse to checking raw memory usage, but of course it's non-trivial with members that allocate on the heap (like <code>std::vector</code>), and I don't know a way to do it.</p>

<p>I have read plenty of posts about testing <code>private</code> members (abusing <code>friend</code>, compile-time conditionally declaring <code>protected</code>/<code>public</code>), but I'm hoping someone can give a prettier solution to this more restricted case, or a way to do dependency injection without indirection and loss of inlining.</p>
",https://stackoverflow.com/questions/45537512/c14-unit-testing-deallocation-of-a-private-member,"['c++', 'performance', 'unit-testing', 'dependency-injection', 'c++14']",100,TRUE,0,1
Unit Testing VueJS Karma Mocha ExpectJS nextTick not working,"<p>I have a simple form with a password field.  If the password input field is empty this span is shown:</p>

<pre><code>&lt;span id='password-required' v-show='!validation.password'&gt;Required&lt;/span&gt;
</code></pre>

<p>Once at least one character is entered the <code>'Required'</code> message is hidden.  This logic works in the browser just fine.  The problem is that I cannot seem to get the unit test to work.</p>

<p>I figured <code>nextTick()</code> would fix it, but it did not. I used code very similar to this for the email field, and it works. I commented out two lines that I also tried, but that also fail. PhantomJS is used.</p>

<p>How do I add a value to the password field and verify that the 'Required' message goes invisible?</p>

<pre><code>it(`Hides 'Required' message (password input contains data).`, done =&gt; {
  // Extend the component to get the constructor, and initialize directly.
  let email = 'a@b'
  const Constructor = Vue.extend(Login)
  const component = new Constructor({
    propsData: {
      emailentry: email
    }
  }).$mount()

  let password = '123'
  component.$el.querySelector('#password').value = password

  //This line passes.
  expect(component.$el.querySelector('#password').value).to.equal(password)

  // Confirm 'Required' message is hidden.
  Vue.nextTick(() =&gt; {
    expect(component.$el.querySelector('#password-required').style.display).to.equal('none')

    // expect(component.validation.password).to.equal(true)
    // expect(!!component.user.password.trim()).to.equal(true)
    done()
  })
})
</code></pre>

<p><a href=""https://github.com/nueverest/vue-signup-login/blob/master/test/unit/specs/Login.spec.js"" rel=""nofollow noreferrer"">Login.spec.js Test File</a> (Failing tests are commented out.)</p>

<p><a href=""https://github.com/nueverest/vue-signup-login/blob/master/src/components/Login.vue"" rel=""nofollow noreferrer"">Login.vue Component File</a></p>
",https://stackoverflow.com/questions/43037239/unit-testing-vuejs-karma-mocha-expectjs-nexttick-not-working,"['unit-testing', 'vue.js', 'vuejs2', 'vue-component', 'karma-mocha']",552,FALSE,0,1
MVVM Cross Unit testing possible with MSTest in Xamarin,"<p>Is it possible to do unit testing of Xamarin MVVM Cross View Models which are placed in pcl project with Microsoft Unit Testing Framework (MS-TEST)?</p>
",https://stackoverflow.com/questions/44457063/mvvm-cross-unit-testing-possible-with-mstest-in-xamarin,"['unit-testing', 'xamarin', 'mvvm', 'mvvmcross', 'mstest']",324,TRUE,0,1
C# unit testing for a NotFound via a GET,"<p>For some reason, I am having troubles making a unit test for the following in C#</p>

<pre><code>[Route(""api/Orders/{orderID:int}/Items"")]
public OrderItemsDTO Get(int orderID)
{
    if (_orderItemsService.Get(orderID).Items.Count() == 0)
    {
          throw new HttpResponseException(
             Request.CreateErrorResponse(HttpStatusCode.NotFound, String.Format(""Order {0} not found."", orderID)));
    }           

    return _orderItemsService.Get(orderID);              
}
</code></pre>

<p>I have a unit test running correctly for an Async Add which is what I'm using to Post that I was trying to base my unit test off of with some tweaks I thought it would work, but it doesn't. the following is what I thought should work:</p>

<pre><code>   private OrderItemsController _testSubject;
   private Mock&lt;IOrderItemsService&gt; _moqOrderItemsService = new Mock&lt;IOrderItemsService&gt;();

    [TestInitialize]
    public void TestInitialize()
    {
        _testSubject = new OrderItemsController(_moqOrderItemsService.Object);
    }

    [TestMethod]
    [ExpectedException(typeof(HttpResponseException))]
    public async Task ThrowHttpResponseExceptionWhenThereIsAValidationException()
    {
        _moqOrderItemsService.Setup(ois =&gt; ois.Get(It.IsAny&lt;int&gt;()))
            .Throws(new ValidationException(""test""));

        try
        {
            _testSubject.Get(17);
        }
        catch(HttpResponseException ex)
        {
            Assert.IsNotNull(ex.Response);
            Assert.AreEqual(HttpStatusCode.NotFound, ex.Response.StatusCode);
            throw;
        }            
    }
</code></pre>
",https://stackoverflow.com/questions/42986670/c-unit-testing-for-a-notfound-via-a-get,"['c#', 'rest', 'unit-testing']",2100,TRUE,0,2
AngularJs Unit Testing Controller with sweetalert in Jasmine Testing,"<p>I'm trying to test my angularjs controller with jasmine and karma but i cant test codeblocks that are in sweetalert function. How can i confirm sweet function from my test class to test $scope.getCategory() is called or not? Here is a example code from my controller and jasmine test case.</p>

<p>Controller:</p>

<pre><code>$scope.changeCategoryStatus = function(selectedId, selectedActive, topId) {
    sweet.show({
        title : ""Kategoriyi ""+(!selectedActive ? 'aktif' : 'pasif')+ "" hale getirmek istiyor musunuz?"",
        type : ""warning"",
        showCancelButton : true,
        confirmButtonColor : ""#DD6B55"",
        confirmButtonText : ""Evet, değiştir!"",
        closeOnConfirm : false,
        showLoaderOnConfirm : true,
        html : false
    }, function() {
        $http({
            method : ""POST"",
            url : webRootUrl+""ajax/category/setActivation"",
            data : {
                ""id"" : selectedId,
                ""active"" : !selectedActive
            }

        }).then(function(response) {

            //console.log(JSON.stringify(response.data))
            if(response.data.outPutDouble==-7){
                swal(""Değiştirilemedi!"", response.data.outPutString,""error"");
            }else{
            $scope.getCategory(topId);
            swal(""Bu kategorinin durumu değiştirildi"","""",
            ""success"");
            }
        }, function myError(response) {
            swal(""Bu kategorinin durumu değiştirilemedi"","""",""error"");

            //console.log(""***aaa"" + JSON.stringify(response))
        });


    });

}
</code></pre>

<p>Jasmine Test Case:</p>

<pre><code>  it(""changeCategoryStatus success"", function () {
  $scope.changeCategoryStatus(21,true,0)

  spyOn($scope,'getCategory')
  expect($scope.getCategory).toHaveBeenCalled(); });
</code></pre>

<p>Has anyone had a similar problem earlier? Thanks in advance for help.</p>
",https://stackoverflow.com/questions/42803602/angularjs-unit-testing-controller-with-sweetalert-in-jasmine-testing,"['javascript', 'angularjs', 'unit-testing', 'jasmine', 'sweetalert']",1163,TRUE,0,1
Null pointer exception while doing unit testing using Mockito,"<p>I am new with Mockito. I am writing unit test cases for <code>SomeDaoImplclass</code></p>

<p>this is the method in <code>SomeDaoImplClass</code></p>

<pre><code>@Override 
Public SomeModelClass retriveSomeDetails(int a,long b){
    return retrieveSomeDetails(a,b,Enum.Active)
}
</code></pre>

<p>Here is my test class</p>

<pre><code>@Mock
private SomeDaoImplClass someDaoImplClass

@Mock
private NamedParameterJdbcTemplate jdbcTemplate

@Mock
DataSource dataSource

@Mock
SomeDaoClass someDaoClass

@Before
Public void setUp() throws Exception {
    someDaoImplClass = new SomeDaoImplClass();

    dataSource = Mockito.mock(DataSource.class);
    jdbcTemplate = Mockito.mock(NamedParameterJdbcTemplate.class);

    someDaoClass = Mockito.mock(SomeDaoClass.class);

    SomeDaoImplClass.setDataSource(dataSource);
    SomeDaoImplClass.setSomeDaoClass(someDaoClass);
}

@Test
public void testSomeData(){
    Modelclass modelclass = new ModelClass();
    Mockito.when(SomeDaoClass.retriveSomeDetails(Mockito.anyInt(),Mockito.anyLong())).thenReturn(modelClass);
    ModelClass object2 = SomeDaoImplClass.retriveSomeDetails(01,1000L,Class.Active);
    Assert.assertEquals(01,1000L, object2);
}
</code></pre>
",https://stackoverflow.com/questions/44565461/null-pointer-exception-while-doing-unit-testing-using-mockito,"['spring-mvc', 'mockito', 'junit4', 'dao']",989,FALSE,-1,1
Unit testing rendering context. Page context throws an exception,"<p>I am trying to create unit test using sitecoreFakeDB my code displays below:</p>

<pre><code>using (Sitecore.FakeDb.Db db = new Sitecore.FakeDb.Db() { new Sitecore.FakeDb.DbItem(""source"") })
        {
            var contextItem = db.GetItem(""/sitecore/content/source"");
            var args = new Sitecore.Pipelines.PipelineArgs();
            using (RenderingContext.EnterContext(new Rendering(), contextItem))
            {

                var processor = new Mock&lt;Sitecore.FakeDb.Pipelines.IPipelineProcessor&gt;();

                db.PipelineWatcher.Register(""mypipeline"", processor.Object);

                Sitecore.Pipelines.CorePipeline.Run(""mypipeline"", args);

                Xunit.Assert.NotNull(args.Current));
            }
        }
</code></pre>

<p>upon checking the pagecontext in the RenderingContext.Current it throws an exception. How can I have a value for the pagecontext?
<a href=""https://i.stack.imgur.com/unIRI.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/unIRI.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/44389823/unit-testing-rendering-context-page-context-throws-an-exception,"['sitecore', 'moq']",698,TRUE,0,1
Unit testing text manipulation in the DOM using jQuery,"<p>I am trying to test simple DOM manipulation and running into some trouble. Imagine the following simple click event:</p>

<pre><code>$('.js-click-me').on('click', function(e) {
  e.preventDefault();

  $('.some-span').text('changed text');
});
</code></pre>

<p>Now also imagine that my HTML contains the following:</p>

<pre><code>&lt;span class=""some-span""&gt;Original Text&lt;/span&gt;
&lt;button class=""js-click-me""&gt;Click Me&lt;/button&gt;
</code></pre>

<p>Ok, so now I have a unit tests</p>

<pre><code>describe('text change test', function() {
  it('The text of .some-span should change when button is clicked', function() {
    assert.equal('Original Text', $('.some-span').text());
    $('.js-click-me').click();
    assert.equal('changed text', $('.some-span').text());
  });
});
</code></pre>

<p>My expectation is that the first assertion will pass because the original text is, in fact ""Original Text"" (this is just done to set a baseline and probably not required).</p>

<p>The second assertion I expect to pass because after the click it is changing the text from ""Original Text"" to ""changed text"". However, when I run tests like this the second assertion fails because the test runs <em>immediately</em> after and the DOM hasn't updated the text yet. </p>

<p>I can add the second test in a <code>setTimeout</code> wrapper but that doesn't seem correct or efficient. </p>

<p>Any tips for this?</p>
",https://stackoverflow.com/questions/42398731/unit-testing-text-manipulation-in-the-dom-using-jquery,"['jquery', 'unit-testing', 'mocha.js', 'karma-runner', 'chai']",70,FALSE,0,1
How do I start unit testing in Angular 4?,"<p>I'm currently following this guide on unit testing .<a href=""https://angular.io/docs/ts/latest/guide/testing.html"" rel=""nofollow noreferrer"">Unit testing in Angular</a></p>

<p>I went to the ""Test environment setup files"" and there is a link to a page that should explain how to configure and bootstrap files for unit testing but I get a 404 when I click on it. Also, on the same page it says :""The deep details of these files and how to reconfigure them for your needs is a topic beyond the scope of this guide ."" So where can I find details about how to setup files for unit testing? I've tried using the sample files they had but I'm not sure how to tailor them to my needs.</p>
",https://stackoverflow.com/questions/43507915/how-do-i-start-unit-testing-in-angular-4,"['unit-testing', 'angular']",382,TRUE,0,1
Dart Angular replacing provider with mock in unit testing,"<p>How can I replace the provider <code>QuizService</code> to <code>QuickServiceMock</code> in Angular Dart unit testing?</p>

<p>I tried using <code>addProviders</code> method but that didn't replace <code>QuizService</code> with <code>QuizkServiceMock</code>.</p>

<p>It seems <code>MultipleChoiceQuizComponent</code> is still using the original class <code>QuizkService</code> and not <code>QuizServiceMock</code> like I want it to.</p>

<pre><code>import 'dart:html';
import 'package:angular2/angular2.dart';
import 'package:angular_test/angular_test.dart';
import 'package:test/test.dart';
import 'package:mockito/mockito.dart';

import '...quiz_service.dart';
import '...multiple_choice_quiz_component.dart';
import '...multiple_choice_quiz.dart';

class MockQuizService extends Mock implements QuizService {}

@AngularEntrypoint()
void main()
{
    group('$MultipleChoiceQuizComponent', () {
        MockQuizService quizServiceMock;
        setUp(() async {
            quizServiceMock = new MockQuizService();
            List&lt;String&gt; mockChoiceList = [
                ""incorrect1"",
                ""incorrect2"",
                ""correct answer"",
                ""incorrect3""
            ];
            when(quizServiceMock.getQuiz())
                .thenReturn(
                    new MultipleChoiceQuiz(
                        mockChoiceList,
                        ""correct answer"",
                        'test question description'
                )
            );
        });

        test('should add ""incorrect"" css class to incorrect answer', () async {
            NgTestBed bed = new NgTestBed&lt;MultipleChoiceQuizComponent&gt;().addProviders([
                provide(QuizService, useValue: quizServiceMock)
            ]);
            NgTestFixture fixture = await bed.create();
            Element answer = fixture.rootElement.querySelector('.quiz-choice:nth-child(2)');
            answer.dispatchEvent(new MouseEvent('click'));
            bool hasClass = answer.classes.contains('incorrect');
            expect(hasClass, true);
        });
    });

}
</code></pre>

<p><strong>multiple_choice_quiz_component.dart:</strong></p>

<pre><code>import 'package:angular2/core.dart';
import 'package:angular2/common.dart';
import 'package:angular2_components/angular2_components.dart';

import '.../quiz/quiz.dart';
import '.../service/quiz_service.dart';

@Component
(
    selector: 'multiple-choice-quiz-component',
    directives: const [materialDirectives, NgFor],
    providers: const [materialProviders, QuizService],
    templateUrl: 'multiple_choice_quiz_component.html',
    styleUrls: const['/app_component.css', 'quiz.css']
)

class MultipleChoiceQuizComponent
{
    String selectedAnswer;
    String description;
    bool correctAnswer = false;
    Quiz quiz;

    MultipleChoiceQuizComponent(QuizService quizService)
    {
        this.quiz = quizService.getQuiz();
    }

    void onSelect(String answer)
    {
        selectedAnswer = answer;
        this.correctAnswer = this.quiz.isAnswer(answer);
    }
}
</code></pre>

<p>What am I missing?</p>
",https://stackoverflow.com/questions/42887057/dart-angular-replacing-provider-with-mock-in-unit-testing,"['unit-testing', 'angular', 'mocking', 'dart', 'mockito']",456,TRUE,0,1
Unit testing a Xamarin Forms Android specific code project,"<p>I'm running into an issue where I've done a Xamarin.Forms Application.</p>

<p>Currently, I'm trying to Unit test an Android Service. </p>

<p>So currently this means I've done the following at this point:</p>

<ol>
<li>default Xamarin forms application with iOS project deleted</li>
<li>Basic Forms in the PCL created</li>
<li>Have styles created in Xamarin.Forms PCL</li>
<li>Have basic theme in Xamarin.Forms.Droid project</li>
</ol>

<p>After doing that, I've created Xamarin UITest Android Project</p>

<p>Now, I've added a reference to the Xamarin Forms.Droid Project</p>

<p>Every time I launch the unit test, which has to run in the Android emulator, it fails to find the theme.</p>

<p>within the app.xml that resides in the PCL</p>

<pre><code>&lt;Application.Resources&gt;
    &lt;!-- Application resource dictionary --&gt;
    &lt;ResourceDictionary&gt;
        &lt;Color x:Key=""BackgroundGlobal""&gt;#ff333333&lt;/Color&gt;
        &lt;Color x:Key=""MidGradient""&gt;#ff0d0d0d&lt;/Color&gt;
        &lt;Color x:Key=""BottomGradient""&gt;Black&lt;/Color&gt;
        &lt;Color x:Key=""MenuTextColor""&gt;Azure&lt;/Color&gt;
        &lt;Style TargetType=""ImageCell"" x:Key=""Clicky""&gt;
            &lt;Setter Property=""TextColor"" Value=""{StaticResource  MenuTextColor}""/&gt;
            &lt;Setter Property=""DetailColor"" Value=""Aqua""/&gt;
        &lt;/Style&gt;
    &lt;/ResourceDictionary&gt;
&lt;/Application.Resources&gt;
</code></pre>

<p>within the Xamarin.Forms.Droid Resource\Values\strings.xml</p>

<pre><code>    &lt;?xml version=""1.0"" encoding=""utf-8"" ?&gt;
    &lt;resources&gt;
        &lt;style name=""MainTheme"" parent=""MainTheme.Base""&gt;
        &lt;/style&gt;

        &lt;!-- Base theme applied no matter what API --&gt;
        &lt;style name=""MainTheme.Base"" parent=""Theme.AppCompat""&gt;
            &lt;!--If you are using revision 22.1 please use just windowNoTitle. Without android:--&gt;
            &lt;item name=""windowNoTitle""&gt;true&lt;/item&gt;
            &lt;!--We will be using the toolbar so no need to show ActionBar--&gt;
            &lt;item name=""windowActionBar""&gt;false&lt;/item&gt;
            &lt;!-- Set theme colors from http://www.google.com/design/spec/style/color.html#color-color-palette--&gt;
            &lt;!-- colorPrimary is used for the default action bar background --&gt;
            &lt;item name=""colorPrimary""&gt;#2196F3&lt;/item&gt;
            &lt;!-- colorPrimaryDark is used for the status bar --&gt;
            &lt;item name=""colorPrimaryDark""&gt;#1976D2&lt;/item&gt;
            &lt;!-- colorAccent is used as the default value for colorControlActivated
     which is used to tint widgets --&gt;
            &lt;item name=""colorAccent""&gt;#FF4081&lt;/item&gt;
            &lt;!-- You can also set colorControlNormal, colorControlActivated
     colorControlHighlight and colorSwitchThumbNormal. --&gt;
            &lt;item name=""windowActionModeOverlay""&gt;true&lt;/item&gt;
            &lt;item name=""android:datePickerDialogTheme""&gt;@style/AppCompatDialogStyle&lt;/item&gt;
       &lt;/style&gt;   
       &lt;style name=""AppCompatDialogStyle"" parent=""Theme.AppCompat.Light.Dialog""&gt;
            &lt;item name=""colorAccent""&gt;#FF4081&lt;/item&gt;
       &lt;/style&gt;
   &lt;/resources&gt;
</code></pre>

<p>I currently get the following:</p>

<pre><code>Severity    Code    Description Project File    Line    Suppression State Error 
Error: No resource found that matches the given name (at 'theme' with value '@style/MainTheme').    Xamarin.Forms.Droid.Tests   C:\dev\git\example\Xamarin.Forms.Droid.Tests\obj\Debug\android\manifest\AndroidManifest.xml 9   
</code></pre>
",https://stackoverflow.com/questions/45000812/unit-testing-a-xamarin-forms-android-specific-code-project,"['c#', 'unit-testing', 'xamarin.android', 'xamarin.forms']",424,TRUE,0,1
Mocking service module Variables dependencies for Angular unit testing,"<p>I have an angular service that I am writing unit tests for and one of the methods I am testing uses module variables from external dependencies that I am mocking and injecting in a BeforeEach before the test is run. These variables are either just standard arrays or JSON and in the original function, they are accessed based off the outputs off service dependency methods.</p>

<p>I've mocked the methods using jasmine createSpy and callFake and I tried mocking the values of these variables in the same way but they are coming back as undefined and the test fails as a result.</p>

<p>What would be the best approach to mock the values of these variables?</p>

<p>The variables are defined for example like this:</p>

<pre><code>var module = {
   variableOne= [ a, b , c];
   variableTwo = {1, 2, 3};
};
</code></pre>

<p>and then the service method that I am testing calls them by eg:</p>

<pre><code>DependentService.variableOne[outputOfMockedDependencyMethod];
</code></pre>
",https://stackoverflow.com/questions/46098004/mocking-service-module-variables-dependencies-for-angular-unit-testing,"['angular', 'unit-testing', 'variables', 'service', 'mocking']",2167,TRUE,0,1
How to test functions for equality when unit testing,"<p>I have the following code:</p>

<pre><code>DeviceEventEmitter.addListener(eventName, () =&gt; { return 'myHandler' })
</code></pre>

<p>I am testing that <code>DeviceEventEmitter</code> is called with the following test:</p>

<pre><code>DeviceEventEmitter.addListener = jest.fn();
expect(DeviceEventEmitter.addListener.mock.calls[0][1]).toEqual(() =&gt; { return 'myHandler' });
</code></pre>

<p>However, the test fails with:</p>

<pre><code>expect(received).toEqual(expected)

Expected value to equal:
  [Function anonymous]
Received:
  [Function anonymous]
</code></pre>

<p>It looks like it doesn't understand that the functions are the same.</p>

<p>So how can I make it detect when the functions are the same?</p>
",https://stackoverflow.com/questions/47351091/how-to-test-functions-for-equality-when-unit-testing,"['javascript', 'reactjs', 'jestjs']",1731,TRUE,0,1
Unit testing only controller file instead of express framework,"<p>I am trying to unit test my controller file that handles a particular request. I do not want to test express as we have another mechanism for testing our Apis. I am stubbing the data using sinon. But the response is not what I am expecting.. I am always getting back a 200 status instead of the 201 that I am supposed to receive. Am I missing out on any specific part? I am using Typescript and mocha</p>

<p>my spec.ts file is </p>

<pre><code>import {expect} from 'chai';
import {HiringCompanyJobHandler} from 
""../../source/Handlers/HiringCompanyJobHandler"";
import * as httpMocks from 'node-mocks-http';
import * as sinon from 'sinon';
import Jobs from ""../../source/DAL/model/job"";
import * as mongoose from 'mongoose';
import {Response, Request, Express} from 'express';


describe(""Hiring Company Job Handler Unit Test Cases"", () =&gt; {
let request = null;
let response = null;

beforeEach(function () {
    response = httpMocks.createResponse();
});

it(""Should return the job details that belong to a particular company"", (done) =&gt; {
    request = {
        query: {
            UserName: 'HiringCompany',
            CompanyID: '1'
        }
    };

    let expectedJobs = [
        {
            'hiringCompanyId': '1',
            'companyJobId': 'T1',
            'jobName': 'Plumber',
            'jobType': 'Permanent'
        }, {
            'hiringCompanyId': '1',
            'companyJobId': 'T2',
            'jobName': 'Electrician',
            'jobType': 'Temporary'
        }
    ];

    sinon.mock(Jobs)
        .expects('find')
        .resolves(expectedJobs);

    let hiringCompanyJobHandler = new HiringCompanyJobHandler();
    hiringCompanyJobHandler.GetBasicJobInformationForHiringCompany(request, response);

    expect(response.statusCode).to.equal(201);        
    done();

})
});
</code></pre>

<p>My controller code is as follows</p>

<pre><code>import { NextFunction, Request, Response } from ""express"";
import { isNullOrUndefined } from ""util"";
import JobDal from ""../DAL/jobdal"";


export class HiringCompanyJobHandler {
constructor() {

}

public GetBasicJobInformationForHiringCompany(req: Request, res: Response) {
    let userName = req.query.UserName;
    let companyID = req.query.CompanyID;
    let status = req.query.status;
    let jobDal = new JobDal();
    jobDal.GetHiringCompanyJobDetails(companyID,status).then((details) =&gt; {
        if (details.length &gt; 0) {
            res.status(201).send({ details });
        }else {
            res.status(200).send({ status: ""No jobs found!"" });
        }
    }).catch((error: any) =&gt; {
        console.log(error);
        res.status(500).send(error);
    });
}
</code></pre>

<p>}</p>

<pre><code>export default new HiringCompanyJobHandler();
</code></pre>
",https://stackoverflow.com/questions/47264456/unit-testing-only-controller-file-instead-of-express-framework,"['node.js', 'unit-testing', 'typescript', 'mocha.js']",475,TRUE,0,1
Angular Unit Testing : Cannot read property &#39;findIndex&#39; of undefined,"<p>Am implementing an unit test for my Component .</p>

<p>i imported everything necessary :  services , RouterModuleTesting ,FormsModule HttpModule ... </p>

<p>but i still confronting a strange error :</p>

<p><strong>My Test file :</strong></p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { CustomerDetailComponent } from './customer-detail.component';

import {DxProgressBarModule} from 'devextreme-angular';
import {RouterTestingModule} from '@angular/router/testing';

import { CustomerService } from './../customer.service';
import {HttpService} from '../../../shared/service/http.service';

import {HttpModule} from '@angular/http';
import {FormsModule} from '@angular/forms';

describe('CustomerDetailComponent', () =&gt; {
  let component: CustomerDetailComponent;
  let fixture: ComponentFixture&lt;CustomerDetailComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        HttpModule,
        FormsModule,
        DxProgressBarModule,
        RouterTestingModule,
      ],
      providers:    [ CustomerService , HttpService ],
      declarations: [ CustomerDetailComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(CustomerDetailComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('Customer-detail component should be well defined', () =&gt; {
    expect(component).toBeDefined();
  });
});
</code></pre>

<p><strong>My component.ts</strong></p>

<pre><code>import { Component, OnInit } from '@angular/core';
import { Response, Http } from '@angular/Http';
import { Router, ActivatedRoute, Params } from '@angular/router';

import { HttpService } from './../../../shared/service';
import { Customer } from './../../../model';
import { CustomerService } from './../customer.service';

@Component({
    selector: 'app-customer-detail',
    templateUrl: './customer-detail.component.html',
    styleUrls: ['./customer-detail.component.css']
})
export class CustomerDetailComponent implements OnInit {
    customer: Customer;
    customersList: Customer[];
    error: string;
    idPrevious: number;
    idNext: number;

    constructor(
        private http: HttpService,
        private router: Router,
        private activatedRoute: ActivatedRoute,
        private customerService: CustomerService
    ) {
        this.customerService.getCustomersList().subscribe(
            (customers: Customer[]) =&gt; this.customersList = customers,
            (error: Response) =&gt; this.error = error.json()
        );

        const idCustomer: number = parseInt(activatedRoute.snapshot.params['idCustomer'], null);

        /* La 2ième instruction ne sert à rien sur le principe mais si F5 alors error sur find undefined */
        if (activatedRoute.snapshot.params['idCustomer']) {
            // Récupération de la liste de clients
            this.customerService.getCustomersList().subscribe(
                (customersList: Customer[]) =&gt; {
                    this.customersList = customersList;
                    this.prepareVariable();
                },
                (error: Response) =&gt; this.error = error.json()
            );
        } else {
            this.customer = new Customer();
        }
    }

    createOrUpdate(): void {
        this.http.put(this.http.wsCustomer.concat('createOrEdit'), this.customer).subscribe(
            () =&gt; {
                this.customerService.customersList = null;
                this.error = null; // Pour effacer le message d'erreur de l'appel précédent
                if (this.customer.id == null) {
                    this.customer = new Customer();
                } else {
                    this.router.navigate(['/customers-list']);
                }
            },
            (error: Response) =&gt; this.error = error.json()
        );
    }

    // Quand les paramètres d'un chemin changent, le composant n'est pas réinitialisé.
    // Donc il faut s'abonner au changement de param et refaire le traitement.
    ngOnInit() {
        this.activatedRoute.params.subscribe((params: Params) =&gt; {
            this.prepareVariable();
        });
    }

    private prepareVariable(): void {
        const indexCustomer: number = this.customersList.findIndex(
            customer =&gt; customer.id === parseInt(this.activatedRoute.snapshot.params['idCustomer'], null)
        );
        this.customer = this.customersList[indexCustomer];
        this.idPrevious = this.customersList[indexCustomer - 1] != null
            ? this.customersList[indexCustomer - 1].id
            : this.customersList[this.customersList.length - 1].id;
        this.idNext = this.customersList[indexCustomer + 1] != null
            ? this.customersList[indexCustomer + 1].id
            : this.customersList[0].id;
    }
}
</code></pre>

<p>The error is the following : </p>

<pre><code>TypeError: Cannot read property 'findIndex' of undefined
    at CustomerDetailComponent.Array.concat.CustomerDetailComponent.prepareVariable (webpack:///src/app/customer/customer-detail/customer-detail.component.ts:73:57 &lt;- src/test.ts:233183:47)
    at SafeSubscriber._next (webpack:///src/app/customer/customer-detail/customer-detail.component.ts:68:17 &lt;- src/test.ts:233178:19)
    at SafeSubscriber.Array.concat.SafeSubscriber.__tryOrSetError (webpack:///~/rxjs/Subscriber.js:247:0 &lt;- src/test.ts:18017:16)
    at SafeSubscriber.Array.concat.SafeSubscriber.next (webpack:///~/rxjs/Subscriber.js:187:0 &lt;- src/test.ts:17957:27)
    at Subscriber.Array.concat.Subscriber._next (webpack:///~/rxjs/Subscriber.js:125:0 &lt;- src/test.ts:17895:26)
    at Subscriber.Array.concat.Subscriber.next (webpack:///~/rxjs/Subscriber.js:89:0 &lt;- src/test.ts:17859:18)
    at BehaviorSubject.Array.concat.BehaviorSubject._subscribe (webpack:///~/rxjs/BehaviorSubject.js:28:0 &lt;- src/test.ts:114179:24)
    at BehaviorSubject.Array.concat.Observable._trySubscribe (webpack:///~/rxjs/Observable.js:171:0 &lt;- src/test.ts:15883:25)
    at BehaviorSubject.Array.concat.Subject._trySubscribe (webpack:///~/rxjs/Subject.js:97:0 &lt;- src/test.ts:29682:51)
    at BehaviorSubject.Array.concat.Observable.subscribe (webpack:///~/rxjs/Observable.js:159:0 &lt;- src/test.ts:15871:65)
</code></pre>

<p>Even if that i know that i'm using my reals services , not stubs (what i would do ) but i don't know from what that error occurs exactly.</p>

<p><strong>Suggestions ?</strong> </p>
",https://stackoverflow.com/questions/45506930/angular-unit-testing-cannot-read-property-findindex-of-undefined,"['angular', 'unit-testing', 'typescript', 'jasmine', 'karma-jasmine']",1704,FALSE,0,0
How to mock request-promise-native for NodeJS unit testing?,"<p>My NodeJS application uses request-promise-native. </p>

<pre><code>import request from 'request-promise-native'
const https = require('https')

const myRequest = request.defaults({
  baseUrl: 'myBaseUrl',
  agent: new https.Agent({ keepAlive: true })
})

async function findResults() {
  const myResponse = await myRequest.get({
      uri: '/myUri'
  })
  return myResponse
}
</code></pre>

<p>I am trying to mock 'get' of the above request for unit testing. But it still makes the actual call and gets the results, not going through my mock object call.</p>

<p>I tried different variations, using Sinon:</p>

<pre><code>import test from 'ava'
import sinon from 'sinon'
import Bluebird from 'bluebird'
import request from 'request-promise-native'
import { findResults } from '../services/results'

test.only(async t =&gt; {
  let response = JSON.stringify({
     statusCode: 504
  })

  sinon.stub(request, 'get').returns(Bluebird.resolve(response))

  const returnValue = await findResults()
  console.log('return: ', returnValue)

  t.is (1, 1)
})
</code></pre>

<p>Using Mockery (per the documentation <a href=""https://www.npmjs.com/package/request-promise"" rel=""noreferrer"">https://www.npmjs.com/package/request-promise</a>)</p>

<pre><code>import mockery from 'mockery'
import { findResults } from '../services/results'

test.before(async t =&gt; {
    mockery.enable({
      warnOnReplace: false,
      warnOnUnregistered: false,
      useCleanCache: true
    })

  mockery.registerMock('request-promise-native', function () {
  // var response = fs.readFileSync(__dirname + '/data/' + filename, 'utf8');
    let response = JSON.stringify({
        statusCode: 9
    })
   return Bluebird.resolve(response.trim());
  })
})

test.after(async t =&gt; {
   mockery.disable()
   mockery.deregisterAll()
   // done()
})

test.only(async t =&gt; {
   const returnValue = await findResults()
   console.log('return: ', returnValue)

   t.is(1, 1)
})
</code></pre>

<p>I have also tried variations of proxyquire and sinon's fake server. But I couldn't get them to work.</p>

<p>Any suggestions?</p>
",https://stackoverflow.com/questions/46655592/how-to-mock-request-promise-native-for-nodejs-unit-testing,"['node.js', 'unit-testing', 'sinon', 'ava']",9062,TRUE,5,2
"Python 3 unit-testing, create mock of singleton class function","<p>I'm working on creating unittests for my project.</p>

<p>I have a class called TimerHandler that needs to be tested. This class uses a class called AudioHandler. Both of these classes are singletons. see code below.</p>

<p>timer_handler.py</p>

<pre><code>class TimerHandler(metaclass=Singleton):

    def play(self):
        # some code that needs to be tested

        AudioHandler().start()
</code></pre>

<p>audio_handler.py</p>

<pre><code>class AudioHandler(metaclass=Singleton):

    def start(self):
        # some code that connects with an audio device
</code></pre>

<p>I'm trying to mock the start method of AudioHandler so it will just return None and won't try to connect to an audio device. The unittest looks like this:</p>

<pre><code>@patch.object(AudioHandler, 'start', return_value=None)
def test_play_pause(self, start):

    self.timer_handler.play()
</code></pre>

<p>The problem is that it is still running the code in the original start function in AudioHandler.</p>

<p>How can I write a test function that removes/mocks the functionality of the start function in AudioHandler?</p>

<p>Thanks in advance</p>
",https://stackoverflow.com/questions/44701134/python-3-unit-testing-create-mock-of-singleton-class-function,"['python', 'python-3.x', 'unit-testing', 'mocking']",1302,FALSE,5,1
Unit testing a method which is inside an Android Activity,"<p>I don't know if it has been answered or not, I found some similar questions but the answers are not making any sense to me. So, I am asking it again. </p>

<p><strong>How can we test a method which is inside an activity.</strong></p>

<pre><code>public class MyActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       //inflate layout        
   }

   public int someMethod() {
       //perform some logic and return an integer
   }

}
</code></pre>

<p>I want to unit test the method <code>someMethod</code> but how can I do this as I cannot create an instance of the activity and directly call that method. The method under test does not use any android component so I dont want to use Roboelectric or any other such libraries or tools. It is a plain java method.</p>

<p>One way I know is to move the method to another class and have that class unit tested and I am perfectly fine with it, but I wanted to know if that is the right way, (create a separate class just for this purpose), or is there any other way to do it?</p>

<p>Thank you for any feedback.</p>
",https://stackoverflow.com/questions/46439558/unit-testing-a-method-which-is-inside-an-android-activity,"['java', 'android', 'unit-testing']",2782,TRUE,5,1
How to mock Vue Mixins during unit testing using vue-test-utils and jest?,"<p>I have read the documentation for <a href=""https://v1.test-utils.vuejs.org/"" rel=""nofollow noreferrer""><code>vue-test-utils</code></a> and Jest, but I am still unsure about how to properly mock Vue mixins in a Vue component and test the component.</p>
",https://stackoverflow.com/questions/47329261/how-to-mock-vue-mixins-during-unit-testing-using-vue-test-utils-and-jest,"['javascript', 'vue.js', 'unit-testing', 'jestjs', 'mixins']",22576,TRUE,29,3
How to write unit testing for router.url in angular 2,"<p>Please help to write unit testing on router.url usging angular 2. Please have a look at the below code to understand my query.</p>

<pre><code>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
    selector: 'app-about',
    templateUrl: './app-about.component.html',
    styleUrls: ['./app-about.component.scss']
})
export class AboutComponent implements OnInit {
    constructor(private router: Router) {
        if (this.router.url.includes('home')) {
            ...some functions
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/47332956/how-to-write-unit-testing-for-router-url-in-angular-2,['angular2-routing'],1594,FALSE,5,1
Loading existing HTML file with JSDOM for frontend unit testing,"<p>I'm new to unit testing, and I'm aware my tests may not be valuable or following a specific best practice, but I'm focused on getting this working, which will allow me to test my frontend code using JSDOM.</p>

<pre><code>const { JSDOM } = require('jsdom');
const { describe, it, beforeEach } = require('mocha');
const { expect } = require('chai');

let checkboxes;
const options = {
  contentType: 'text/html',
};

describe('component.js', () =&gt; {
  beforeEach(() =&gt; {
    JSDOM.fromFile('/Users/johnsoct/Dropbox/Development/andybeverlyschool/dist/individual.html', options).then((dom) =&gt; {
      checkboxes = dom.window.document.querySelectorAll('.checkbox');
    });
  });
  describe('checkboxes', () =&gt; {
    it('Checkboxes should be an array', () =&gt; {
      expect(checkboxes).to.be.a('array');
    });
  });
});
</code></pre>

<p>I'm getting the error ""AssertionError: expected undefined to be an array"". I'm simply using the array test as a test to ensure I have JSDOM functioning correctly. There are no other errors occurring. Any help would be much appreciated!</p>
",https://stackoverflow.com/questions/45945798/loading-existing-html-file-with-jsdom-for-frontend-unit-testing,"['javascript', 'unit-testing', 'mocha.js', 'chai', 'jsdom']",7686,TRUE,5,1
Unit testing firebase functions: how to stub firebase-admin sdk,"<p>In index.js, I have the following</p>

<pre><code>exports.write = functions.https.onRequest((req, res) =&gt; {
    admin.database()
        .ref(`xxx/yyy`)
        .push()
        .set({timestamp: admin.database.ServerValue.TIMESTAMP});
    res.status(200).end();
});
</code></pre>

<p>In my test.js, I stub admin.database() as follows:</p>

<pre><code>const refStub = sinon.stub();
setStub = sinon.stub();
refStub.withArgs('xxx/yyy').returns({push: () =&gt; ({key: 'fakeKey', set: setStub})});
databaseStub = sinon.stub(admin, 'database').get(() =&gt; {
    return () =&gt; {
      return {ref: refStub};
    };
  });
</code></pre>

<p>When I run my test, I get the following error <code>TypeError: Cannot read property 'TIMESTAMP' of undefined</code>.  How do I fix this error or stub the call to <code>admin.database.ServerValue.TIMESTAMP</code>? Thanks.</p>
",https://stackoverflow.com/questions/47939456/unit-testing-firebase-functions-how-to-stub-firebase-admin-sdk,"['javascript', 'unit-testing', 'firebase', 'firebase-realtime-database', 'sinon']",1376,TRUE,5,2
"React unit testing, cannot read &#39;push&#39; of undefined react router","<p>I have a component that uses react router like so:</p>

<pre><code>_viewCompany(companyId) {
    this.context.router.push(`/admin/companies/${companyId}`);
}
</code></pre>

<p>It works great in the component, but while writing tests for the component I ran into an error. Here is the test causing the issue (I am using enzyme, jest, sinon):</p>

<pre><code>    it('should call _viewCompany', () =&gt; {
        jest.spyOn(CompaniesList.prototype, '_viewCompany');
        wrapper = mount(&lt;CompaniesList {...props}/&gt;);
        const viewButton = wrapper.find('.btn-info').at(0);
        viewButton.simulate('click');
        expect(CompaniesList.prototype._viewCompany).toHaveBeenCalled();
    });
</code></pre>

<p>This test returns an error saying the following: </p>

<p><code>Cannot read property 'push' of undefined</code></p>

<p>Is there something I can do to mock it or create an empty function for the tests?</p>
",https://stackoverflow.com/questions/42704261/react-unit-testing-cannot-read-push-of-undefined-react-router,"['reactjs', 'unit-testing', 'jestjs', 'enzyme']",2520,FALSE,4,1
Unit testing Express/Mongoose app routes without hitting the database,"<p>I have read the following posts on Stack Overflow:</p>

<p><a href=""https://stackoverflow.com/questions/19284207/unit-test-with-mongoose"">Unit Test with Mongoose</a></p>

<p><a href=""https://stackoverflow.com/questions/33270667/mocking-stubbing-mongoose-model-save-method"">Mocking/stubbing Mongoose model save method</a></p>

<p>I have also looked into mockgoose but I would prefer to use testdouble or sinon to stub/mock my database calls.</p>

<p>The information found <a href=""https://codeutopia.net/blog/2016/06/10/mongoose-models-and-unit-tests-the-definitive-guide/"" rel=""noreferrer"">here</a> is probably what comes closest to what I would like to do. But I can't quite wrap my head around it. The difference, I think, is that I'm trying to test a route in my api and not the Mongoose model directly. Here is my code:</p>

<p>server.ts</p>

<pre><code>import * as express from 'express';
const app = express()
import { createServer } from 'http';
const server = createServer(app);
import * as ioModule from 'socket.io';
const io = ioModule(server);


import * as path from 'path';
import * as bodyParser from 'body-parser';
import * as helmet from 'helmet';
import * as compression from 'compression';
import * as morgan from 'morgan';

// Database connection
import './server/db';

// Get our API routes and socket handler
import { api } from './server/routes/api'
import { socketHandler } from './server/socket/socket';

// Helmet security middleware
app.use(helmet());

// Gzip compression middleware
app.use(compression());

// Morgan logging middleware
app.use(morgan('common'));

// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));

// Set our api routes
app.use('/api', api);

// Catch all other routes and return the index file
app.get('*', (req: any, res: any) =&gt; {
    res.sendFile(path.join(__dirname, 'dist/index.html'));
});

/**
 * Get port from environment and store in Express.
 */
const port = process.env.PORT || '3000';
app.set('port', port);


/**
 * Listen on provided port, on all network interfaces.
 */
server.listen(port, () =&gt; console.log(`API running on localhost:${port}`));

io.on('connection', socketHandler);

export { server };
</code></pre>

<p>/server/db.ts</p>

<pre><code>import * as mongoose from 'mongoose';
// Enter database URL and delete this comment
const devDbUrl = 'mongodb://localhost:27017/book-trade';
const prodDbUrl = process.env.MONGOLAB_URI;

const dbUrl = devDbUrl || prodDbUrl;

mongoose.connect(dbUrl);

(&lt;any&gt;mongoose).Promise = global.Promise;

mongoose.connection.on('connected', () =&gt; {
    console.log('Mongoose connected to ' + dbUrl);
});

mongoose.connection.on('disconnected', () =&gt; {
    console.log('Mongoose disconnected');
});

mongoose.connection.on('error', (err: any) =&gt; {
    console.log('Mongoose connection error' + err);
});

process.on('SIGINT', () =&gt; {
    mongoose.connection.close(() =&gt; {
        console.log('Mongoose disconnected through app termination (SIGINT)');
        process.exit(0);
    });
});

process.on('SIGTERM', () =&gt; {
    mongoose.connection.close(() =&gt; {
        console.log('Mongoose disconnected through app termination (SIGTERM)');
        process.exit(0);
    });
});

process.once('SIGUSR2', () =&gt; {
    mongoose.connection.close(() =&gt; {
        console.log('Mongoose disconnected through app termination (SIGUSR2)');
        process.kill(process.pid, 'SIGUSR2');
    });
});
</code></pre>

<p>/server/models/user.ts</p>

<pre><code>import * as mongoose from 'mongoose';
const Schema = mongoose.Schema;
const mongooseUniqueValidator = require('mongoose-unique-validator');

export interface IUser extends mongoose.Document {
    firstName: string,
    lastName: string,
    city: string,
    state: string,
    password: string,
    email: string,

    books: Array&lt;{
        book: any, 
        onLoan: boolean, 
        loanedTo: any 
    }&gt;
}

const schema = new Schema({
    firstName: { type: String, required: true },
    lastName: { type: String, required: true },
    city: { type: String, required: true },
    state: { type: String, required: true },
    password: { type: String, required: true },
    email: { type: String, required: true, unique: true },

    books: [{ 
        book: { type: Schema.Types.ObjectId, ref: 'Book', required: true},
        onLoan: { type: Boolean, required: true },
        loanedTo: { type: Schema.Types.ObjectId, ref: 'User'}
    }]
});

schema.plugin(mongooseUniqueValidator);

export const User = mongoose.model&lt;IUser&gt;('User', schema);
</code></pre>

<p>/server/routes/api.ts</p>

<pre><code>import * as express from 'express';
const router = express.Router();

import { userRoutes } from './user';


/* GET api listing. */
router.use('/user', userRoutes);

export { router as api };
</code></pre>

<p>/server/routes/user.ts</p>

<pre><code>import * as express from 'express';
const router = express.Router();
import * as bcrypt from 'bcryptjs';

import { User } from '../models/user';

router.post('/', function (req, res, next) {
    bcrypt.hash(req.body.password, 10)
        .then((hash) =&gt; {
            const user = new User({
                firstName: req.body.firstName,
                lastName: req.body.lastName,
                city: req.body.city,
                state: req.body.state,
                password: hash,
                email: req.body.email
            });
            return user.save();
        })
        .then((user) =&gt; {
            res.status(201).json({
                message: 'User created',
                obj: user
            });
        })
        .catch((error) =&gt; {
            res.status(500).json({
                title: 'An error occured',
                error: error
            });
        });
});
</code></pre>

<p>/server/routes/user.spec.ts</p>

<pre><code>import * as request from 'supertest';
import * as td from 'testdouble';
import { server } from '../../server';
import { finishTest } from '../../spec/helpers/suptertest';


describe('user route', function () {
  let app: any;
  beforeEach(function () {
    app = server;
  });
  afterEach(function (done) {
    app.close(done);
  });
  it('creates a user /', (done) =&gt; {
    //make request
    request(app)
      .post('/api/user')
      .send({
        firstName: 'Philippe',
        lastName: 'Vaillancourt',
        city: 'Laval',
        state: 'Qc',
        password: 'test',
        email: 'test@test.com',
      })
      .expect(201, finishTest(done));
  });

});
</code></pre>

<p>I use supertest to fake the requests and use Jasmine as a test framework and runner.</p>

<p>My question: What do I need to change in my spec file in order to get this test to bypass making a call to the database and instead use stubs or mocks?</p>
",https://stackoverflow.com/questions/45023344/unit-testing-express-mongoose-app-routes-without-hitting-the-database,"['node.js', 'unit-testing', 'express', 'mongoose', 'mocking']",8242,TRUE,5,3
Android RecyclerView Adapter Item count is returning 0 on unit testing,"<p>I am trying to test RecyclerView with AndroidJunit4, it is my test code:</p>

<pre><code>@Rule
    public ActivityTestRule&lt;ProductListActivity&gt; rule  = new  ActivityTestRule&lt;&gt;(ProductListActivity.class);

............................
..........................

@Test
    public void ensureDataIsLoadingOnSuccess() throws Exception {
        ProductListActivity activity = rule.getActivity();
        ...........................
        ............

        activity.runOnUiThread(new Runnable() {
        public void run() {
            activity.displayProducts(asList(product1, product2), 0);
        }
    });

        assertEquals(2, mAdapter.getItemCount());
        assertThat(((ProductAdapter) mAdapter).getItemAtPosition(0),sameInstance(product1));
        assertThat(((ProductAdapter) mAdapter).getItemAtPosition(1),sameInstance(product2));


    }
</code></pre>

<p>Here is my code for displayProducts() in Activity:</p>

<pre><code>@Override
    public void displayProducts(List&lt;Product&gt; products, Integer pageNo) {
        progressBar.setVisibility(View.GONE);
        if (pageNo == 0 &amp;&amp; products.size() == 0) {
            noProductTextView.setVisibility(View.VISIBLE);
        } else {
            mProductAdapter.addProduct(products);
            noProductTextView.setVisibility(View.GONE);
            productListView.setVisibility(View.VISIBLE);
        }
    }
</code></pre>

<p>It is giving error like: </p>

<pre><code>junit.framework.AssertionFailedError: expected:&lt;2&gt; but was:&lt;0&gt;
at junit.framework.Assert.fail(Assert.java:50)
at junit.framework.Assert.failNotEquals(Assert.java:287)
at junit.framework.Assert.assertEquals(Assert.java:67)
at junit.framework.Assert.assertEquals(Assert.java:199)
at junit.framework.Assert.assertEquals(Assert.java:205)
at com.kaushik.myredmart.ui.ProductListActivityTest.ensureDataIsLoadingOnSuccess(ProductListActivityTest.java:94)
</code></pre>

<p>Please help what is the problem in my code?</p>
",https://stackoverflow.com/questions/43898456/android-recyclerview-adapter-item-count-is-returning-0-on-unit-testing,"['android', 'unit-testing', 'android-adapter', 'android-junit']",1324,FALSE,10,2
Angular 2 unit testing &quot;Cannot read property &#39;unsubscribe&#39; of undefined&quot;,"<p>I have sample TestComp with ngOnInit and ngOnDestroy methods and ActivatedRoute subscription.</p>

<pre><code>@Component({
    selector: 'test',
    template: '',
})
export class TestComp implements OnInit, OnDestroy {

    constructor (
        private route: ActivatedRoute
    ) {
    }

    ngOnInit() {
        this.subscription = this.route.data
            .subscribe(data =&gt; {
                console.log('data', data.name);
            })
        ;
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}
</code></pre>

<p>I am getting ""Cannot read property 'unsubscribe' of undefined"" when I call ngOnDestroy method from spec file (or when I am running multiple tests).</p>

<p>My spec file: </p>

<pre><code>describe('TestComp', () =&gt; {
    let comp: TestComp;
  let fixture: ComponentFixture&lt;TestComp&gt;;

  beforeEach(async(() =&gt; {
    TestBed
    .configureTestingModule({
      declarations: [TestComp],
      imports: [RouterTestingModule],
      providers: [
        {
        provide: ActivatedRoute,
        useValue: {
          data: {
            subscribe: (fn: (value: Data) =&gt; void) =&gt; fn({
              name: 'Stepan'
            })
          }
        }
      }
        // { //Also tried this
        //   provide: ActivatedRoute,
        //   useValue: {
        //     params: Observable.of({name: 'Stepan'})
        //   }
        // }
      ]
    })
    .compileComponents()
    .then(() =&gt; {
          fixture = TestBed.createComponent(TestComp);        
          fixture.detectChanges();
    })
    }));

  it('TestComp successfully initialized', () =&gt; {
    fixture.componentInstance.ngOnInit();
    expect(fixture.componentInstance).toBeDefined()
    fixture.componentInstance.ngOnDestroy();
  });
});
</code></pre>

<p>I am passing ActivatedRoute value based on answers <a href=""https://stackoverflow.com/questions/38356084/how-to-unit-test-a-component-that-depends-on-parameters-from-activatedroute"">here</a>, but I am getting error. So my question is - what should I pass as ActivatedRoute to make it possible to subscribe and unsubscribe? 
<a href=""https://plnkr.co/edit/lev5qsBiyob4zFYN3g1a?p=preview"" rel=""nofollow noreferrer"">Example Plunker</a>.</p>
",https://stackoverflow.com/questions/42153464/angular-2-unit-testing-cannot-read-property-unsubscribe-of-undefined,"['javascript', 'unit-testing', 'angular', 'karma-jasmine', 'angular-routing']",6663,TRUE,3,2
UnintentionalCodeFirstException | Entity Framework Unit Testing with Effort.Ef6 using Database First,"<h2>The situation</h2>

<p>I want to enable unit testing of my <a href=""https://msdn.microsoft.com/en-US/library/system.data.entity.dbcontext.aspx"" rel=""nofollow noreferrer""><code>DbContext</code></a> based on entity framework 6. I have created my <code>DbContext</code> and my models with the database first approach and now have an <em>.edmx</em> designer file.</p>

<h2>The problem</h2>

<p>My automatically created <code>DbContext</code> does override the <a href=""https://msdn.microsoft.com/en-US/library/system.data.entity.dbcontext.onmodelcreating.aspx"" rel=""nofollow noreferrer""><code>DbContext.OnModelCreating</code></a> method like this:</p>

<pre><code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    throw new UnintentionalCodeFirstException();
}
</code></pre>

<p>I am trying to create a new instance of my <code>DbContext</code> in my mocked data access service based on the information of <a href=""https://www.stevefenton.co.uk/2015/11/using-an-in-memory-database-as-a-test-double-with-entity-framework/"" rel=""nofollow noreferrer"">this article</a>. My code doesn't run into <code>Database.SetInitializer;</code> like the author of this blog post pointed out. My constructor looks exactly like his. My <code>DbContext</code> initialization looks like this:</p>

<pre><code>public DatabaseEntities(DbConnection connection) 
     : base(connection, true) { }
</code></pre>

<p>Which results in following exception when reaching the previously mentioned overridden <code>OnModelCreating</code></p>

<blockquote>
  <p><strong>System.Data.Entity.Infrastructure.UnintentionalCodeFirstException:</strong> 'The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development.  This will not work correctly. To fix this problem do not remove the line of code that throws this exception. If you wish to use Database First or Model First, then make sure that the Entity Framework connection string is included in the app.config or web.config of the start-up project. If you are creating your own DbConnection, then make sure that it is an EntityConnection and not some other type of DbConnection, and that you pass it to one of the base DbContext constructors that take a DbConnection. To learn more about Code First, Database First, and Model First see the Entity Framework documentation here: <a href=""http://go.microsoft.com/fwlink/?LinkId=394715"" rel=""nofollow noreferrer"">http://go.microsoft.com/fwlink/?LinkId=394715</a>'</p>
</blockquote>

<p>There are plenty of questions on stackoverflow which focus on unit testing with effort while using the database-first apporach, but no one seems to have similar problems like me.</p>

<h2>What I have already tried to do</h2>

<ul>
<li>Searching the internet a long time for a solution.</li>
<li>Uncomment the overridden <code>OnModelCreating()</code>.</li>
<li>I have already tried to apply <a href=""https://stackoverflow.com/a/34745579/1865613"">this solution</a> without success.</li>
<li>Mock my <code>DbContext</code> with <a href=""https://github.com/Moq/moq4/"" rel=""nofollow noreferrer"">Moq</a>, which is definitely not an option.</li>
</ul>

<h2>The question</h2>

<p>How can i create and use an in-memory database (with effort)?</p>

<hr>

<p><strong>Additional information</strong></p>

<p>When I uncomment the <code>OnModelCreating()</code>, an exception will be thrown at the first access to the DataContext. E.g.:</p>

<pre><code>DbConnection effortConnection = Effort.DbConnectionFactory.CreatePersistent(""MockedDatabaseEntities"");

using (DatabaseEntities dataContext = new DatabaseEntities(effortConnection))
{
    dataContext.Students.Count(); // Exception throws here
}
</code></pre>

<blockquote>
  <p><strong>System.Data.Entity.ModelConfiguration.ModelValidationException:</strong> 'One or more validation errors were detected during model generation:
  MyApplication.Shared.Model.KeyValuePair: : EntityType 'KeyValuePair' has no key defined. Define the key for this EntityType.
  KeyValuePairs: EntityType: EntitySet 'KeyValuePairs' is based on type 'KeyValuePair' that has no keys defined.'</p>
</blockquote>
",https://stackoverflow.com/questions/46172095/unintentionalcodefirstexception-entity-framework-unit-testing-with-effort-ef6,"['c#', 'entity-framework', 'unit-testing', 'entity-framework-6', 'effort']",3872,TRUE,3,2
Mocking Symfony Entities for Unit Testing using PHPUnit and Mockery,"<pre><code>public function reportsToBeRun()
{
    $reports = $this-&gt;repository-&gt;getReportsToBeRun();

    foreach ($reports as $report) {
        $report-&gt;setUpdated(new \DateTime());
    }

    return $reports;
}
</code></pre>

<p>I am learning test driven development in my new job and I am struggling with how I would test the above example. I make a call to a repository that uses <code>getResults()</code> and returns an array of entity objects. I can mock the repository fine, but I do not know what I am best to return here. I can mock the entities and return them, but then the <code>setUpdated</code> will not do anything. I can obviously mock <code>setUpdated</code>, but I do not know how to get it to update the mocked entity or entities. </p>

<p>My 2nd issue with this is the tests I am writing are not really testing anything. The repository call is being mocked and so is the setter. I am then just returning whatever I mocked. What would you recommend doing for a function like this.</p>
",https://stackoverflow.com/questions/42982836/mocking-symfony-entities-for-unit-testing-using-phpunit-and-mockery,"['php', 'doctrine', 'phpunit', 'mockery', 'symfony-2.8']",3607,TRUE,3,1
Unit testing a program which has no output by itself,"<p>I have been asked to test (unit testing stage) program 'B' which is called by program 'A', controls something then calls program 'C' which does have some output. 'B' has no output by itself.</p>

<p>My question is : Should I debug program 'B' in isolation and compare the communication area between 'B' and 'C' to what is expected ? </p>

<p>Or should I run program 'A' and compare output of 'C' to  what is expected ?</p>

<p>Thank you in advance.</p>
",https://stackoverflow.com/questions/42694229/unit-testing-a-program-which-has-no-output-by-itself,"['unit-testing', 'cobol']",417,FALSE,3,1
EntityFramework Core Unit Testing - SQLite in-memory mode vs. The InMemory provider,"<p>I am in a process of writing unit tests for a project that uses EntityFramework Core and according to the <a href=""https://learn.microsoft.com/en-us/ef/core/miscellaneous/testing/"" rel=""noreferrer"">docs</a> I can use <code>SQLite in-memory mode</code> or <code>The InMemory provider</code> to approximate the database context.<br/></p>

<p>The docs states that the <code>SQLite in-memory mode</code> behaves like a relational database and that <code>The InMemory provider</code> does not always behave like a relational database.<br/></p>

<p>As far as I understand the SQLite mode sounds better because it behaves like relational database while the InMemory provider does not, but I guess there is other aspects to consider otherwise noone will use <code>The InMemory provider</code> which sounds a lot worse.<br/></p>

<p>Is there other pros and cons to each approach I should consider before I choose which tool to use?</p>
",https://stackoverflow.com/questions/45162809/entityframework-core-unit-testing-sqlite-in-memory-mode-vs-the-inmemory-provi,"['c#', 'unit-testing', '.net-core', 'entity-framework-core']",2092,TRUE,15,3
Can&#39;t reference a project to run unit testing on it,"<p>I'm runnig through this <a href=""https://msdn.microsoft.com/en-us/library/ms182532.aspx"" rel=""nofollow noreferrer"">walkthrough</a> on the Microsoft website. I have gotten up to creating the Unit testing project, <a href=""https://msdn.microsoft.com/en-us/library/ms182532.aspx#Anchor_2"" rel=""nofollow noreferrer"">here</a>. I just cant seem to reference my project.</p>

<p>I right click on references in my Solution Explorer.</p>

<p><a href=""https://i.stack.imgur.com/BkNzH.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/BkNzH.png"" alt=""Right CLick""></a></p>

<p>Then I go to solution under the projects tab. </p>

<p><a href=""https://i.stack.imgur.com/RsEnI.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/RsEnI.png"" alt=""Reference Tab""></a></p>

<p>If I choose the browse I don't know what to find.</p>

<p><a href=""https://i.stack.imgur.com/VlRIQ.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/VlRIQ.png"" alt=""What to find""></a></p>

<p><a href=""https://msdn.microsoft.com/en-us/library/7314433t(v=vs.90).aspx"" rel=""nofollow noreferrer"">This</a> was no help. Along with other links that I searched.</p>

<p>I just don't know what to do at this point? What am I supposed to look for when browsing to reference my project?</p>

<p>To answer Ayb4btu  question. My folder looks like this</p>

<pre><code>UnitTest //Top folder
    Bank //Bank project to be tested
    BankTest //Bank Unit Test project
</code></pre>
",https://stackoverflow.com/questions/45657261/cant-reference-a-project-to-run-unit-testing-on-it,"['c#', 'unit-testing']",2552,TRUE,3,1
React unit testing -&gt; simulate click on child to invoke method,"<p>Say I implemented a simple pexeso game in react (<a href=""http://dkmgames.com/Memory/pairsrun.php"" rel=""nofollow noreferrer"">for those who do not know pexeso - this is a random pexeso example - not mine</a>).</p>

<p>For now it is important, that the game consists of one <strong>GameBoard</strong> component, in which display a large number of <strong>Card</strong> components.</p>

<p>The GameBoard component has as a state an array of currently flipped cards - <em>this.state.flipped_cards</em>.</p>

<p>Once a card is clicked, it invokes an inner function (forcing the card to flip). In this function, the GameBoard's handleCardFlip function is involved to determine the resulting game state.</p>

<p>The resulting JSX returned from the GameBoard looks something like this:</p>

<pre><code>&lt;div&gt;
  &lt;Card onClick={this.handleFlippedCard} name=""MistyRose"" /&gt;
  &lt;Card onClick={this.handleFlippedCard} name=""Olive"" /&gt;
  &lt;Card onClick={this.handleFlippedCard} name=""MistyRose"" /&gt;
  &lt;Card onClick={this.handleFlippedCard} name=""Olive"" /&gt;
&lt;/div&gt;

handleFlippedCard( flipped_card_text ) {
    if ( this.state.flipped_cards.length &lt; MAX_FLIPPED_CARDS ) {
        this.setState(
            {
                flipped_cards:
                this.state.flipped_cards.concat( [flipped_card_text] )
            },
            () =&gt; {
                __resolveGameState.bind( this )()
            }
        )
    }
} // handleFlippedCard
</code></pre>

<p>Now I want to write unit tests for my code. Currently I am using jest, enzyme and chai (I am getting a bit overwhelmed and am honestly getting really confused with all the crazy test engine names :)) ).</p>

<p>How do I simulate a click on the cards? I read something about spies and stubs, but did not really understand how/when to use them.</p>

<pre><code>it.only( 'Removes flipped cards if they match', () =&gt; {
        const board = shallow( &lt;GameBoard cardsInput={ cardsInput } /&gt; )
        // reveal first card
        board.setState( { 
            flipped_cards: 
                board.state( 'flipped_cards' ).concat( cardsInput[1] )
        } )

        // reveal second card
        board.setState( {
           flipped_cards: 
               board.state( 'flipped_cards' ).concat( cardsInput[3] )
        } )

        // thought the handleFlipped cards would get invoked here..

        expect( board.state( 'visible_cards' ).length ).to
                .equal( cardsInput.length-2 )
    } )
</code></pre>

<p>I will welcome any comments, I am very new to react.</p>
",https://stackoverflow.com/questions/42093126/react-unit-testing-simulate-click-on-child-to-invoke-method,"['unit-testing', 'reactjs', 'chai', 'enzyme']",1897,TRUE,3,1
Unit testing bash scripts that redirect file output in shUnit2,"<p>I am using shUnit2 to do unit testing in Bash shell scripts.</p>

<p>I have code like this:</p>

<pre><code>cat &gt; /etc/somefile &lt;&lt;EOF
some file content
EOF
</code></pre>

<p>I want to write unit tests to test this code, but to do that I would need to avoid the file I/O redirection.</p>

<p>I realise I could refactor the code to move the bits that redirect file output inside functions, e.g.</p>

<pre><code>cat_somefile() {
  cat &gt; /etc/somefile &lt;&lt;EOF
some file content
EOF
}
</code></pre>

<p>And then I could stub this function in my tests.</p>

<p>Is there any way to test this code without refactoring it though?</p>
",https://stackoverflow.com/questions/44870924/unit-testing-bash-scripts-that-redirect-file-output-in-shunit2,"['bash', 'unit-testing', 'shunit2']",518,TRUE,3,1
Unit Testing Using Sitecore.FakeDb Throws Sitecore.Nexus instantiation error on GetItem,"<p>I'm a sitecore developer and I want to use Sitecore.FakeDb in my unit testing.  I have the following code:</p>
<pre><code>[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void Test_ArticleController_With_SitecoreItem()
    {
        Sitecore.Data.ID about_us_itemId = Sitecore.Data.ID.NewID;
        Sitecore.Data.ID careers_itemId = Sitecore.Data.ID.NewID;

        using (var db = new Sitecore.FakeDb.Db
        {
            new Sitecore.FakeDb.DbItem(&quot;about-us&quot;, about_us_itemId)
            {
                new Sitecore.FakeDb.DbField(SitecoreFieldIds.WTW_REDIRECT_TO) { Value = &quot;/WTW-Home/about-us/overview&quot; }
            },
            new Sitecore.FakeDb.DbItem(&quot;careers&quot;, careers_itemId)
            {
                new Sitecore.FakeDb.DbField(SitecoreFieldIds.WTW_REDIRECT_TO) { Value = &quot;http://careers.willistowerswatson.com&quot; }
            }
        })
        {
            Sitecore.Data.Items.Item sampleItem3 = db.GetItem(about_us_itemId); // throws error
            Sitecore.Data.Items.Item sampleItem2 = db.GetItem(&quot;/sitecore/content/careers&quot;); //throws error

            //Assert
            Assert.AreEqual(&quot;abc&quot;, &quot;abc&quot;);
        };
    }
}
</code></pre>
<p>I get the following error when I try either of the two above .GetItem(...) lines:</p>
<pre><code>System.TypeInitializationException: 'The type initializer for 'Sitecore.SecurityModel.License.LicenseManager' threw an exception.'
InvalidOperationException: Could not instantiate the type 'Sitecore.Nexus.Licensing.NexusLicenseApi, Sitecore.Nexus'
</code></pre>
<p>I have included the following relevant references (amongst others) in my unit testing project: <code>Sitecore.FakeDb, Sitecore.Kernel, Sitecore.Mvc, Moq, Glass.Mapper, Glass.Mapper.Sc, Glass.Mapper.Sc.Mvc, Castle.Core</code>.  Do I need <code>Sitecore.Nexus</code>?  If yes, where can I get it from?</p>
<p>I have an <code>App_Config/Include/Sitecore.FakeDb.config</code> file, as well as an <code>App_Config/app.config</code> file, which has this setting in it:</p>
<pre><code>&lt;sitecore&gt;
&lt;settings&gt;
    &lt;setting name=&quot;LicenseFile&quot; value=&quot;..\..\license.xml&quot; /&gt;
&lt;/settings&gt;
&lt;/sitecore&gt;
</code></pre>
<p>Any idea on why this error is occuring and how to exactly fix it?</p>
<p>Here is the full stacktrace, if that helps:</p>
<pre><code>System.TypeInitializationException occurred
  HResult=0x80131534
  Message=The type initializer for 'Sitecore.SecurityModel.License.LicenseManager' threw an exception.
  Source=Sitecore.Kernel
  StackTrace:
   at Sitecore.SecurityModel.License.LicenseManager.DemandRuntime(Boolean acceptExpress)
   at Sitecore.Data.Managers.DefaultItemManager.get_FallbackProvider()
   at Sitecore.Data.Managers.DefaultItemManager.&lt;&gt;c__DisplayClass2f.&lt;GetItem&gt;b__2e()
   at Sitecore.Data.Managers.DefaultItemManager.ExecuteAndReturnResult[TArgs,TResult](String pipelineName, String pipelineDomain, Func`1 pipelineArgsCreator, Func`1 fallbackResult)
   at Sitecore.Data.Managers.DefaultItemManager.GetItem(ID itemId, Language language, Version version, Database database, SecurityCheck securityCheck)
   at Sitecore.Data.Managers.DefaultItemManager.GetItem(ID itemId, Language language, Version version, Database database)
   at Sitecore.Data.Managers.ItemManager.GetItem(ID itemId, Language language, Version version, Database database)
   at Sitecore.Data.DefaultDatabase.GetItem(ID itemId)
   at Sitecore.FakeDb.Db.GetItem(ID id)
   at WTW.Feature.HomeBottomContent.Tests.UnitTest1.Test_ArticleController_With_SitecoreItem() in C:\dev\TowersWatson\DEV\Maintenance\Source\Feature\HomeBottomContent\Tests\UnitTest1.cs:line 76

Inner Exception 1:
InvalidOperationException: Could not instantiate the type 'Sitecore.Nexus.Licensing.NexusLicenseApi, Sitecore.Nexus'
</code></pre>
",https://stackoverflow.com/questions/46288687/unit-testing-using-sitecore-fakedb-throws-sitecore-nexus-instantiation-error-on,"['c#', 'moq', 'sitecore8', 'sitecore-mvc', 'glass-mapper']",2995,TRUE,3,2
Unit Testing a Service That Uses AngularFireAuth and Mocking authState,"<p>I have been going round in circles trying to unit test a Service (<code>AuthService</code>) that depends upon <code>AngularFireAuth</code>.</p>

<p>I am trying to find a way to mock, or highjack the Observable <code>AngularFireAuth.authState</code> instead of the Service actually talking to Firebase.</p>

<p>Here is my test spec:</p>

<pre><code>import { inject, TestBed } from '@angular/core/testing';

import { AngularFireModule } from 'angularfire2';
import { AngularFireAuth, AngularFireAuthModule } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import 'rxjs/add/observable/of';
// import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Rx';

import { AuthService } from './auth.service';
import { environment } from '../../environments/environment';

const authState: firebase.User = null;
const mockAngularFireAuth: any = { authState: Observable.of(authState) };

describe('AuthService', () =&gt; {
  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [AngularFireModule.initializeApp(environment.firebaseAppConfig)],
      providers: [
        { provider: AngularFireAuth, useValue: mockAngularFireAuth },
        AuthService
      ]
    });
  });

  it('should be defined', inject([ AuthService ], (service: AuthService) =&gt; {
    expect(service).toBeDefined();
  }));

  it('.authState should be null', inject([ AuthService ], (service: AuthService) =&gt; {
    expect(service.authState).toBe(null);
  }));
});
</code></pre>

<p>And here is my (simplified) Service:</p>

<pre><code>import { Injectable } from '@angular/core';

import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class AuthService {
  private authState: firebase.User;

  constructor(private afAuth: AngularFireAuth) { this.init(); }

  private init(): void {
    this.afAuth.authState.subscribe((authState) =&gt; {
      if (authState === null) {
        this.afAuth.auth.signInAnonymously()
          .then((authState) =&gt; {
            this.authState = authState;
          })
          .catch((error) =&gt; {
            throw new Error(error.message);
          });
      } else {
        this.authState = authState;
      }
    }, (error) =&gt; {
      throw new Error(error.message);
    });
  }

  public get currentUser(): firebase.User {
    return this.authState ? this.authState : undefined;
  }

  public get currentUserObservable(): Observable&lt;firebase.User&gt; {
    return this.afAuth.authState;
  }

  public get currentUid(): string {
    return this.authState ? this.authState.uid : undefined;
  }

  public get isAnonymous(): boolean {
    return this.authState ? this.authState.isAnonymous : false;
  }

  public get isAuthenticated(): boolean {
    return !!this.authState;
  }

  public logout(): void {
    this.afAuth.auth.signOut();
  }
}
</code></pre>

<p>I get the error <code>Property 'authState' is private and only accessible within class 'AuthService'.</code></p>

<p>Of course it is, but I don't want to actually access it — I want to mock or highjack it so I can control it's value from within my test spec. I believe I am way off-course with my code here.</p>

<p>Please note I am using version <code>^4</code> of AngularFire2 and there were breaking changes introduced; documented here: <a href=""https://github.com/angular/angularfire2/blob/master/docs/version-4-upgrade.md"" rel=""nofollow noreferrer"">https://github.com/angular/angularfire2/blob/master/docs/version-4-upgrade.md</a></p>
",https://stackoverflow.com/questions/45117490/unit-testing-a-service-that-uses-angularfireauth-and-mocking-authstate,"['angular', 'unit-testing', 'firebase', 'jasmine', 'angularfire2']",1217,TRUE,3,1
angular 2 component with ngrx - errors when run unit-testing,"<p>I'm working on angular 2 project, using ngrx (for Redux logic) and rxjs (for observable).</p>

<p>Now I try to testing the project by running the auto-created .spec.ts files.</p>

<p>Some of the testings are fail, all of them are testing of components which use Store (from ngrx). 
Here is one of them:</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

import { MyComponent } from './overlay-menu-item.component';

describe('MyComponent', () =&gt; {
let component: MyComponent;
let fixture: ComponentFixture&lt;MyComponent&gt;;

beforeEach(async(() =&gt; {
  TestBed.configureTestingModule({
    declarations: [ MyComponent ],
  })
  .compileComponents();
}));

beforeEach(() =&gt; {
  fixture = TestBed.createComponent(MyComponent);
  component = fixture.componentInstance;
  fixture.detectChanges();
});

it('should create', () =&gt; {
  expect(component).toBeTruthy();
});
});
</code></pre>

<p>I look after the problem, the error was:</p>

<blockquote>
  <p>No provider to Store</p>
</blockquote>

<p>So I add: (I use jasmine for testing)</p>

<pre><code> beforeEach(async(() =&gt; {
TestBed.configureTestingModule({
  declarations: [ MyComponent ],
  providers: [Store]
 })
 .compileComponents();
}));
</code></pre>

<p>Now I got other error:</p>

<blockquote>
  <p>No provider for StateObservable</p>
</blockquote>

<p>So I add:</p>

<pre><code>  beforeEach(async(() =&gt; {
TestBed.configureTestingModule({
  declarations: [ MyComponent ],
  providers: [Store, StateObservable]
 })
 .compileComponents();
}));
</code></pre>

<p><strong>But now I got new error that I don't know what do to with it:</strong></p>

<blockquote>
<pre><code>Failed: Can't resolve all parameters for StateObservable: (?).
    Error: Can't resolve all parameters for StateObservable: (?).
        at syntaxError [mywebprojectPath]/node_modules/@angular/compiler/@angular/compiler.es5.js:1689:22)
</code></pre>
</blockquote>

<p><strong>What should I do?</strong></p>
",https://stackoverflow.com/questions/46544604/angular-2-component-with-ngrx-errors-when-run-unit-testing,"['unit-testing', 'jasmine', 'ngrx']",1028,TRUE,3,1
Strange behaviour while Unit testing for memory leak using WeakReference,"<p>I'm trying to write a unit test for testing a memory leak.
Steps to Reproduce:</p>

<pre><code>    TestClass test = new TestClass();
    WeakReference reference = new WeakReference(test, true);

    test = null;

    GC.Collect();
    GC.WaitForPendingFinalizers();
    GC.Collect();

    Debug.Assert(reference.Target == null, ""Memory Leak""); // This works

     //Replacing the above line with following, I see ""Memory Leak"" being printed.

    if (reference.Target != null)
    {
        Console.WriteLine(""Memory Leak"");
    }
</code></pre>

<p>I added a finalizer: </p>

<pre><code>~TestClass() { Console.WriteLine(""TestClass instance finalized"");}
</code></pre>

<p>and I noticed that the finalizer gets called as part of GC commands in the Assert case but when I replace it with if condition, the finalizer doesn't gets called as part of the GC commands and hence the reference's target is still alive. The finalizer gets called only before the program exists.</p>

<p>Expected Behavior:</p>

<pre><code>if(reference.Target != null) Console.WriteLine(""Memory Leak"");
</code></pre>

<p>should work.</p>

<p>Actual Behavior:</p>

<pre><code>Debug.Assert(reference.Target == null, ""Memory Leak"");
</code></pre>

<p>works but</p>

<pre><code>if(reference.Target != null) Console.WriteLine(""Memory Leak"");
</code></pre>

<p>doesn't works as it prints ""Memory Leak""</p>
",https://stackoverflow.com/questions/42328841/strange-behaviour-while-unit-testing-for-memory-leak-using-weakreference,"['c#', '.net', 'memory-leaks', 'garbage-collection']",512,TRUE,2,1
MVP or MVVM for Android with respect to Unit Testing?,"<p>Have used MVP model in one module of my android app with the help of which code was testable and I was able to run Unit test via that code.
Now I researched for MVVM model, my main focus is to make my code testable, can MVVM model could help me better than MVP model??</p>
",https://stackoverflow.com/questions/44064459/mvp-or-mvvm-for-android-with-respect-to-unit-testing,"['android', 'unit-testing', 'mvvm', 'mvp']",832,TRUE,2,1
Unit Testing using JUnit for Spring Batch without XML configuration,"<p>I am new to Spring Batch and I started developping a simple batch application. Now I am thinking of some unit testing unsing JUnit that could be healthy for my app and code ;)</p>

<p>The problem is that I couldn't find any ressource (examples, tutos ...) on the internet that shows how to perform unit testing with Spring Batch when using no XML.</p>

<p>Here is my code to be more clear :</p>

<p>Config class:</p>

<pre><code>package my.company.project.name.batch.config
@Configuration
@EnableBatchProcessing
@ComponentScan({
        ""my.company.project.name.batch.reader"",
        ""my.company.project.name.batch.tasklet"",
        ""my.company.project.name.batch.processor"",
        ""my.company.project.name.batch.writer""
})
@Import({CommonConfig.class})
public class MyItemBatchConfig {
    @Autowired
    private StepBuilderFactory steps;

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private MyItemTasklet myItemTasklet;

    @Bean
    public Job myItemJob(@Qualifier(""myItem"") Step loadProducts){
        return jobBuilderFactory.get(""myItemJob"").start(myMethod).build();
    }

    @Bean(name= ""myItem"")
    public Step myMethod(){
        return steps.get(""myItem"").tasklet(myItemTasklet).build();
    }
}
</code></pre>

<p>MyItemReader class :</p>

<pre><code>package my.company.project.name.batch.reader
@Component
public class MyItemReader implements ItemReader&lt;MyItem&gt;{

    @Value(""${batch.load.produit.csv.file.path}"")
    private String csvFilePath;

    private LinkedList&lt;CsvRawLine&gt; myItems;

    @PostConstruct
    public void init() {
        myItems = new LinkedList&lt;&gt;(CsvUtil.getCsvReader(MyItem.class, csvFilePath));
    }

    @Override
    public MyItem read() throws Exception{
        return myItems.poll();
    }
}
</code></pre>

<p>ItemProcessor class :</p>

<pre><code>package my.company.project.name.batch.processor
@Component
public class MyItemProcessor implements ItemProcessor&lt;MyItem, MyItemProcessorResult&gt; {

   public MyItemProcessorResult process(MyItemitem) throws Exception {
     //processing business logic
   }
}
</code></pre>

<p>ItemWriter class :</p>

<pre><code>package my.company.project.name.batch.writer
@Component
public class MyItemWriter implements ItemWriter&lt;MyItem&gt; {

    @Override
    public void write(List&lt;? extends MyItem&gt; myItems) throws Exception {
      //writer business logic
    }
}
</code></pre>

<p>MyItemTasklet class that will call all the previous classes in order to achieve the task wanted by the batch:</p>

<pre><code>package package my.company.project.name.batch.tasklet
@Component
public class MyItemBatchTasklet implements Tasklet{

    @Autowired
    public MyItemReader myItemReader;

    @Autowired
    public MyItemProcessor myItemProcessor;

    @Autowired
    public MyItemeWriter myItemWriter;

    @Override
    public RepeatStatus execute execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
       //calling myItemReader, myItemProcessor and myItemWriter to do the business logic
       return RepeatStatus.FINISHED
    }

}
</code></pre>

<p>MyItemTasklet class that will launch the tasklet by its main method :</p>

<pre><code>package package my.company.project.name.batch
public class MyItemTaskletLauncher{
    public MyItemTaskletLauncher(){
        //No implementation
    }

    public static void main (String[] args) throws IOException, JobExecutionException, NamingException {
        Launcher.launchWithConfig(""Launching MyItemTasklet ..."", MyItemBatchConfig.class,false);
    }
}
</code></pre>
",https://stackoverflow.com/questions/45374216/unit-testing-using-junit-for-spring-batch-without-xml-configuration,"['spring', 'unit-testing', 'spring-batch', 'junit4', 'xml-configuration']",7952,FALSE,2,1
Is it possible to speed up time for unit testing?,"<p>Is there any reasonable way you can speed up (or fake) the passage of time for unit testing? If for instance, you want to test signaling in threads, or that some code correctly handles day/month/year date changes in long-running code?</p>

<p>I know you can check things like day/year change in separate tests but moving towards an integration test it can be nice to be able to run a solid week's time passing without waiting a week... if you have something happening hourly then being able to drive that in some fast-forward mechanism.</p>
",https://stackoverflow.com/questions/42817040/is-it-possible-to-speed-up-time-for-unit-testing,"['c#', '.net', 'testing', 'mstest']",1726,TRUE,3,2
CUSTOM_ELEMENTS_SCHEMA error occur while unit testing with jasmine and karma,"<p>I am doing unit testing with jasmine and karma. I am able to run test in simple application but when i am testing method of a page that has other component it shows error like this</p>

<blockquote>
  <p>If 'custom-component' is a Web Component then add 
      'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component 
      to suppress this message</p>
</blockquote>

<p><strong>custom-component.html</strong></p>

<pre><code>&lt;div class=""data-container""&gt;
    &lt;ion-row&gt;
        &lt;!-- Display week Day and Dates --&gt;
        &lt;ion-col class=""no-padding"" *ngFor=""let days of weekDates""&gt;
            &lt;div class=""header-circle""&gt;
                &lt;!-- Header-Circle for Day --&gt;
                &lt;p class=""uppercase thick day-color""&gt;{{ days.day }}&lt;/p&gt;
            &lt;/div&gt;
            &lt;div id=""{{days.day_date}}"" (click)=""toggle(days)"" class=""{{days.iconClass}}""&gt;
                &lt;!-- Circle for Date --&gt;
                &lt;p class=""uppercase thick day-color""&gt;{{ days.date }}&lt;/p&gt;
            &lt;/div&gt;
        &lt;/ion-col&gt;
        &lt;!-- End of loop --&gt;
    &lt;/ion-row&gt;
&lt;/div&gt;
</code></pre>

<p><strong>custom-component.ts</strong></p>

<pre><code>import { Component, Input, Output, EventEmitter, ApplicationRef } from '@angular/core';

@Component({
    selector: 'custom-component',
    templateUrl: 'custom-component.html'
})
export class custom-component {//Some Code Here }
</code></pre>

<p><strong>Checkin.html</strong></p>

<pre><code>&lt;ion-header&gt;
    &lt;ion-navbar&gt;
        &lt;ion-title&gt;{{ spaceName }}&lt;/ion-title&gt;
        &lt;!-- added spaceName as title  --&gt;
    &lt;/ion-navbar&gt;
&lt;/ion-header&gt;
&lt;ion-content class=""checkin-content"" no-bounce&gt;
    &lt;custom-component [inputDate]=""selectedDate"" (dateChanged)=""dateChanged($event)""&gt;&lt;/custom-component&gt;
&lt;/ion-content&gt;
</code></pre>

<p><strong>Checkin.ts</strong></p>

<pre><code>import { Component } from '@angular/core';
import { IonicPage, ModalController, NavParams, NavController, Events } from 'ionic-angular';
import { custom-component } from '../../components/custom-component/custom-component';

export class CheckinPage {

    public isNumberEven(num: number): boolean {
        return num % 2 === 0;
    }

    public isNumberOdd(num: number): boolean {
        return !this.isNumberEven(num);
    }
}
</code></pre>

<p><strong>Checkin.spec.ts</strong></p>

<pre><code>import { TestBed, ComponentFixture, async } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { IonicModule } from 'ionic-angular';
import { MyApp } from '../../app/app.component';
import { CheckinPage } from './checkin';
import { NavController } from 'ionic-angular';
import { custom-component } from '../../components/custom-component/custom-component';

let comp: CheckinPage;
let fixture: ComponentFixture&lt;CheckinPage&gt;;
let de: DebugElement;
let el: HTMLElement;
let datepipe: DatePipe;

describe('Checkin Component', () =&gt; {

    beforeEach(async(() =&gt; {

        TestBed.configureTestingModule({

            declarations: [MyApp, CheckinPage, RoatedDateComponent],

            providers: [
                NavController
            ],

            imports: [
                IonicModule.forRoot(MyApp)
            ]

        }).compileComponents();

    }));

    beforeEach(() =&gt; {

        fixture = TestBed.createComponent(CheckinPage);
        comp = fixture.componentInstance;

    });

    afterEach(() =&gt; {
        fixture.destroy();
        comp = null;
        de = null;
        el = null;
    });

    it(""should correctly classify numbers as odd"", () =&gt; {
        expect(comp.isNumberOdd(1)).toBe(true);
        expect(comp.isNumberOdd(2)).toBe(false);
    });
});
</code></pre>

<p><strong>checkin.module.ts</strong></p>

<pre><code>import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { CheckinPage } from './checkin';

@NgModule({
    declarations: [
        CheckinPage,
    ],
    imports: [
        IonicPageModule.forChild(CheckinPage),
    ],
})
export class CheckinPageModule { }
</code></pre>

<p>Can anyone help me with this one?</p>
",https://stackoverflow.com/questions/46936983/custom-elements-schema-error-occur-while-unit-testing-with-jasmine-and-karma,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",5193,TRUE,2,1
How to moq responses from Amazon MWS for unit testing,"<p><strong>Context</strong></p>

<p>I'm unit testing a C# .Net class that calls the <code>ListMatchingProducts</code> operation in the Amazon MWS API (using MWSClientCsRuntime).</p>

<p><strong>Issue</strong></p>

<p>The Amazon MWS API is a moving target with product data changing all the time so I'd like to be able to moq the <code>ListMatchingProductsResponse</code> object that the API returns.  I can fetch API responses using the MWS scratchpad and store these in xml files. But then, in unit tests, I need to coerce data from these files into a <code>ListMatchingProductsResponse</code> object.</p>

<p><strong>Question</strong></p>

<p>How can I load this xml data into a <code>ListMatchingProductsResponse</code> object? (I notice that the object has a <code>ReadFragmentsFrom</code> method but I can't see how this might be used).</p>

<p><strong>Code</strong></p>

<pre><code>[TestClass]
public class PossibleAmazonProductMatchesTests
{
    string testDataDirectory = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + @""\Test data"";

    [TestMethod]
    public void FindSpanners()
    {
        // Arrange

        ListMatchingProductsRequest request = new ListMatchingProductsRequest(""secret key"", ""market id"", ""spanner"");
        ListMatchingProductsResult result = new ListMatchingProductsResult();

        ListMatchingProductsResponse response = new ListMatchingProductsResponse();

        string xmlString = File.ReadAllText(this.testDataDirectory + @""\Spanners Response.xml"");

        // *** The issue - How do I coerce xmlString into response? ***

        var client = new Mock&lt;MarketplaceWebServiceProductsClient&gt;();
        client.Setup(c =&gt; c.ListMatchingProducts(request)).Returns(response);

        // Act

        // This is the method being tested. It calls ListMatchingProducts which is being mocked.
        PossibleAmazonProductMatches possibleAmazonProductMatches = new PossibleAmazonProductMatches(""spanners"", client);

        // Assert

        Assert.IsTrue(possibleAmazonProductMatches.SpannersFound == true);
    }
}
</code></pre>
",https://stackoverflow.com/questions/43642965/how-to-moq-responses-from-amazon-mws-for-unit-testing,"['c#', 'xml', 'unit-testing', 'moq', 'amazon-mws']",667,TRUE,2,3
Recommended approach for combining Aurelia build revisions and unit testing,"<p>When creating a new Aurelia project using the CLI (<code>au new</code>) with unit testing and build revisions enabled. I get a warning message that karma cannot find the <code>vendor-bundle.js</code> and <code>app-bundle.js</code>.</p>

<blockquote>
  <p>14 03 2017 08:54:27.260:WARN [watcher]: Pattern
  ""C:/Temp/AureliaTest/scripts/vendor-bundle.js"" does not
  match any file. </p>
  
  <p>14 03 2017 08:54:27.266:WARN [watcher]: Pattern
  ""C:/Temp/AureliaTest/scripts/app-bundle.js"" does not match
  any file.</p>
</blockquote>

<p>I understand that the bundles name should include a hash like <code>vendor-bundle-{hash}.js</code>, but what is the recommended approach to let karma know what the name of the bundle is?</p>

<p>I updated to the newest Aurelia CLI (0.26.1) and created a new project with the following steps:</p>

<ul>
<li>App name : Test</li>
<li>Custom setup</li>
<li>Typescript</li>
<li>Default template</li>
<li>CSS processor: Sass</li>
<li>Unit testing: Yes</li>
<li>Default code editor: VS code</li>
<li>Create the project: Yes</li>
<li>Install dependencies: Yes</li>
</ul>

<p>I enabled build revisions in the <code>aurelia.json</code>: <a href=""http://aurelia.io/hub.html#/doc/article/aurelia/framework/latest/the-aurelia-cli/8"" rel=""nofollow noreferrer"">http://aurelia.io/hub.html#/doc/article/aurelia/framework/latest/the-aurelia-cli/8</a></p>

<pre><code>""options"": {
  ""minify"": ""stage &amp; prod"",
  ""sourcemaps"": ""dev &amp; stage"",
  ""rev"": true
}
</code></pre>

<p>Aftwerwards I ran the build (<code>au build</code>) and ran the unit tests (<code>au test</code>)</p>

<p>This results in the following code sample: <a href=""https://github.com/jimmyvdberg/aurelia-revisions-and-unit-tests"" rel=""nofollow noreferrer"">https://github.com/jimmyvdberg/aurelia-revisions-and-unit-tests</a></p>
",https://stackoverflow.com/questions/42781044/recommended-approach-for-combining-aurelia-build-revisions-and-unit-testing,['aurelia'],176,FALSE,2,1
Unit Testing select menu change event (not getting updated value),"<p>Trying to get my select menus change event to fire correctly with the correct value.  It seems to be firing but the value is not changing.</p>

<p>I have this select menu in my component:</p>

<pre><code>&lt;select id=""seasonDropDown"" style=""width:200px;height: 36px;"" aria-label=""Select a Season"" (change)=""changeSeason($event.target.value)""&gt;
        &lt;option *ngFor=""let item of seasons"" [value]=""item.id"" [selected]=""item.id === seasonId""&gt;Season {{item.id}}&lt;/option&gt;
    &lt;/select&gt;
</code></pre>

<p>I have this change event:</p>

<pre><code>  public changeSeason(seasonId: number) {
    this.test = 'blah';  //for testing sake
    console.log('change season ' + seasonId)
    this.seasonId = seasonId;
    this.notify.emit(this.seasonId);
  }
</code></pre>

<p>I have tried testing it like the code below but commponent.seasonId never changes from its default value.  It should get changed in changeSeason method.  I know the method is firing because when I test expect(component.test).toEqual('blah') it will pass:</p>

<pre><code>    it('should emit new season on change event', fakeAsync(() =&gt; {

        let select = fixture.debugElement.query(By.css('#seasonDropDown')).nativeElement;

        select.value = 2;
        select.selectedValue = 2;

        fixture.detectChanges();

        select.dispatchEvent(new Event('change'));
        tick();

        fixture.detectChanges();


        expect(component.seasonId).toEqual(2);
        //expect(component.test).toEqual('blah');  this will pass so I know the 
        //changeSeason event is actually getting called 
  }));
</code></pre>
",https://stackoverflow.com/questions/46379815/unit-testing-select-menu-change-event-not-getting-updated-value,"['angular', 'jasmine', 'karma-jasmine']",3021,TRUE,2,1
How to do unit testing of HTTP requests using Ginkgo?,"<p>i have just started learning to write unit tests for the http requests, i went through several blogs but i didn't understood how to write tests for this using Ginkgo.</p>

<pre><code>func getVolDetails(volName string, obj interface{}) error {
    addr := os.Getenv(""SOME_ADDR"")
    if addr == """" {
        err := errors.New(""SOME_ADDR environment variable not set"")
        fmt.Println(err)
        return err
    }
    url := addr + ""/path/to/somepage/"" + volName
    client := &amp;http.Client{
        Timeout: timeout,
    }
    resp, err := client.Get(url)
    if resp != nil {
        if resp.StatusCode == 500 {
            fmt.Printf(""VSM %s not found\n"", volName)
            return err
        } else if resp.StatusCode == 503 {
            fmt.Println(""server not reachable"")
            return err
        }
    } else {
        fmt.Println(""server not reachable"")
        return err
    }

    if err != nil {
        fmt.Println(err)
        return err
    }
    defer resp.Body.Close()

    return json.NewDecoder(resp.Body).Decode(obj)
}

// GetVolAnnotations gets annotations of volume
func GetVolAnnotations(volName string) (*Annotations, error) {
    var volume Volume
    var annotations Annotations
    err := getVolDetails(volName, &amp;volume)
    if err != nil || volume.Metadata.Annotations == nil {
        if volume.Status.Reason == ""pending"" {
            fmt.Println(""VSM status Unknown to server"")
        }
        return nil, err
    }
    // Skipped some part,not required
}
</code></pre>

<p>I went through this <a href=""https://nathanleclaire.com/blog/2015/10/10/interfaces-and-composition-for-effective-unit-testing-in-golang/"" rel=""nofollow noreferrer"">blog</a> and it exactly explains what my code requires but it uses Testing package and i want to implement this using ginkgo.</p>
",https://stackoverflow.com/questions/45434849/how-to-do-unit-testing-of-http-requests-using-ginkgo,"['unit-testing', 'http', 'go', 'ginkgo']",4609,TRUE,2,1
Importing modules properly for unit testing in Python using pyunit,"<h1>Question on unit testing</h1>

<p><strong>Goal</strong>: The goal is to use pyUnit in testCalc.py to unit test the simpleCalc object in calculator.py.<br>
<strong>Problem</strong>: I cannot successfully import the simpleCalc object from calculator.py into testCalc.py when testCalc is run from a separate directory in the project.<br>
<strong>Background</strong>: The unit test in testCalc.py runs perfectly fine when it's included in the same directory as calculator.py, but when I move it into a separate folder and try to import the simpleCalc object defined in calculator.py, I get an error.  I am trying to learn how to use the pyUnit unit testing framework in a simple project and I'm clearly missing something basic about how to import modules for unit testing in a hierarchical directory structure.  The basic calculator_test project described below is a simple project that I created to practice.  You can see all the posts I've gone through already at the end of this post.<br>
<strong>Ultimate Question</strong>: How can I import the simpleCalc object into testCalc.py with the directory hierarchy described below?</p>

<p>Github: <a href=""https://github.com/jaybird4522/calculator_test/tree/unit_test"" rel=""nofollow noreferrer"">https://github.com/jaybird4522/calculator_test/tree/unit_test</a></p>

<p>Here's my directory structure:</p>

<pre><code>calculator_test/
    calculatorAlgo/
        __init__.py
        calculator.py
    test_calculatorAlgo/
        __init__.py
        testCalc.py
        testlib/
            __init__.py
            testcase.py
</code></pre>

<p>Here's the calculator.py file, which describes the simpleCalc object I want to unit test:  </p>

<pre><code># calculator.py

class simpleCalc(object):

    def __init__(self):
        self.input1 = 0
        self.input2 = 0

    def set(self, in1, in2):
        self.input1 = in1
        self.input2 = in2

    def subtract(self, in1, in2):
        self.set(in1, in2)
        result = self.input1 - self.input2
        return result
</code></pre>

<p>Here's the testCalc.py file, which contains the unit tests:</p>

<pre><code># testCalc.py

import unittest
from calculatorAlgo.calculator import simpleCalc

class testCalc(unittest.TestCase):

    # set up the tests by instantiating a simpleCalc object as calc
    def setUp(self):
        self.calc = simpleCalc()

    def runTest(self):
        self.assertEqual(self.calc.subtract(7,3),4)

if __name__ == '__main__':
    unittest.main()
</code></pre>

<p>I have been running the unit test file with the simple command:</p>

<blockquote>
  <p>testCalc.py</p>
</blockquote>

<h1>What I've attempted so far</h1>

<p><strong>First Attempt</strong><br>
I tried simply importing the simpleCalc object based on where it's located in the directory structure:</p>

<pre><code># testCalc.py

import unittest
from .calculatorAlgo.calculator import simpleCalc

class testCalc(unittest....
</code></pre>

<p>And got this error:<br>
<em>ValueError: Attempted relative import in non-package</em></p>

<p><strong>Second Attempt</strong><br>
I tried importing it without relative references:</p>

<pre><code># testCalc.py

import unittest
import simpleCalc

class testCalc(unittest....
</code></pre>

<p>And got this error:<br>
<em>ImportError: No module named simpleCalc</em></p>

<p><strong>Third Attempt</strong><br>
Based on this post, <a href=""http://blog.aaronboman.com/programming/testing/2016/02/11/how-to-write-tests-in-python-project-structure/"" rel=""nofollow noreferrer"">http://blog.aaronboman.com/programming/testing/2016/02/11/how-to-write-tests-in-python-project-structure/</a>, I tried creating a separate base class called testcase.py which could do the relative imports.</p>

<pre><code># testcase.py

from unittest import TestCase
from ...calculator import simpleCalc

class BaseTestCase(TestCase):
    pass
</code></pre>

<p>And changed my imports in testCalc.py  </p>

<pre><code># testCalc.py

import unittest
from testlib.testcase import BaseTestCase

class testCalc(unittest....
</code></pre>

<p>And got this error:<br>
<em>ValueError: Attempted relative import beyond toplevel package</em></p>

<p><strong>Other Resources</strong><br>
Here are some of the posts I've worked through to no avail:<br>
<a href=""https://stackoverflow.com/questions/279237/import-a-module-from-a-relative-path"">Import a module from a relative path</a><br>
<a href=""https://stackoverflow.com/questions/4348452/python-packaging-for-relative-imports"">python packaging for relative imports</a><br>
<a href=""https://stackoverflow.com/questions/11536764/how-to-fix-attempted-relative-import-in-non-package-even-with-init-py/27876800#27876800"">How to fix &quot;Attempted relative import in non-package&quot; even with __init__.py</a><br>
<a href=""https://stackoverflow.com/questions/24048203/python-importing-works-from-one-folder-but-not-another"">Python importing works from one folder but not another</a><br>
<a href=""https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time"">Relative imports for the billionth time</a>  </p>

<p>Ultimately, I feel that I'm just missing something basic, even after a lot of research.  This feels like a common setup, and I'm hoping someone can tell me what I'm doing wrong, and that it might help others avoid this problem in the future.</p>
",https://stackoverflow.com/questions/42193932/importing-modules-properly-for-unit-testing-in-python-using-pyunit,"['python', 'unit-testing', 'python-import', 'python-unittest']",2655,FALSE,2,1
Swift 3 Unit Testing - Linker fails when using import @testable,"<p>I'm currently trying to write unit tests (<strong>NOT</strong> UI Tests) for my (macOS) Xcode project. I have created a new Unit Test target which creates a blank unit test file for me.</p>

<p>This complies and links fine, but there are no tests.</p>

<p>As soon as I add the line <code>@testable import Pilot</code>, where <code>Pilot</code> is the name of my App Target, and I try to compile and run, it fails with this message:</p>

<p><code>Linker command failed with exit code 1 (use -v to see invocation)</code></p>

<p>I've tried everything I can find, but nothing seems to be working. The other posts I have read on here deal with this problem in UI Tests, but that is because you cannot use <code>@testable</code> in UI Tests. You are supposed to be able to use it in Unit Tests, but I can't figure out why this is not working.</p>

<p>Does anyone have any insight?</p>

<p>If it helps, my project is located at: <a href=""https://github.com/RohanNagar/pilot-osx"" rel=""nofollow noreferrer"">https://github.com/RohanNagar/pilot-osx</a></p>

<p>Here is the full <code>PilotTests.swift</code> file:</p>

<pre><code>import XCTest

@testable import Pilot

class PilotTests: XCTestCase {

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }

    func testExample() {
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
    }

    func testPerformanceExample() {
        // This is an example of a performance test case.
        self.measure {
            // Put the code you want to measure the time of here.
        }
    }

}
</code></pre>
",https://stackoverflow.com/questions/43358947/swift-3-unit-testing-linker-fails-when-using-import-testable,"['swift', 'xcode', 'unit-testing', 'cocoa', 'linker']",2715,TRUE,2,4
Unit Testing with datatypes inputs set to MAX+1 values,"<p>I am doing unit testing for code in <a href=""/questions/tagged/c"" class=""post-tag"" title=""show questions tagged &#39;c&#39;"" rel=""tag"">c</a> language where I am thinking what could be the harm if I do not exercise testing inputs with <code>MAX+1</code> values of datatypes. </p>

<p>Usually, <a href=""/questions/tagged/c"" class=""post-tag"" title=""show questions tagged &#39;c&#39;"" rel=""tag"">c</a> wraps the variable value to its minimum if the value overflows its <code>MAX</code> capacity. Eg: if a <code>char</code> (range: <code>0-255</code>) is incremented after <code>255</code> will result in <code>0</code>. </p>

<p>Is there any example where it would be really harmful if the testing is not done <code>MAX+1</code> cases where the value rolls back to the datatype's MIN value?</p>
",https://stackoverflow.com/questions/42851226/unit-testing-with-datatypes-inputs-set-to-max1-values,"['c', 'unit-testing']",87,TRUE,2,1
Xamarin Unit Testing Portable Bait and Switch error with Xamarin.Auth?,"<p>I have set up a TestProject in Visual Studio for Mac that references my Xamarin Forms project for testing the non-visual portions of my code. </p>

<p>However I am getting the following error when I try to test a piece of my code that leverages Xamarin.Auth to access the keychain.</p>

<pre><code>System.NotImplementedException : 
Portable Bait And Switch is nuget feature, so the package must be installed in all project.

NotImplementedException will indicate that Portable Code from PCL is used and not Platform Specific
implementation. Please check whether platform specific Assembly is properly installed.

Cannot save account in Portable profile - bait-and-switch error.
Please file a bug in https://bugzilla.xamarin.com
</code></pre>

<p>This code works fine running on the iOS simulator, and I assume it has something to do with the way xamarin auth leverages the ios Keychain which is not present in this test project.  I tried to add my ios solution in references, but I am unable to do so in ""edit references"" of my test project.  The project references dialog wont permit it: <a href=""https://i.stack.imgur.com/yzq8Q.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/yzq8Q.png"" alt=""enter image description here""></a></p>

<p>Here is the code that is failing in my PCL.</p>

<pre><code> AccountStore store;
 store = AccountStore.Create();
</code></pre>

<p>Apparently it has trouble with AccountStore.Create()</p>

<p>Here is the testcode class that calls the PCL:</p>

<pre><code>using System;
using NUnit.Framework;
using CrowdWisdom;
using CrowdWisdom.Authentication;

namespace CrowdWisdomTest
{
    [TestFixture()]
    public class AuthServiceTest
    {
        [Test()]
        public void SaveRestoreSecret()
        {
            String secret = ""ABCD"";
            AuthService auth = AuthService.GetInstance();
            auth.putSecret(""MySecret"", secret);
            Assert.AreEqual(secret, auth.GetSecret(""MySecret""));
    }
  }
}
</code></pre>
",https://stackoverflow.com/questions/46042175/xamarin-unit-testing-portable-bait-and-switch-error-with-xamarin-auth,"['xamarin', 'xamarin.ios', 'xamarin.forms']",498,TRUE,1,2
Unit Testing - JAVA/XML unable to figure out the error,"<p>I am doing a unit testing. The code is as below</p>

<pre><code>NodeList nodelist1 = node.getChildNodes();
</code></pre>

<p>I printed the nodelist1 object by referring one of the stackoverflow link to print a nodelist</p>

<p>it printed the xml as below</p>

<pre><code>   &lt;label _FORMAT =""A1""&gt;
       &lt;variable name=""BOX""/&gt;
       &lt;variable name=""CA1""/&gt;
       &lt;variable name=""Item""/&gt;  &lt;/label&gt;
</code></pre>

<p>the next operation is inside loop</p>

<pre><code>Node node1 = nodelist1.item(j);
</code></pre>

<p>when I print node1 it prints empty spaces.</p>

<p>can some one help me to understand , why its printing empty spaces ? btw am new to java and XML</p>
",https://stackoverflow.com/questions/44106721/unit-testing-java-xml-unable-to-figure-out-the-error,"['java', 'xml']",68,TRUE,1,2
C# Unit Testing validate if data input is being deserialized,"<p>How can I unit test if my JSON input is being deserialized? I am trying to deserialize a JSON input, calculate and then serialize. But I don't know how to check if my input is being deserialized. So I am writing unit test to validate.</p>

<p><strong>NOTE:</strong> AlphaCalcParam ParseParameter is a private method. This is where I am getting an error.</p>

<p><strong>Unit Test</strong></p>

<pre><code>   [TestMethod()]
            public void ParseParameterTest()
            {
                Algo.Alpha.AlphaCalculator calc = new Alpha.AlphaCalculator();

                string test_input = File.ReadAllText(@""..\..\..\case\Alpha Example Input.json"");
                string expected = File.ReadAllText(@""..\..\..\case\Alpha Example DOutput.json"");
                string res = calc.AlphaCalcParam(test_input);

                res == expected
                Assert.Fail();
            }
</code></pre>

<p><strong>Logic</strong></p>

<pre><code> public string Calculation(string json_param)
        {
            try
            {
                AlphaCalcParam param = ParseParameter(json_param);
                AlphaCalcResults result = CalculateAlpha(param);

                return JsonConvert.SerializeObject(result);
            }
            catch (Exception e)
            {
                return ""Failed in Alpha Calculation!. "" + e.Message;
            }
        }

...some more code.. below is what i want to test...

 private AlphaCalcParam ParseParameter(string json_param)
        {
            try
            {
                return JsonConvert.DeserializeObject&lt;AlphaCalcParam&gt;(json_param);
            }
            catch (Exception ex)
            {
                throw new Exception(""The input json string format is wrong for Alpha Calculation!. "" + ex.Message);
            }
        }
</code></pre>
",https://stackoverflow.com/questions/42304172/c-unit-testing-validate-if-data-input-is-being-deserialized,"['c#', 'json', 'unit-testing', 'serialization']",2785,TRUE,1,1
Mocha Unit Testing of Controller resolving promise coming from services,"<p>I have controller : </p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>function(req, res) {
    // Use the Domain model to find all domain
    CIO.find(function(err, CIOs) {
        if (err) {
            response = responseFormat.create(false, ""Error getting CIOs"", err, {});
            res.status(400).json(response);
        } else {

            var metrics = {
                ""count"": CIOs.length
            };

            // .then means it will wait for it to finish, then let you have the result


            var promises = [];

            for (i in CIOs) {
                promises.push(Analysis.structureMetrics(CIOs[i].toObject()))
            }

            var output = []
            var errors = []
            Q.allSettled(promises)
                .then(function(results) {


                    for (i in results) {
                        if (results[i].state === ""rejected"") {
                            console.log(results[i])
                            errors.push(results[i].reason.errors)
                            output.push(results[i].reason)
                        } else {
                            output.push(results[i].value)
                        }
                    }
                }).then(function() {
                    response = responseFormat.create(true, ""List of all CIOs"", output, metrics, errors);
                    res.status(200).json(response);
                })
        }
    });
};</code></pre>
</div>
</div>
</p>

<p>and cio.test file :</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>describe('/cio', function() {
    describe('GET', function() {

        //this.timeout(30000);
        before(function() {
            
        });

        it('should return response', function(done) {
            var response = http_mocks.createResponse({eventEmitter: require('events').EventEmitter})
            var request  = http_mocks.createRequest({
                method: 'GET',
                url: '/cio',
            })          
            //var data = JSON.parse( response._getData() );
            response.on('end', function() {
                response.statusCode.should.be.equal(400);
                done();
            
            })
            cioCtrl.getCIOs(request, response);
        });

     
    });
});</code></pre>
</div>
</div>
</p>

<p>getting Error </p>

<blockquote>
  <p>Error: timeout of 10000ms exceeded. Ensure the done() callback is being called in this test</p>
</blockquote>

<p>1>I have already tried increasing the time, but It  doesn't work.</p>

<p>2> What I found is <code>response.('end', function(){})</code> is not getting called, but not sure why</p>

<p>Any help would be appreciated.
Thanks!</p>
",https://stackoverflow.com/questions/45027659/mocha-unit-testing-of-controller-resolving-promise-coming-from-services,"['javascript', 'node.js', 'unit-testing', 'controller', 'mocha.js']",170,FALSE,1,1
Laravel &amp; PHPUnit: Getting 500 when unit testing &quot;Passport&quot; restricted route,"<p>I have a Laravel 5.3 app. </p>

<p>Inside my <code>api.php</code> file, there's a route for posting an answer within a poll. </p>

<p><code>Route::group(['middleware' =&gt; 'auth:api'], function () {
    Route::post('/poll/answer', 'API\PollsController@createAnswer');
});</code></p>

<p>The route is part of a group, restricted by the <code>auth:api</code> middleware, using Laravel's Passport engine. </p>

<p>When calling this route from Postman or any other tool to test APIs, I get 401 which is ok because I'm not attaching the token. </p>

<p>But when unit testing this call using PHPUnit, it returns 500. I have no idea why. </p>

<p><code>$this-&gt;postJson('api/poll/answer');</code></p>

<p>I'm probably missing a configuration or setup instruction. </p>

<p>Any ideas?</p>
",https://stackoverflow.com/questions/41541476/laravel-phpunit-getting-500-when-unit-testing-passport-restricted-route,"['laravel', 'unit-testing', 'laravel-5', 'phpunit', 'laravel-5.3']",1133,TRUE,8,1
Unit testing code in catch block of a Spring Controller,"<p>I have controller with the following structure: </p>

<pre><code>@RequestMapping(value = ""${foo.controller.requestMappingUrl.login}"", method = RequestMethod.POST)
    public ResponseMessage&lt;String&gt; loginUser(
            @RequestParam(""username"") String username, HttpServletRequest httpServletRequest,
            HttpServletResponse httpServletResponse) {

    try {

       return fooService.login(username); // can mock test

    } catch (UserNotFoundException e) {
            //CANNOT MOCK TEST THIS BLOCK
            String errorMsg = LoggerUtil.printStackTrace(e);
            LOG.error(""[RequestId: {}] UserNotFoundException: {}, Stack: {}"", requestId, e.getMessage(), errorMsg);
            httpServletResponse.setStatus(HttpStatus.NOT_ACCEPTABLE.value());
            statusCode = StatusCode.UserNotFound.value();
            responseMessage.buildResponseMessage(StringUtils.EMPTY, HttpStatus.NOT_ACCEPTABLE, statusCode,
                    messageByLocaleService.getMessageResponse(statusCode, null, locale));
    }
}
</code></pre>

<p>When I mock to throw the exception UserNotFoundException, I get only NestedServletException. Even though I tried adding expected = NestedServletException.class. The corbetura reports indicate that the code block is not covered in testing. Do you have any suggestion to help test the code inside the catch block. </p>

<p>The test code as requested:</p>

<pre><code>@SuppressWarnings(""unchecked"")
@Test(expected = UserNotFoundException.class)
    public void testControllerUserNotFoundException() throws Exception {
        Response resp = new Response();
        resp.setStatusCode(StatusCode.UserNotFoundErrorCode);
        when(fooService.login(any(String.class)).thenThrow(UserNotFoundException.class);

        mockMvc.perform(post(""/service-user/1.0/auth/login?&amp;username=test"")
                        .contentType(contentType)).andExpect(status().isNotAcceptable())
                .andExpect(jsonPath(""$.statusCode"", is(""ERRORCODE144"")));

    }
</code></pre>

<p>And the stack trace</p>

<blockquote>
  <p>java.lang.Exception: Unexpected exception,
  expected
  but was  at
  org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:28)
    at
  org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at
  org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at
  org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at
  org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)  at
  org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)   at
  org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)     at
  org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)   at
  org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)  at
  org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at
  org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at
  org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at
  org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at
  org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at
  org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at
  org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at
  org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
  Caused by: org.springframework.web.util.NestedServletException:
  Request processing failed; nested exception is
  com.atlassian.crowd.exception.runtime.UserNotFoundException   at
  org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
    at
  org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)     at
  org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at
  org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)     at
  org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
    at
  org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
    at
  org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
    at
  id.co.allianz.microservice.cop.app.auth.controller.AuthControllerTest.testControllerUserNotFoundException(AuthControllerTest.java:105)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)     at
  org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at
  org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at
  org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at
  org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at
  org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:19)
    ... 22 more Caused by:
  com.atlassian.crowd.exception.runtime.UserNotFoundException</p>
</blockquote>
",https://stackoverflow.com/questions/43019566/unit-testing-code-in-catch-block-of-a-spring-controller,"['java', 'spring', 'unit-testing', 'junit', 'mockito']",3683,TRUE,1,1
Unit Testing - &#39;fixtures&#39; no method error using No-Brainer ORM,"<p>I am trying to write unit tests for my database using fixtures in rails 5.0.1. </p>

<p>I keep getting the error: </p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>test/test_helper.rb:7:in `&lt;class:TestCase&gt;': undefined method `fixtures' for ActiveSupport::TestCase:Class (NoMethodError)
	from /Users/Stephan/ruby/react/test/test_helper.rb:5:in `&lt;top (required)&gt;'
	from /Users/Stephan/ruby/react/test/models/blog_test.rb:1:in `require'
	from /Users/Stephan/ruby/react/test/models/blog_test.rb:1:in `&lt;top (required)&gt;'
	from /Users/Stephan/.rvm/gems/ruby-2.4.0@global/gems/railties-5.0.1/lib/rails/test_unit/test_requirer.rb:11:in `require'
	from /Users/Stephan/.rvm/gems/ruby-2.4.0@global/gems/railties-5.0.1/lib/rails/test_unit/test_requirer.rb:11:in `block in require_files'
	from /Users/Stephan/.rvm/gems/ruby-2.4.0@global/gems/railties-5.0.1/lib/rails/test_unit/test_requirer.rb:10:in `each'
	from /Users/Stephan/.rvm/gems/ruby-2.4.0@global/gems/railties-5.0.1/lib/rails/test_unit/test_requirer.rb:10:in `require_files'
	from /Users/Stephan/.rvm/gems/ruby-2.4.0@global/gems/railties-5.0.1/lib/rails/test_unit/minitest_plugin.rb:86:in `plugin_rails_init'
	from /Users/Stephan/.rvm/gems/ruby-2.4.0@global/gems/minitest-5.10.1/lib/minitest.rb:80:in `block in init_plugins'
	from /Users/Stephan/.rvm/gems/ruby-2.4.0@global/gems/minitest-5.10.1/lib/minitest.rb:78:in `each'
	from /Users/Stephan/.rvm/gems/ruby-2.4.0@global/gems/minitest-5.10.1/lib/minitest.rb:78:in `init_plugins'
	from /Users/Stephan/.rvm/gems/ruby-2.4.0@global/gems/minitest-5.10.1/lib/minitest.rb:129:in `run'
	from /Users/Stephan/.rvm/gems/ruby-2.4.0@global/gems/railties-5.0.1/lib/rails/test_unit/minitest_plugin.rb:73:in `run'
	from /Users/Stephan/.rvm/gems/ruby-2.4.0@global/gems/minitest-5.10.1/lib/minitest.rb:62:in `block in autorun'</code></pre>
</div>
</div>
</p>

<p>Everything in the test_helper.rb is out of the box ruby 2.4.0 and rails 5.0.1. </p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>ENV[""RAILS_ENV""] = ""test""
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'


class ActiveSupport::TestCase
  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
  fixtures :all

  # Add more helper methods to be used by all tests here...
end</code></pre>
</div>
</div>
</p>

<p>Any help would be appreciated. For reference here is the test_helper.rb file</p>
",https://stackoverflow.com/questions/42541506/unit-testing-fixtures-no-method-error-using-no-brainer-orm,"['unit-testing', 'ruby-on-rails-5', 'rethinkdb', 'nobrainer']",72,FALSE,1,0
Should I reuse encapsulated constants when unit testing and how?,"<p>So, I am writing a unit test for a function.
The technical details are not important, but I wanted to share some code for clarity.<br>
Here is the function:</p>

<pre><code>export function getSalutations(lang: Salutation = Salutation.default): string[] {
    return SALUTATIONS[lang] || SALUTATIONS.default;
};

export const enum Salutation {
    de,
    es,
    default
};
const SALUTATIONS = {
    de: ['Hr.', 'Fr.'],
    es: ['Sr.', 'Sra.'],
    default: ['Mr.', 'Mrs.', 'Ms.']
};
</code></pre>

<p>An example for unit test:</p>

<pre><code>QUnit.module('getSalutations', (hooks) =&gt; {
    QUnit.test('null / default salutations', (assert) =&gt; {
        assert.ok(DW.Utils.isEqual(DW.Utils.getSalutations(null), ['Mr.', 'Mrs.', 'Ms.']));
    });
});
</code></pre>

<p>I do not want to copy the data like this, in order to test the method. I would like to reuse <code>SALUTATIONS</code> for my tests, so there is no redundant code. The problem is I can not use it, because it is not exported from the scope it lives in, so I have no way to access it.</p>

<p>So I am put before the following choices:</p>

<ol>
<li>I have to copy code as mocked data.</li>
<li>I have to expose encapsulated code just for unit tests</li>
</ol>

<p>I am not happy with both, so I hope someone can tell me what would be an optimal solution. Maybe there are other options, which I can not figure out?</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/47926296/should-i-reuse-encapsulated-constants-when-unit-testing-and-how,"['unit-testing', 'typescript', 'qunit']",261,TRUE,1,2
Inbuilt pipes cause failures when unit testing Angular 2 component,"<p>I have sample component which I would like to test.
When I am using custom pipe (e.g my custom pipe <code>concat</code>) its working fine.</p>

<pre><code>import { ConcatPipe } from 'path-to-concat-pipe';

@Component({
  selector: 'test',
  template: '{{ testProp | concat }}'
})
class TestComp {
  public testProp: Array = [2017, 2018];
}
</code></pre>

<p>But when I am trying to use <a href=""https://angular.io/docs/ts/latest/api/#!?query=pipe"" rel=""nofollow noreferrer"">inbuilt pipe</a> (e.g. <code>number</code>), my tests are failing without any informative error message.</p>

<pre><code>@Component({
  selector: 'test',
  template: '{{ testProp | number }}'
})
class TestComp {
  public testProp: number = 2017;
}
</code></pre>

<p>Sample spec code</p>

<pre><code>describe('TestComp', () =&gt; {
    let comp: TestComp;
  let fixture: ComponentFixture&lt;TestComp&gt;;

  beforeEach(async(() =&gt; {
    TestBed
    .configureTestingModule({
      declarations: [TestComp, ConcatPipe],

    })
    .compileComponents()
    .then(() =&gt; {
          fixture = TestBed.createComponent(TestComp);        
          fixture.detectChanges();
    })
    }));

  it('TestComp successfully initialized', () =&gt; {
    expect(fixture.componentInstance).toBeDefined()
  });
});
</code></pre>

<p>Also, I have tried to import DecimalPipe from '@angular/common' and add it to declarations array but it cause error</p>

<blockquote>
  <p>Type DecimalPipe is part of the declarations of 2 modules:
  CommonModule and DynamicTestModule!</p>
</blockquote>

<p>I am using angular 2.0 release version.</p>

<p><strong>UPD</strong></p>

<p>Test works fine in <a href=""https://plnkr.co/edit/aaAbqlFNCL8XBoky7Wv2?p=preview"" rel=""nofollow noreferrer"">plunker</a> @yurzui provided, but fails in my project. I guess issue may be related to my karma configuration files</p>

<p>karma.shim.js</p>

<pre><code>'use strict';

Error.stackTraceLimit = Infinity;
require('es6-shim');
require('reflect-metadata');
require('zone.js/dist/zone');;
require('zone.js/dist/long-stack-trace-zone');
require('zone.js/dist/async-test');
require('zone.js/dist/fake-async-test');
require('zone.js/dist/sync-test');
require('zone.js/dist/proxy');
require('zone.js/dist/jasmine-patch');
require('@angular/core/testing');

var appContext = require.context('./src', true, /root.spec.ts/);

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



testing.TestBed.initTestEnvironment(browser.BrowserDynamicTestingModule, browser.platformBrowserDynamicTesting());
</code></pre>

<p>karma.conf.js</p>

<pre><code>'use strict';

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

module.exports = function (config) {
    var _config = {
        basePath: '',

        frameworks: ['jasmine'],

        files: [
            {pattern: './karma-shim.js', watched: false},
            {pattern: './src/app/**/*spec.ts', watched: true, included: false}
        ],

        exclude: [],

        preprocessors: {
            './karma-shim.js': ['webpack', 'sourcemap']
        },

        webpack: webpackConfig,

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

        coverageReporter: {
            dir: 'coverage/',
            reporters: [
                {type: 'text-summary'},
                {type: 'html'}
            ]
        },

        browserNoActivityTimeout : 100000,

        webpackServer: {
            noInfo: true
        },

        reporters: ['story', 'coverage', 'progress'],

        port: 9876,

        colors: true,

        logLevel: config.LOG_DEBUG,

        autoWatch: false,

        browsers: ['PhantomJS'], 

        singleRun: true,
    };

    config.set(_config);

};
</code></pre>
",https://stackoverflow.com/questions/42072095/inbuilt-pipes-cause-failures-when-unit-testing-angular-2-component,"['javascript', 'unit-testing', 'angular', 'angular-pipe']",2662,TRUE,1,2
Configure Unit testing for DAO Layer with Hibernate in SpringBoot,"<p>I've created an application using Springboot and Hibernate and i want to configure unit testing for it.</p>

<p>first this is the DAO interface.</p>

<pre><code>public interface OrderDetailsDao {
    void createOrder(OrderDetails orderDetails);
    void updateOrder(OrderDetails orderDetails);
    void deleteOrder(OrderDetails orderDetails);
}
</code></pre>

<p>this is the DAO interface implemnetation</p>

<pre><code>public class OrderDetailsDaoImpl extends HibernateDaoSupport implements OrderDetailsDao {

    public void createOrder(OrderDetails orderDetails){
        getHibernateTemplate().save(orderDetails);
    }

    public void updateOrder(OrderDetails orderDetails){
        getHibernateTemplate().save(orderDetails);
    }

    public void deleteOrder(OrderDetails orderDetails){
        getHibernateTemplate().delete(orderDetails);
    }
}
</code></pre>

<p>Then I have created a test class as the following</p>

<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
public class OrderDetailsDaoTest {

    OrderDetails orderDetails = new OrderDetails();

    @Autowired
    OrderDetailsDao orderDetailsDao;

    @Test
    public void testCreateOrder(){
        orderDetails.setValue(101.91);
        orderDetailsDao.createOrder(orderDetails);
    }
}
</code></pre>

<p>I have put the application.properties file in resources of both test and src directories.</p>

<p>i tried to run this unit test case, but it fails because of the following error: </p>

<pre><code>Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.abdul.epl.repo.OrderDetailsDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
</code></pre>

<p>So could i know please the best way to configure the unit test for the DAO layer?</p>
",https://stackoverflow.com/questions/46015115/configure-unit-testing-for-dao-layer-with-hibernate-in-springboot,"['java', 'hibernate', 'spring-boot', 'junit']",1154,TRUE,1,1
Unit testing RxJava using Single.just(true) as the expected result,"<pre><code>Android Studio 3.0
RxJava-1
</code></pre>

<p>Unit testing the following code that will return a single with the result that could be either true or false depending if <code>findLastMessage</code> returns null or not.</p>

<pre><code> public Single&lt;Boolean&gt; hasLocalStorage() {
        return Single.fromCallable(() -&gt;
                chatStorageHelper.findLatestMessage() != null);
    }
</code></pre>

<p>In my test case I have the following:
<code>storageHelper</code> is a mock that will return a non-null value for this case</p>

<pre><code>@Test
    public void testHasLocalStorage_hasLocalStorage_returnTrue() {
        when(storageHelper.findLatestMessage()).thenReturn(new DBMessage());

        final Single&lt;Boolean&gt; result = Single.just(true);
        assertThat(localRepository.hasLocalStorage(), is(result));
    }
</code></pre>

<p>However, the test always fails because of this:</p>

<pre><code>Expected :is &lt;rx.internal.util.ScalarSynchronousSingle@712cfb63&gt; 
Actual   :&lt;rx.Single@32e54a9d&gt;
</code></pre>

<p>When I check what <code>Single.just(true)</code> returns is the following:</p>

<pre><code>public static &lt;T&gt; Single&lt;T&gt; just(final T value) {
        return ScalarSynchronousSingle.create(value);
    }
</code></pre>

<p>Calls the ScalarSynchronousSingle. I am wondering how can I change my test case so that a <code>rx.Single</code> is return from <code>Single.just(true)</code>?</p>

<p>Many thanks for any suggestions,</p>
",https://stackoverflow.com/questions/47228160/unit-testing-rxjava-using-single-justtrue-as-the-expected-result,"['java', 'android', 'unit-testing', 'rx-java']",4466,TRUE,1,2
Unit testing Vue components that rely on a global event bus,"<p>I declare an event bus in my global <code>app.js</code> like so:</p>

<pre><code>window.Event = new Vue();
</code></pre>

<p>The component looks like</p>

<pre><code>export default {
    data() {
        return {
            hasError: false,
            zip: '',
        };
    },

    methods: {
        setZip: function() {
            this.hasError = false;
            this.$emit('setZip', this.zip);
        },
    },

    mounted() {
        Event.$on('showErrors', (errors) =&gt; {
            this.hasError = errors.zip ? true : false;
        });

        this.zip = this.editZip;
    },

    props: [
        'editZip'
    ],
}
</code></pre>

<p>I unit test my components with <code>ava</code> with the following <code>helpers/setup.js</code>:</p>

<pre><code>const browserEnv = require('browser-env');
const hook = require('vue-node');
const { join } = require('path');

// Setup a fake browser environment
browserEnv();

// Pass an absolute path to your webpack configuration to the hook function.
hook(join(__dirname, './webpack.config.js'));
</code></pre>

<p>The <code>webpack.config.js</code> looks like:</p>

<pre><code>module.exports = {
    module: {
      loaders: [
          {
            test: /\.vue$/,
            loader: 'vue-loader',
          },
        {
          test: /\.js$/,
            loader: 'babel',
            exclude: /node_modules/,
          },
      ],
    },
  resolve: {
      extensions: ['.js', '.vue'],
      },
};
</code></pre>

<p>When running the following test</p>

<pre><code>import Vue from 'vue/dist/vue.js';
import test from 'ava';
import Zip from '../../resources/assets/js/components/Company/Zip.vue';

let vm;

test.beforeEach(t =&gt; {
    let Z = Vue.extend(Zip);

    vm = new Z({ propsData: {
        editZip: 1220
    }}).$mount();
});

test('that it renders a div with class form-group', t =&gt; {
    t.is(vm.$el.className, 'form-group');
});
</code></pre>

<p>it passes, but the following error gets thrown:</p>

<pre><code>[Vue warn]: Error in mounted hook: ""TypeError: Event.$on is not a function""

(found in &lt;Root&gt;)
TypeError: Event.$on is not a function
    at VueComponent.mounted (/mnt/c/code/leaflets/resources/assets/js/components/Company/City.vue:107:15)
    at callHook (/mnt/c/code/leaflets/node_modules/vue/dist/vue.js:2530:21)
    at mountComponent (/mnt/c/code/leaflets/node_modules/vue/dist/vue.js:2424:5)
    at VueComponent.Vue$3.$mount (/mnt/c/code/leaflets/node_modules/vue/dist/vue.js:7512:10)
    at VueComponent.Vue$3.$mount (/mnt/c/code/leaflets/node_modules/vue/dist/vue.js:9592:16)
    at Test._ava2.default.beforeEach.t [as fn] (/mnt/c/code/leaflets/tests/js/CompanyCity.js:12:9)
    at Test.callFn (/mnt/c/code/leaflets/node_modules/ava/lib/test.js:281:18)
    at Test.run (/mnt/c/code/leaflets/node_modules/ava/lib/test.js:294:23)
    at runNext (/mnt/c/code/leaflets/node_modules/ava/lib/sequence.js:58:44)
    at Sequence.run (/mnt/c/code/leaflets/node_modules/ava/lib/sequence.js:90:10)
    at Concurrent.run (/mnt/c/code/leaflets/node_modules/ava/lib/concurrent.js:41:37)
    at runNext (/mnt/c/code/leaflets/node_modules/ava/lib/sequence.js:58:44)
    at Sequence.run (/mnt/c/code/leaflets/node_modules/ava/lib/sequence.js:90:10)
    at runNext (/mnt/c/code/leaflets/node_modules/ava/lib/sequence.js:58:44)
    at Sequence.run (/mnt/c/code/leaflets/node_modules/ava/lib/sequence.js:90:10)
    at Bluebird.try (/mnt/c/code/leaflets/node_modules/ava/lib/runner.js:214:48)
    at tryCatcher (/mnt/c/code/leaflets/node_modules/bluebird/js/release/util.js:16:23)
    at Function.Promise.attempt.Promise.try (/mnt/c/code/leaflets/node_modules/bluebird/js/release/method.js:39:29)
    at Runner.run (/mnt/c/code/leaflets/node_modules/ava/lib/runner.js:214:22)
    at process.on.options (/mnt/c/code/leaflets/node_modules/ava/lib/main.js:82:10)
    at emitOne (events.js:96:13)
    at process.emit (events.js:191:7)
    at process.on.message (/mnt/c/code/leaflets/node_modules/ava/lib/process-adapter.js:14:10)
    at emitTwo (events.js:106:13)
    at process.emit (events.js:194:7)
    at process.nextTick (internal/child_process.js:766:12)
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)
</code></pre>

<p>I can't figure out where to declare the <code>window.Event = new Vue()</code> in my test, so that the tested component can access the <code>Event</code> variable. </p>
",https://stackoverflow.com/questions/43886458/unit-testing-vue-components-that-rely-on-a-global-event-bus,"['javascript', 'unit-testing', 'vue.js', 'ava']",1705,TRUE,7,1
unit testing express route controller with multiple external API requests,"<p>in my unit tests I need to mock some http requests. </p>

<pre><code>const getDashboardData = (req, res) =&gt; {
  const activeListings = articlesLib.getLiveArticles(req.user.id)
  const soldThisMonthPromise = articlesLib.getSoldArticles(req.user.id, {})
  const userDrafts = articlesLib.getDrafts(req.user.id)

  return Promise.all([activeListings, soldThisMonthPromise, userDrafts])
  .then((data) =&gt; {
    res.render(`${__dirname}/home`, {
      viewData: data
    })
  })
}

router.get('/', getDashboardData)
</code></pre>

<p>Each request from articleLib has the same url, but uri is different. I wanted to mock it with nock, but it doesn't support multiple mock for the same base url. Is there any tool that mock a response when given http request is detected?</p>
",https://stackoverflow.com/questions/45532521/unit-testing-express-route-controller-with-multiple-external-api-requests,"['unit-testing', 'express', 'nock']",118,FALSE,1,0
Unit testing ArrayMap throws Method put in android.util.ArrayMap not mocked,"<p>I am trying to unit test a method that uses array map and I keep getting the following exception:</p>

<pre><code>java.lang.RuntimeException: Method put in android.util.ArrayMap not mocked. See http://g.co/androidstudio/not-mocked for details.
</code></pre>

<p>code:</p>

<pre><code>  ArrayMap&lt;String, String&gt; sampleMap =new ArrayMap&lt;&gt;();
                            for (SampleInfo info : details.getSampleList())
                            {
                                sampleMap.put(info.getkey(),info.getName());
                            }
</code></pre>

<p>I have tried:</p>

<pre><code>testOptions {
        unitTests.returnDefaultValues = true
    }
</code></pre>

<p>This way the exception is avoided but the map is always empty. How to resolve this issue?</p>
",https://stackoverflow.com/questions/45124522/unit-testing-arraymap-throws-method-put-in-android-util-arraymap-not-mocked,"['java', 'android', 'unit-testing']",1300,TRUE,1,3
How to gracefully integrate unit testing where none is present?,"<p>I have been tasked with developing a document for internal testing standards and procedures in our company. I've been doing plenty of research and found some good articles, but I always like to reach out to the community for input on here.</p>

<p>That being said, my question is this: How do you take a company that has a very large legacy code base that is barely testable, if at all testable, and try to test what you can efficiently? Do you have any tips on how to create some useful automated test cases for tightly coupled code?</p>

<p>All of our new code is being written to be as loosely coupled as possible, and we're all pretty proud of the direction we're going with new development. For the record, we're a Microsoft shop transitioning from VB to C# ASP.NET development.</p>
",https://stackoverflow.com/questions/45468867/how-to-gracefully-integrate-unit-testing-where-none-is-present,"['unit-testing', 'standards', 'design-principles', 'principles']",41,TRUE,1,1
what are options for automated unit testing in angular js,"<p>I'm new for unit testing so i want to know best automated option for angular js app testing.</p>

<p>I found some framework call Jasmine and Karma but I want to know best option.</p>
",https://stackoverflow.com/questions/43633862/what-are-options-for-automated-unit-testing-in-angular-js,"['angularjs', 'unit-testing', 'jasmine', 'automated-tests', 'karma-jasmine']",266,FALSE,1,0
Unit testing: Required to mock methods of the class itself?,"<p>I've been doing some unit testing and just getting into the topic as a whole. </p>

<p>I stumbled upon the following scenario, suppose I have a class like this:</p>

<pre><code>class A{
  public B mehtod_1(B b){
    b = method_2(b);
    b = method_3(b);
    b += 1; 
    return b;
  }

  public B method_2(B b){
    // do something to B without external dependency
    return B;
  }

  public B method_3(B b){
    // do something else to B without external dependency
    return B;
  }
}
</code></pre>

<p>I can write tests for <code>method_2</code> and <code>method_3</code> without a problem, do different tests by configuring B in different ways and asserting the expected transformation on B after the call, those methods are atomic.</p>

<p>So my question is: </p>

<p>If I was to test <code>method_1</code> in an atomic way I would have to mock the calls to <code>method_2</code> and <code>method_3</code> since if I would actually call these methods I would not test <code>method_1</code> in an atomic manor. </p>

<p>In the latter case is <code>method_2</code> was broken then the tests for <code>method_1</code> and <code>method_2</code> would break, and that would be misleading. If I'd mock the <code>method_2</code> call inside the <code>method_1</code> test, only the <code>method_2</code> test would fail, giving a clearer indication of where the error is (namely somewhere in the business logic of <code>method_1</code> given all other invoked methods worked as expected). </p>

<p>Did I understand the concept here correctly?</p>

<p>On the other hand it is correct, if both tests fail, since in the real world, <code>method_1</code> cannot work without <code>method_2</code> working. </p>

<p>My gut would say atomicity of tests is what is desired, meaning the first solution where there is one test for <code>method_1</code>, for every possible outcome of <code>method_2</code> and <code>method_3</code> (statically mocked).</p>

<p>Is there a ""correct""/common/best practice way?</p>
",https://stackoverflow.com/questions/42929444/unit-testing-required-to-mock-methods-of-the-class-itself,['unit-testing'],506,TRUE,1,1
Unit testing asynchronous computation that has to be interrupted manually,"<p>I have got a class that records eyetracking data asynchronously. There are methods to <code>start</code> and <code>stop</code> the recording process. The data is collected in a collection and the collection can only be accessed if the recording thread has finished its work. It basically encapsulates all the threading and synchronizing so the user of my library doesn't have to do it.</p>

<p>The heavily shortened code (generics and error handling omitted):</p>

<pre><code>public class Recorder {
  private Collection accumulatorCollection;
  private Thread recordingThread;

  private class RecordingRunnable implements Runnable {
    ...

    public void run() {
      while(!Thread.currentThread().isInterrupted()) {
        // fetch data and collect it in the accumulator
        synchronized(acc) { acc.add(Eyetracker.getData()) }
      }
    }
  }

  public void start() {
    accumulatorCollection = new Collection();
    recordingThread = new Thread(new RecordingRunnable(accumulatorCollection));
    recordingThread.start();
  }

  public void stop() {
    recordingThread.interrupt();
  }

  public void getData() {
    try {
      recordingThread.join(2000);
      if(recordingThread.isAlive()) { throw Exception(); }
    }
    catch(InterruptedException e) { ... }

    synchronized(accumulatorCollection) { return accumulatorCollection; }
  }
}
</code></pre>

<p>The usage is quite simple:</p>

<pre><code>recorder.start();
...
recorder.stop();
Collection data = recorder.getData();
</code></pre>

<p>My problem with the whole thing is how to test it. Currently i am doing it like this:</p>

<pre><code>recorder.start();
Thread.sleep(50);
recorder.stop();
Collection data = recorder.getData();
assert(stuff);
</code></pre>

<p>This works, but it is non-deterministic and slows down the test suite quite a bit (i marked these tests as integration tests, so they have to be run separately to circumvent this problem).</p>

<p>Is there a better way?</p>
",https://stackoverflow.com/questions/42495499/unit-testing-asynchronous-computation-that-has-to-be-interrupted-manually,"['java', 'multithreading', 'unit-testing', 'asynchronous']",74,TRUE,1,1
C# Unit testing - check if a private method was reached,"<p>I am using C# MOQ library. </p>

<p>Lets say I want to create a <code>UnitTest</code> for this piece of code:</p>

<pre><code>if(condition){
    privateMethod();
}
else{
    logger.info(""didn't hit"")
}
</code></pre>

<p>I want to check if <code>privateMethod</code> was hit, I can't use the <code>Verify</code> function as it is private. How can I do that?</p>

<p>I thought about adding a <code>Status</code> member dedicated for the unit testing, which will hold the last location before exiting the tested method.</p>
",https://stackoverflow.com/questions/44364237/c-unit-testing-check-if-a-private-method-was-reached,"['c#', 'moq']",5462,TRUE,1,2
Does unit testing in AngularJS involve interaction with the template?,"<p>I want to test a function that redirects to a different route. However, I'm wondering whether making the browser ""click"" through Karma, is putting the test out of the scope of the unit testing and making it more like e2e testing.</p>

<p>I saw in <a href=""https://angular.io/docs/ts/latest/guide/testing.html#!#routed-component"" rel=""nofollow noreferrer"">Angular2 relative documentation</a> that it calls a ""HeroClick"" function, but I don't get exactly what is this function and where it comes from.</p>

<p>If someone can shed some light to my confused mind, I would appreciate it.</p>
",https://stackoverflow.com/questions/41445641/does-unit-testing-in-angularjs-involve-interaction-with-the-template,"['unit-testing', 'angular', 'angular2-routing']",35,FALSE,0,1
mocha javascript unit testing a function that return html string,"<p>i have a function that return a html string """" from array,</p>

<p>trying to write a mocha test for it. but the white spaces and \n are giving me hard time if i try to assert identical, and its not also flexiable to test html as if its string !.</p>

<p>how do you write tests for pure functions that return html strings ?</p>

<p>example:</p>

<pre><code>renderHtml(json){
  // .. function that parse json and return &lt;table&gt; of its content.
}
</code></pre>

<p>how can i test this function ?</p>

<pre><code>  var mod = require('./render');
  var count = (s1,s2) =&gt; (s1.match(new RegExp(s2, 'gi'))||[]).length;
  describe('should handle simple array', function () {
    let json = [{ ""id"": ""1"", ""name"": ""momen"" }];
    let result = mod.renderHtml(json);

    it('should have 1 h1', function () {
      assert.equal(count(result, '&lt;h1&gt;'), 1);
    })

    it('should have 4 ths', function () {
      assert.equal(count(result, '&lt;th&gt;'), 4);
    })

    it('should have 2 tr', function () {
      assert.equal(count(result, '&lt;tr&gt;'), 2);
    })

    it('should have 2 td', function () {
      assert.equal(count(result, '&lt;td&gt;'), 2);
    })
  })
</code></pre>

<p>i want to test result to be contain  tag, and table with X number of ths and X number or rows that contain X number of tds each row </p>
",https://stackoverflow.com/questions/45041452/mocha-javascript-unit-testing-a-function-that-return-html-string,"['javascript', 'unit-testing', 'tdd', 'mocha.js', 'chai']",1637,TRUE,0,1
Unit Testing with different behaviour on existance of a file,"<p>There are some cases that the software shall behave differently according to some environmental conditions, for example whether a file exists at some place or not.</p>

<p>In my case, I'm developing a library, and it is configured according to a configuration file in classpath, (and falls back to default behavior if the config file does not exists).</p>

<p>How shall I unit test this class?
I need to write tests for evaluating the class in following cases:</p>

<ul>
<li>the file does not exists on classpath</li>
<li>the file with content A exist on classpath</li>
<li>the file with content B exist on classpath</li>
</ul>

<p>But I don't know how to configure environment to justify all of them. And execute the test one after each other.</p>

<p>By the way I'm using Java, and I have both JUnit and TestNG on the test classpath.</p>

<hr>

<p>Edit:
One of the problems is that the config file resides in classpath, so if the <em>normal ClassLoader</em> finds and loads it, it returns the same content as long as the same class loader is used.
And I believe using a custom ClassLoader for testing is so complicated, that it needs tests to validate the tests!</p>
",https://stackoverflow.com/questions/46633248/unit-testing-with-different-behaviour-on-existance-of-a-file,"['java', 'unit-testing', 'tdd', 'testng']",316,TRUE,0,1
Unit Testing for private member List&lt;Integer&gt; mTasks in android,"<p>I am trying to write unit test cases for below class. Specially, for 'isSumOfTaskWeightIsValid()' method from the below. it has private member involved it. Could you please help writing test cases for that. I find it difficult because of the 'for loop' in that method where it loops over the 'mTasks'. Thanks in advance.</p>

<pre><code>Class TaskCard {

private List&lt;Integer&gt; mTasks = new ArrayList&lt;&gt;();
private boolean mIsGood;

public TaskCard(boolean isGood) { mIsGood = isGood}    

public void setUpListofTasks(DataBaseHelper db){
  mTasks.addAll(db.getTasks());
}

public boolean isSumOfTaskWeightIsValid(){
  int sum = 0;
  for(int taskWeight : mTasks)
  { sum += taskWeight;
  }
 return (sum&gt;0 || mIsGood);
}

}
</code></pre>
",https://stackoverflow.com/questions/47425552/unit-testing-for-private-member-listinteger-mtasks-in-android,"['android', 'unit-testing', 'junit', 'mockito', 'android-testing']",109,TRUE,0,1
"Dynamically loaded js is undefined while unit testing (karma, jasmine)","<p>Dynamically loaded js is undefined while unit testing (karma, jasmine)
I'm working on an angular js app and 
I've js libraries which are loaded dynamically(appended to head on some action). They are loaded this way because system.js cannot load them.
E.g dtjava.js which is used for launching signed jar through jnlp. Example for dynamically js loading.</p>

<pre><code>let script = document.createElement('script');
script.src = 'https://java.com/js/dtjava.js';
document.head.appendChild(script);
</code></pre>

<p>And then I use dtjava</p>

<pre><code>dtjava.launch({url: 'someTool.jnlp', params:{param1: ""852237""}}, {javafx: '8.0+'}, {};
</code></pre>

<p>This works perfectly, but I can't mock dtjava because it is undefined.
So, is it possible to mock dynamically loaded js?</p>
",https://stackoverflow.com/questions/43319588/dynamically-loaded-js-is-undefined-while-unit-testing-karma-jasmine,"['angularjs', 'unit-testing', 'karma-runner', 'karma-jasmine']",192,TRUE,0,1
Unit testing JavaScript function with ForEach with Tape and Sinon,"<p>I am struggling to unit test the following function. In particular I cannot get it to cover the highlighted code:</p>

<pre><code>function authCert(trustedCAFile){
    let ca = [];
    let cert = [];
    let trustedCA = String(fs.readFileSync(trustedCAFile));
    let trustedCALines = trustedCA.split(""\n"");

    trustedCALines.forEach(function(entry){

    cert.push(entry);
    if(entry.match(/-END CERTIFICATE-/)){
        **ca.push(cert.join(""\n""));
        cert = [];**
    }
});

return ca;
}
</code></pre>

<p>This is my current test:</p>

<pre><code>let test = require('tape');
let rewire = require('rewire');
let sinon = require('sinon');
let fs = require('fs');
let proxyquire = require('proxyquire');

test('should cycle through trusted ', function(t) {
  let authCert = rewire('../authCert');
  let getAuthCerts = certUtils.getAuthCert;

  let certStub = 'test';

  let fsStub = {
      readFileSync: () =&gt; {}
  };

  let ca = [];
  ca.push('1');

  certUtils.__set__('fs', fsStub);

  let result = getAuthorisedCerts(certStub);

  t.deepEquals(result, []);
  t.end();

});
</code></pre>

<p>I have looked at the documentation but as a noob I am unsure how to go about getting coverage and testing the highlighted code.</p>

<p>If anyone could help me or point me in the right direction I'd be very grateful.</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/45007083/unit-testing-javascript-function-with-foreach-with-tape-and-sinon,"['javascript', 'node.js', 'unit-testing', 'sinon']",796,FALSE,0,1
Object method mocking or spying for unit testing in Scala,"<p>Is there a way to mock or spy on methods in a Scala object?</p>

<pre><code>object Object {

  def fun(value: String) = println(value)

  def main(args: Array[String]): Unit = {
    fun(""executed"")
    sys.exit(0)
  }
}
</code></pre>

<p>I would like to do something like:</p>

<pre><code>spy(Object.fun)
</code></pre>

<p>I looked at <code>ScalaMock</code>, <code>EasyMock</code>, <code>JMock</code> and <code>Mockito</code> but couldn't really figure it out.</p>
",https://stackoverflow.com/questions/45278492/object-method-mocking-or-spying-for-unit-testing-in-scala,"['scala', 'mocking', 'scalatest', 'spy']",1436,TRUE,0,1
C# MVC Unit Testing: Check if View exists by name,"<p>I have many controller actions that return a view. Currently we just test whether the ActionResult is not null, but this doesn't actually test whether a valid view will be returned. </p>

<p>I do not want to just check the name, i feel like this is too fragile. What i want to do is grab the view name returned in the ActionResult and somehow check if that view exists/compiles. </p>
",https://stackoverflow.com/questions/45889063/c-mvc-unit-testing-check-if-view-exists-by-name,"['c#', 'asp.net-mvc', 'unit-testing', 'view']",432,FALSE,0,0
how to write a unit testing function for my function?,"<p>This is a function i created:</p>

<pre><code>def hab(h, a, b= None):
    if b != None:
        result = (""{} , {} , {}"".format(h, b, a))
    else:
        result = (""{} , {}"".format(h, a))
    return result
</code></pre>

<p>I'm trying to write a unit testing for my function, the unit test should assert the function correctness when two or three parameters are provided.</p>

<p>This is my frame:</p>

<pre><code>class hab_Test_Class(unittest.TestCase):
   def test_pass2(self):

   def test_pass3(self):

# i'll use code below to run the unit test
t = hab_Test_Class()
suite = unittest.TestLoader().loadTestsFromModule(t)
unittest.TextTestRunner().run(suite)
</code></pre>

<p>I really have little sense of what the unit testing is doing, but not quite get it. </p>
",https://stackoverflow.com/questions/46713912/how-to-write-a-unit-testing-function-for-my-function,"['python', 'unit-testing']",1044,TRUE,0,2
Unit Testing php from command line throws error at com_create_guid(),"<p>I am writing unit tests using PHPUnit 4.8 with Laravel 5.1, OS is Windows 10.</p>

<p>One of these tests involves adding a new record to a database using an array of attributes. I am not changing any of the existing code, it is not my material. Within that array, the following appears.:</p>

<p><code>$attributes[]</code>                 </p>

<pre><code>'TAX_EXEMPT_NO'      =&gt; $customer-&gt;TAX_EXEMPT_NO,
'DOC_GUID'           =&gt; com_create_guid(),
'BILL_TO_CONTACT_ID' =&gt; 1,
</code></pre>

<p>where <a href=""http://php.net/manual/en/function.com-create-guid.php"" rel=""nofollow noreferrer""><code>com_create_guid</code></a> is a PHP global function for generating a global unique identifier.</p>

<p>Then my test file: </p>

<p><code># OrderTest.php</code></p>

<pre><code>class ApiCpOrderTest extends TestCase
{
    public function testPutDocumentWithNewDocNoContacts()    
    {
            $doc = $this-&gt;getOrder();

            $doc-&gt;TKT_NO = null;
            $doc-&gt;DRW_ID = 1;
            $doc = $doc-&gt;toArray();
            $this-&gt;doc['CONTACTS'] = null;

            $this-&gt;assertInternalType('object', $this-&gt;orderObj-&gt;putDocument($this-&gt;docTypT, $doc));
        }
}
</code></pre>

<p>Running it from the command line, 
<code>phpunit tests/path/OrderTest.php</code> throws this error: </p>

<blockquote>
  <p>PHP Fatal error:  <strong>Call to undefined function
  App\Lib\Api\CounterPoint\com_create_guid()</strong> in
  C:\Users\cmahoney\workspace\csos-counterpoint-org-trunk\app\Lib\Api\CounterPoint\Order.php
  on line 132</p>
</blockquote>

<p><strong>I am not rewriting any of the existing code- that needs to be untouched.</strong> Is there any way that I can get the command line to understand <code>com_create_guid</code> or other php functions while running tests? Again, the issue is when the console begins executing scripts in another file (which I can not edit) and does not undrstand com_create_guid(). </p>
",https://stackoverflow.com/questions/43590125/unit-testing-php-from-command-line-throws-error-at-com-create-guid,"['php', 'windows', 'unit-testing', 'command', 'phpunit']",21,FALSE,0,0
How to Mock Session variables in ASP.net core unit testing project?,"<p><strong>How to Mock Session variables in ASP.net core unit testing project?</strong></p>
<p><strong>1) I have created a mock object of a session.</strong></p>
<pre><code>Mock&lt;HttpContext&gt; mockHttpContext = new Mock&lt;HttpContext&gt;();
Mock&lt;ITestSession&gt; mockSession = new Mock&lt;ISession&gt;().As&lt;ITestSession&gt;();
</code></pre>
<p><strong>2) Setup GetString() MEthod</strong></p>
<pre><code>mockSession.Setup(s =&gt; s.GetString(&quot;ModuleId&quot;)).Returns(&quot;1&quot;);
</code></pre>
<p><strong>3) created controllerContext and assigned mockhttpContext object</strong></p>
<pre><code>controller.ControllerContext.HttpContext = mockHttpContext.Object; 
</code></pre>
<p><strong>4) Trying to read from a controller.</strong></p>
<pre><code>HttpContext.Session.GetString(&quot;ModuleId&quot;)
</code></pre>
<p>Whereas I get a null value of &quot;ModuleId&quot;. Please help me to mock session GetString() method</p>
<p><strong>Example:</strong></p>
<pre><code>        //Arrange
        //Note: Mock session 
        Mock&lt;HttpContext&gt; mockHttpContext = new Mock&lt;HttpContext&gt;();
        Mock&lt;ITestSession&gt; mockSession = new Mock&lt;ISession&gt;().As&lt;ITestSession&gt;();
        //Cast list to IEnumerable
        IEnumerable&lt;string&gt; sessionKeys = new string[] { };
        //Convert to list.
        List&lt;string&gt; listSessionKeys = sessionKeys.ToList();
        listSessionKeys.Add(&quot;ModuleId&quot;);
        sessionKeys = listSessionKeys;
        mockSession.Setup(s =&gt; s.Keys).Returns(sessionKeys);
        mockSession.Setup(s =&gt; s.Id).Returns(&quot;89eca97a-872a-4ba2-06fe-ba715c3f32be&quot;);
        mockSession.Setup(s =&gt; s.IsAvailable).Returns(true);
        mockHttpContext.Setup(s =&gt; s.Session).Returns(mockSession.Object);
     mockSession.Setup(s =&gt; s.GetString(&quot;ModuleId&quot;)).Returns(&quot;1&quot;);         

        //Mock TempData
        var tempDataMock = new Mock&lt;ITempDataDictionary&gt;();
        //tempDataMock.Setup(s =&gt; s.Peek(&quot;ModuleId&quot;)).Returns(&quot;1&quot;);

        //Mock service
        Mock&lt;ITempServices&gt; mockITempServices= new Mock&lt;ITempServices&gt;();
        mockITempServices.Setup(m =&gt; m.PostWebApiData(url)).Returns(Task.FromResult(response));

        //Mock Management class method
        Mock&lt;ITestManagement&gt; mockITestManagement = new Mock&lt;ITestManagement&gt;();
        mockITestManagement .Setup(s =&gt; s.SetFollowUnfollow(url)).Returns(Task.FromResult(response));

        //Call Controller method
        TestController controller = new TestController (mockITestManagement .Object, appSettings);
        controller.ControllerContext.HttpContext = mockHttpContext.Object;            
        controller.TempData = tempDataMock.Object;

        //Act
        string response = await controller.Follow(&quot;true&quot;);

        // Assert
        Assert.NotNull(response);
        Assert.IsType&lt;string&gt;(response);
 
</code></pre>
",https://stackoverflow.com/questions/42269770/how-to-mock-session-variables-in-asp-net-core-unit-testing-project,"['asp.net', 'unit-testing']",9532,TRUE,6,6
mock unit testing file reading and writing in python 2.7,"<p>I am creating a file downloader API in Python. The API will be able to download files from a host using FTP or SFTP (I have implemented separate classes for both) and should also keep track of already downloaded files in the form of a CSV file, database table or Excel file (I have implemented separate classes for all). I have done some basic implementation and now I want to unit test all my methods (because I don't want to actually download files from a real host and save on my machine but just want to make sure it works the way it is supposed to work). I am having hard time finding a good starting point for unit testing, specially to unit test the file handling part and the FTP, SFTP downloader methods. My complete code can be found here 
<a href=""https://ghostbin.com/paste/o8jxk"" rel=""nofollow noreferrer"">https://ghostbin.com/paste/o8jxk</a></p>

<p>Any help or useful learning sources will be appreciated.</p>

<p>The code for file read write class </p>

<pre><code>class CSVManager(DownloadManager):

        def __init__(self, file_path, csv_file):
    self.path = os.path.join(file_path, csv_file)

def register_download(self, file_name):
    files = file_name
    with open(self.path, ""wb"") as csv_file:
        writer = csv.writer(csv_file, delimiter=',')
        for file in files:
            writer.writerow(file)

def downloaded(self):
    downloaded_files = []
    with open(self.path, ""rb"") as csv_file:
        reader = csv.reader(csv_file)
        for file in reader:
            downloaded_files.append(file)
    return downloaded_files
</code></pre>
",https://stackoverflow.com/questions/45253714/mock-unit-testing-file-reading-and-writing-in-python-2-7,"['python', 'unit-testing', 'ftp', 'mocking', 'filesystems']",1465,FALSE,0,2
Laravel unit testing with sqlite on Virtualbox does not work,"<p>Testing on Virtualbox with laravel dusk and using as test database sqlite I get</p>

<pre><code>unlink(/var/www/laravel/database/database.sqlite): Text file busy
</code></pre>

<p>after researches I understand this problem is mainly because of Virtualbox shared folder.</p>

<p>I was trying to call the sqlite file from /tmp folder but in this case I get </p>

<pre><code>Database (/tmp/database.sqlite) does not exists
</code></pre>

<p>How would I manage this issue to have my tests running</p>
",https://stackoverflow.com/questions/46667881/laravel-unit-testing-with-sqlite-on-virtualbox-does-not-work,"['sqlite', 'testing', 'laravel-5', 'virtualbox', 'laravel-dusk']",61,FALSE,0,1
Unit Testing : No provider for &quot;InterceptableStoreFactory&quot; even if added to &quot;providers&quot;,"<p>I'm working on unit tests within my Angular app , i'm using TestBed approach ,</p>

<p>I'm testing components , so each spec file looks like this</p>

<pre><code>import...
describe('AppComponent', () =&gt; {
// Importing dependecies
    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            imports : [RouterTestingModule , HttpModule , FormsModule ],
            declarations: [AppComponent
            ],
            providers: [AUTH_PROVIDERS ,UserService, SharedclientService, RouteNavigator, JwtHelper, ReloadTokenService, ShopService
                , EnvVarsService, ProfileService, LocalStorageService, ApiVersionInterceptor, ApiTrackingInterceptor, MonitoringService ,
                { provide: 'LOCAL_STORAGE_SERVICE_CONFIG', useValue: userConfig } , TokenUtilService , HttpInterceptorService ,
                { provide: InterceptableStoreFactory, useClass: InterceptableStoreFactoryMock },ReloadTokenEventService , InterceptableStoreFactory

            ]

        }).compileComponents();
    }));
    // detecting changes every times
    beforeEach(() =&gt; {
        fixture = TestBed.createComponent(AppComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    // Test case 0 (compilation of the component)
    it('AppComponent is well defined', () =&gt; {
        expect(component).toBeDefined();
    });

    // Test case 1
    it('test', () =&gt; {
        expect(""1"").toBe(""1"");
    });
});
</code></pre>

<p>This approach of testing , is causing the failure of the whole test suite , if the dependencies importing isn't well.</p>

<p><strong>For example</strong> : in this test suite , it throws this error :</p>

<blockquote>
  <p>No provider for <strong>InterceptableStoreFactory</strong>! 
  It seems to be strange , as i'm importing this service in my <strong>providers</strong> (last one)</p>
</blockquote>

<p>This causes almost the failure of all test cases assince the verification of the fixture imports is ""<em>beforeEach</em>"" test cases</p>

<p><strong>Am looking for</strong> better ideas for :</p>

<ol>
<li>the problem of ""no provider for service"" (which is already added to providers"" </li>
</ol>

<p>and for </p>

<ol start=""2"">
<li>unit testBed better way of testing</li>
</ol>
",https://stackoverflow.com/questions/47017663/unit-testing-no-provider-for-interceptablestorefactory-even-if-added-to-pro,"['angular', 'unit-testing', 'jasmine', 'fixtures', 'testbed']",2322,TRUE,6,2
Difference between various verifySignatures functions in Corda flow unit testing,"<p>What's the difference between those three methods in Corda flow unit testing?</p>

<pre><code>ptx.verify(servicehub)
ptx.verifyRequiredSignatures()
ptx.verifySignaturesExcept(vararg allowedToBeMissed)
</code></pre>

<p>Because now I cannot use <code>ptx.verifySignatures()</code> as before and I have those three options!
Thanks</p>
",https://stackoverflow.com/questions/47534217/difference-between-various-verifysignatures-functions-in-corda-flow-unit-testing,"['unit-testing', 'testing', 'intellij-idea', 'kotlin', 'corda']",80,TRUE,0,1
"Jasmine, React &amp; AJAX: Unit testing function within a function","<p>Here's the code I would like to test. Specifically, I want to spy on a utility called <code>Linkvalidation.validate</code> to make sure that it is called when <code>handleSave()</code> is called. </p>

<p>This code lives in a component called the <code>CondensedFormModal</code>: </p>

<pre><code>handleSave() {
  LinkValidation.validate(this.state.url)
  .then((response) =&gt; {
    if (response.success) {
      this.setState({
        message: ''
      });
    }
  })
  .fail((error) =&gt; {
    if (error &amp;&amp; error.message &amp;&amp; error.message.match(/invalid internal link/)) {
      this.setState({
        message: 'The URL is an internal link. Please use a public link.'
      });
    } else {
      this.setState({
        message: 'The URL is invalid.'
      });
    }
  });
</code></pre>

<p>Here is the LinkValidation.validate utility I'm using in the <code>handleSave</code> function above: </p>

<pre><code>  define([
  'module/api-call'
  ], function(
  ApiCall
  ) {

  'use strict';

  // Calls validation API
  function validate(link) {
  var deferred = $.Deferred();

  ApiCall.apiCall(
    '/url/check',
    { link: link },
    'POST',
    function(data) {
      if (data.success === true) {
        deferred.resolve(data);
      } else {
        // This link is not valid
        deferred.reject(data);
      }
    },
    function() {
      deferred.reject();
    }
  );

  return deferred;
}

return {
  validate: validate
};
});
</code></pre>

<p>Here is my test file-- </p>

<p>Import statement: 
<code>import { validate } from 'modules/link-validation.js';</code></p>

<p>Test:</p>

<pre><code>describe('when the URL is an internal link', () =&gt; {
          it('displays a unique error message', (done) =&gt; {
            let modal = shallowInstance(&lt;CondensedFormModal /&gt;);
            modal.setState({
              url: 'https://internal.example.com'
            });

            let x = jasmine.createSpy('validate').and.returnValue({
              message: ""invalid internal link"",
              success: false,
              url: 'https://example.com'
            });

            modal.handleSave();
            _.defer(() =&gt; {
              expect(x).toHaveBeenCalled();
              done();
            });
          });
   });
</code></pre>

<p>When I run this test, it consistently fails with the message ""Expected spy validate to have been called.""</p>

<p>After looking at the Jasmine docs (<a href=""https://jasmine.github.io/2.1/introduction"" rel=""nofollow noreferrer"">https://jasmine.github.io/2.1/introduction</a>) and various other Stack Overflow questions (<a href=""https://stackoverflow.com/questions/22140869/unit-test-with-spy-is-failing-says-spy-was-never-called"">Unit test with spy is failing. Says spy was never called</a> , <a href=""https://stackoverflow.com/questions/31634863/jasmine-test-case-error-spy-to-have-been-called"">Jasmine test case error &#39;Spy to have been called&#39;</a> , etc.) I'm unable to make this work. I've also tried <code>callFake</code> and <code>callThrough</code> instead of <code>returnValue</code>. </p>

<p>Any ideas on how to spy on <code>LinkValidation.validate</code> to assure that it was called?</p>
",https://stackoverflow.com/questions/42683647/jasmine-react-ajax-unit-testing-function-within-a-function,"['javascript', 'ajax', 'unit-testing', 'reactjs', 'jasmine']",210,FALSE,0,1
Laravel cookies not available in service provider during unit testing,"<p>I have a service provider which instantiates a <code>CartCookie</code> class which generates a unique cookie for saving shopping carts. It's a singleton class and it's injected into the service container.</p>

<p>CartCookieServiceProvider.php</p>

<pre><code>public function boot(Request $request)
    {
        $this-&gt;app-&gt;singleton(CartCookie::class, function ($app) use ($request) {
            return new CartCookie($request);
        });
    }
</code></pre>

<p>CartCookie.php</p>

<pre><code>use App\Cart;
use Illuminate\Http\Request;

class CartCookie
{
    private $id;
    private $request;

    function __construct(Request $request)
    {
        $this-&gt;request = $request;

        if ($request-&gt;cookie('cart_id')) {
            $this-&gt;id = $request-&gt;cookie('cart_id');
        } else {
            $this-&gt;id = $this-&gt;generateUniqueCartId();
        }
    }

    public function id()
    {
        return $this-&gt;id;
    }

    private function generateUniqueCartId()
    {
        do {
            $id = md5(time() . 'cart' . rand(100000000000000, 9999999999999999));
        } while (Cart::find($id));

        return $id;
    }
}
</code></pre>

<p>In the <code>CartCookie</code> class I check for the existence of a <code>cart_id</code> cookie. Works perfectly fine when using the application! </p>

<p>My issue is that during unit tests, the <code>cart_id</code> cookie is empty, but only when the <code>Request</code> comes from the service provider. If I obtain the <code>Request</code> from a Controller later on in the lifecycle for example, the cookie is present.</p>

<p>Here is an example of a test:</p>

<pre><code>/** @test */
    public function get__store_checkout__checkout_displays_database_cart_correctly()
    {
        $cart = $this-&gt;createDatabaseCart();

        $cookie = ['cart_id' =&gt; Crypt::encrypt($this-&gt;cartCookie)];

        $response = $this-&gt;call('get', route('root.store.checkout'), [
            'seller_id' =&gt; $cart-&gt;seller-&gt;id,
        ], $cookie);

        $cart-&gt;seller-&gt;items()-&gt;each(function ($item) use ($response) {
            $this-&gt;assertContains($beat-&gt;item, $response-&gt;getContent());
        });
    }
</code></pre>

<p>I can tell the existence when I <code>dd()</code> the request cookies in both the service provider and the controller that handles the cart functionality. For some reason, only during unit tests, the request doesn't contain the cookie yet in the service provider.</p>

<p>Hope this makes sense.</p>
",https://stackoverflow.com/questions/41833168/laravel-cookies-not-available-in-service-provider-during-unit-testing,"['php', 'laravel']",1356,TRUE,0,1
Unit testing using testthat for R packages with compiled code,"<p>I am currently developing an R package where most of the computational work is done in C code. In particular, I have several complex C routines for which I then wrap with an R function. These I know I can test using testthat because the namespace includes the C function called (I am using roxygen comments to generate the namespace).</p>

<p>The difficulty I am having is that some of these C routines have a few complicated subroutines, the output of which is non-trivial to check. These functions are never called from R directly, so there is no code in my R/ directory that has a roxygen comment that results in the namespace making these functions available. What I want to do is write an R routine that performs the same computation and then use testthat to compare against the output of the C function. I have done this and it works great when I load the entire shared library (using dyn.load), but I don't think this is the proper approach for tests in a package that I intend to submit to CRAN.</p>

<p>My current workaround is to create a dummy function in a file in my R/ directory that then has a roxygen comment for each of the functions I wish to load. That way when I run devtools::document(), these functions are included in the namespace.</p>

<p>Is this the best approach, or is there another method that is better/preferred?</p>
",https://stackoverflow.com/questions/42150135/unit-testing-using-testthat-for-r-packages-with-compiled-code,"['c', 'r']",61,FALSE,0,0
Unit testing a void method in an internal static class,"<p>How do we go about testing a void method without instantiating the object in the test class? I understand in an internal static class we are unable to use ""new"" to create an object to test it. I've unit tested by creating objects for non static class but I  haven't dealt with an internal static class and am stuck. Any guidance would be great. </p>

<p>Here is the class/method in question:</p>

<pre><code>internal static class Util
{
    public static void AssertBytesEqual(byte[] expected, byte[] actual)
    {
        if (expected.Length != actual.Length)
        {
            Debugger.Break();
            throw new CryptographicException(""The bytes were not of the expected length."");
        }

        for (int i = 0; i &lt; expected.Length; i++)
        {
            if (expected[i] != actual[i])
            {
                Debugger.Break();
                throw new CryptographicException(""The bytes were not identical."");
            }
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/46436703/unit-testing-a-void-method-in-an-internal-static-class,"['c#', 'unit-testing', 'testing', 'methods', 'void']",1205,TRUE,0,1
Unit testing Angular 2 authGuard; spy method is not being called,"<p>I'm trying to unit test my auth guard service. From <a href=""https://stackoverflow.com/a/40301110/2800116"">this answer</a> I was able to get this far, but now when I run the unit test for this, it says <code>Expected spy navigate to have been called</code>.</p>

<p>How to I get my spied router to be used as <code>this.router</code> in the service?</p>

<h3>auth-guard.service.ts</h3>

<pre class=""lang-js prettyprint-override""><code>import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';

@Injectable()
export class AuthGuardService {

  constructor(private router:Router) { }

  public canActivate() {
    const authToken = localStorage.getItem('auth-token');
    const tokenExp = localStorage.getItem('auth-token-exp');
    const hasAuth = (authToken &amp;&amp; tokenExp);

    if(hasAuth &amp;&amp; Date.now() &lt; +tokenExp){
      return true;
    }
    this.router.navigate(['/login']);
    return false;
  }
}
</code></pre>

<h3>auth-guard.service.spec.ts</h3>

<pre class=""lang-js prettyprint-override""><code>import { TestBed, async, inject } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';

import { AuthGuardService } from './auth-guard.service';

describe('AuthGuardService', () =&gt; {
  let service:AuthGuardService = null;
  let router = {
    navigate: jasmine.createSpy('navigate')
  };

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      providers: [
        AuthGuardService,
        {provide:RouterTestingModule, useValue:router}
      ],
      imports: [RouterTestingModule]
    });
  });

  beforeEach(inject([AuthGuardService], (agService:AuthGuardService) =&gt; {
    service = agService;
  }));

  it('checks if a user is valid', () =&gt; {
    expect(service.canActivate()).toBeFalsy();
    expect(router.navigate).toHaveBeenCalled();
  });
});
</code></pre>

<p>Replacing <code>RouterTestingModule</code> with <code>Router</code> like in the example answer throws <code>Unexpected value 'undefined' imported by the module 'DynamicTestModule'</code>.</p>
",https://stackoverflow.com/questions/41496194/unit-testing-angular-2-authguard-spy-method-is-not-being-called,"['unit-testing', 'angular', 'angular2-routing', 'angular2-testing']",9016,TRUE,6,2
How to prevent code exit during Python 3.6 unit testing,"<p>As I write functions and classes with Python 3.6 I try to write unit tests as soon as I am capable. I am writing a simple function that tests whether or not a file exists at a user-specified location that looks like this:</p>
<pre><code>import os
import sys
import unittest

def verify_file_existance(file_path, file_name):
    total_name = file_path + file_name
    if os.path.isfile(total_name):
        return
    sys.exit('{}{}{}'.format('FATAL ERROR: ', file_name, 'does not exist'))
</code></pre>
<p>The unit test for the above function looks like</p>
<pre><code>class InputFileTest(unites.TestCase):
    def test_verify_file_existance(self):
        file_name = 'Test.csv'
        file_path = '../../Data/VandV/Input_Reader/'
        verify_file_existance(file_path, file_name)
</code></pre>
<p>If the file exists at the desired location, the test passes successfully; however, if the file does not exist, the program exits with a <em>Fatal Warning</em>.  This is how I want the program to behave during normal operation; however, in unit testing, I want to purposefully be able to place an incorrect path and register that as a successful test, to prove the program does what I want.  In other words during one test case, I don't want the program to exit. Is there a way to do this during unit testing?</p>
",https://stackoverflow.com/questions/47230145/how-to-prevent-code-exit-during-python-3-6-unit-testing,"['python', 'python-3.x']",110,TRUE,-1,2
Unit Testing with AngularJS 1.5+ using $componentController - Double data binding,"<p>I'm currently facing a problem with my testing code.
An example is better than 10 thousands words so here it is.</p>

<pre><code>describe('Initilazing', () =&gt; {

    let $componentController, scope;
    beforeEach(inject((_$componentController_, _$rootScope_) =&gt; {
        $componentController = _$componentController_;
        scope = _$rootScope_.$new();
        scope.name = 'Testing...';
    }));

    it('Should have the parent scope double binded', () =&gt; {
        let $ctrl = $componentController('sasInput', scope, { api: scope.sasInput });
        $ctrl.onInit();

        scope.$apply();
        expect(scope.sasInput).not.toBeUndefined();
    });
});


class SasInputController() {
    constructor() {
      'ngInject';
    }


    $onInit() {
        this.api = { clear: this.clear.bind(this) };
    }

    clear() {
        this.input = null;
    }
}

export default {
    ...
    bindings: {
        api: '='
    }
}
</code></pre>

<p>Here's the deal, inside my component, scope.sasInput should be updated with the current component api on the $onInit. But it is not.
What do I do wrong here ?</p>

<p>Can you help, please ?
Thank you.</p>
",https://stackoverflow.com/questions/45944040/unit-testing-with-angularjs-1-5-using-componentcontroller-double-data-bindin,"['angularjs', 'jasmine', 'jestjs']",755,TRUE,0,2
Unit testing and minimizing &quot;Arrange&quot; phase with central DI logic,"<p>The only problem I have with my unit tests is that my <code>Arrange</code> phases (in <code>Arrange-Act-Assert pattern</code>) are quite long so that maintainability problems arise. I have dozens of registrations which I make in constructor of test classes. Some of the test classes have common registrations and I thought that I can move all of these registrations in one central place and use <code>AssemblyInitialize</code> attribute on it (e.g. this approach will be like the registration part in <code>Global.asax</code> or <code>Startup.cs</code>). And if one wants to override the registered type, it can simply re-registers it (my container overrides the old registered type in that case). However, there will be some extra registrations made for some test classes too.</p>

<p>Would that be a bad decision? And if so, why? </p>

<p>Are there any third party tools that can help me with that (maybe in a better way)?</p>

<p>Would my unit test timings take a great hit by doing this? Because some of the test classes have only a few registrations. Should I use something to ignore these central registrations for them maybe?</p>

<p><strong>Edit:</strong></p>

<p>Sample Code:</p>

<pre><code>private CustomersController controller;

public CustomersControllerTests()
{
    var container = ContainerFactory.GetContainer();
    MapperConfiguration autoMapperConfig = new MapperConfiguration(cfg =&gt;
    {
        cfg.AddProfile&lt;DefaultMappingProfile&gt;();
    });
    container.RegisterInstance(autoMapperConfig);
    container.Register&lt;Common.Contracts.Mapper.IMapper, AutoMapperWrapped&gt;(Lifetime.Singleton);
    container.Register&lt;IProxy, BusinessProxy&gt;();
    container.Register&lt;IDataContext, FakeDataContext&gt;();
    container.Register&lt;IUnitOfWork, FakeUnitOfWork&gt;();
    container.Register&lt;ICustomerBusiness, CustomerBusiness&gt;();
    //...Some more registrations
    controller = new CustomersController();
} 

[TestMethod]
public async Task GetCustomerById_ForNonExistingCustomer_ReturnsNotFound()
{
    //Act
    var result = await controller.GetCustomerById(0);

    //Assert
    Assert.IsInstanceOfType(result, typeof(NotFoundResult));
}
</code></pre>

<p>For this test method, the Arrange part is in the constructor of the test class as shown.</p>
",https://stackoverflow.com/questions/47509323/unit-testing-and-minimizing-arrange-phase-with-central-di-logic,"['c#', 'unit-testing', 'dependency-injection', 'mstest']",610,TRUE,0,1
How to spy method in angular-cli Jasmine unit testing,"<p><strong>login.component.ts:</strong></p>

<pre><code>@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  loginForm: FormGroup;
  email: AbstractControl;
  password: AbstractControl;
  isError: boolean;
  errorMessage: string;
  constructor(public loginService: LoginService, fb: FormBuilder, public router: Router, public helperService: HelperService) {
    this.loginForm = fb.group({
      'email': ['', Validators.compose([Validators.required, Validators.email, Validators.minLength(4), Validators.maxLength(50)])
      ],
      'password': ['', Validators.compose([Validators.required, AppValidator.digitsOnly, Validators.minLength(4), Validators.maxLength(50)])
      ]
    });
  }
    this.email = this.loginForm.controls['email'];
this.password = this.loginForm.controls['password'];
  ngOnInit() { }

  onLogin(loginForm: LoginForm): void {
    this.isError = false;
    if (this.loginForm.valid) {
      // if email='test@gmail.com'&amp; password='123456', login will success else it will fail.
      this.loginService.fakeLogin(loginForm)
        .subscribe((res: LoginResponse) =&gt; {
          const url = '/dashboard';
          this.router.navigate([url]);
        },
        (err: ErrorResponse) =&gt; {
          this.errorMessage = err.message;
          this.isError = true;
        });
    }
  }
}
</code></pre>

<p><strong>login.component.html:</strong></p>

<pre><code>&lt;div class=""login""&gt;
    &lt;h1&gt;Login&lt;/h1&gt;
    &lt;p *ngIf=""isError""&gt;
        &lt;ngb-alert [type]=""'danger'"" [dismissible]=""true"" (close)=""closeAlert()""&gt;{{ errorMessage }}&lt;/ngb-alert&gt;
    &lt;/p&gt;
    &lt;form method=""post"" [formGroup]=""loginForm"" (ngSubmit)=""onLogin(loginForm.value)""&gt;
        &lt;div class=""form-group row"" [ngClass]=""helperService.getInputValidationClass(loginForm,'email')""&gt;
            &lt;div class=""col-sm-12""&gt;
                &lt;input [formControl]=""email"" type=""text"" class=""form-control"" id=""email"" placeholder=""Email""&gt;
                &lt;span *ngIf=""helperService.showCtrlValidationMsg(loginForm,'email')"" class=""help-block sub-little-text text-danger""&gt;{{helperService.getCtrlValidationMsg(loginForm,'email')}}&lt;/span&gt;
            &lt;/div&gt;
        &lt;/div&gt;
        &lt;div class=""form-group row"" [ngClass]=""helperService.getInputValidationClass(form,'password')""&gt;
            &lt;div class=""col-sm-12""&gt;
                &lt;input [formControl]=""password"" type=""password"" class=""form-control"" id=""password"" placeholder=""Password""&gt;
                &lt;span *ngIf=""helperService.showCtrlValidationMsg(loginForm,'password')"" class=""help-block sub-little-text text-danger""&gt;{{helperService.getCtrlValidationMsg(loginForm,'password')}}&lt;/span&gt;
            &lt;/div&gt;
        &lt;/div&gt;
        &lt;button type=""submit"" [disabled]=""helperService.isFormSubmitDisabled(loginForm,helperService.isProcessing)"" class=""btn btn-primary btn-block btn-large login-submit""&gt;
          &lt;span &gt;Sign in&lt;/span&gt;&lt;span *ngIf=""helperService.isProcessing""&gt;Processing...&lt;i class=""fa fa-spinner fa-spin fa-fw"" aria-hidden=""true""&gt;&lt;/i&gt;&lt;/span&gt;
        &lt;/button&gt;
    &lt;/form&gt;
&lt;/div&gt;
</code></pre>

<p><strong>login.component.spec.ts:</strong></p>

<pre><code>import { By } from '@angular/platform-browser';
import { LoginService } from './login.service';
import { async, ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { SlimLoadingBarModule } from 'ng2-slim-loading-bar';
import { SlimLoadingBarService } from 'ng2-slim-loading-bar';
import { RouterTestingModule } from '@angular/router/testing';

import { LoginComponent } from './login.component';
import { HelperService } from '../shared/helper.service';
import { NgbAlertModule } from '@ng-bootstrap/ng-bootstrap/alert/alert.module';
import { NgbAlertConfig } from '@ng-bootstrap/ng-bootstrap/alert/alert-config';

describe('LoginComponent', () =&gt; {
  let component: LoginComponent;
  let fixture: ComponentFixture&lt;LoginComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [FormsModule, ReactiveFormsModule, RouterTestingModule, NgbAlertModule,],
      declarations: [LoginComponent],
      providers: [LoginService, HelperService, NgbAlertConfig,],
    }).compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  function updateForm(loginFormValue) {
    component.loginForm.controls['email'].setValue(loginFormValue.email);
    component.loginForm.controls['password'].setValue(loginFormValue.password);
  }    

  it('isError should be true when password is wrong', fakeAsync(() =&gt; {
    const loginFormValue = {
      email: 'test@gmail.com',
      password: '123', // give wrong password
    };
    updateForm(loginFormValue);
    fixture.debugElement.query(By.css('.login-submit')).triggerEventHandler('ngSubmit', null);
    tick(); // wait for async operations
    expect(component.isError).toBeTruthy();
  }));

  it('onLogin should be called', fakeAsync(() =&gt; {
    spyOn(component, 'onLogin');
    const loginFormValue = {
      email: 'test@gmail.com',
      password: '123456',
    };
    updateForm(loginFormValue);
    fixture.debugElement.query(By.css('.login-submit')).triggerEventHandler('ngSubmit', null);
    expect(component.onLogin).toHaveBeenCalledWith(loginFormValue);
  }));
});
</code></pre>

<p>Both of my test cases are failing:</p>

<blockquote>
  <ol>
  <li><p>(LoginComponent isError should be true when password is wrong):  Expected undefined to be truthy.</p></li>
  <li><p>(LoginComponent onLogin should be called):  Expected spy onLogin to have been called with [ Object({ email: 'test@gmail.com', password:
  '12345' }) ] but it was never called.</p></li>
  </ol>
</blockquote>

<p>What exactly I am doing wrong here?</p>
",https://stackoverflow.com/questions/47509657/how-to-spy-method-in-angular-cli-jasmine-unit-testing,"['javascript', 'angular', 'unit-testing', 'jasmine', 'angular-cli']",523,FALSE,0,1
React - are propTypes unecessary if also unit testing the component?,"<p>If you are unit testing a React component, using Mocha + Enzyme for example, and the unit tests for this component include testing the props, is it safe to say that defining <code>propTypes</code> for that component is unecessary?</p>
",https://stackoverflow.com/questions/42114625/react-are-proptypes-unecessary-if-also-unit-testing-the-component,['reactjs'],109,TRUE,0,1
How to mock a custom ImageView for activity unit testing,"<p>I have a <code>LoginActivity</code> which loads a <code>SplashFragment</code> in <code>onResume()</code>.  </p>

<p>The layout XML of the splash fragment contains a custom <code>ImageView</code> called <code>RotatingImageView</code> which, as the name suggests, starts rotating a source image as soon as it's attached to the Window.</p>

<p>Now this is causing problems when I try to write a unit test for <code>LoginActivity</code> using <code>ActivityInstrumentationTestCase2&lt;LoginActivity&gt;</code>. I'm trying to run the tests on a real device(unrooted), not an emulator.</p>

<p>The <code>getActivity()</code> call starts the activity but because of the rotating image view (which is an animation btw), the espresso is stuck. I know that espresso doesn't like an animation going on there. I get exceptions that </p>

<blockquote>
  <p>""espresso couldn't launch intent within 45 seconds. Perhaps the main
  thread has not gone idle within a reasonable amount of time? There
  could be an animation or something constantly repainting the screen.
  Or the activity is doing network calls on creation? See the thread dump
  logs. For your reference the last time the event queue was idle before
  your activity launch request was 1487296262885 and now the last time
  the queue went idle was: 1487296262885. If these numbers are the same
  your activity might be hogging the event queue...""</p>
</blockquote>

<p>Now obviously the problem is to somehow stop/mock the animation. </p>

<ol>
<li><p>I have already disabled all animation options from Device -> Settings -> Developer Options but still when activity is launched I see the image spinning so this doesn't help.</p></li>
<li><p>I've also looked into <a href=""https://gist.github.com/xrigau/11284124"" rel=""nofollow noreferrer"">Disable animations for Espresso tests</a> but this hasn't helped me much either. I could have been doing it wrong but anyways, it's not helping.</p></li>
<li><p>Another option is to launch <code>LoginActivity</code> using a special intent which tells the activity that this is launching under test so when you load the fragment it disables the animation. This method works but it's not ideal because it involves adding code in the main class which is purely for testing.</p></li>
</ol>

<p>One other solution could be to mock <code>RotatingImageView</code> and inject it into <code>SplashFragment</code> before it starts loading. I would have mocked out the call to <code>startSpinningAnimation</code> so when it's loaded into the Window it won't start the animation.</p>

<p>My question is: Is it possible? Can I mock and inject this custom <code>imageView</code> into my fragment somehow, before the call to <code>getActivity()</code> is done?</p>
",https://stackoverflow.com/questions/42290280/how-to-mock-a-custom-imageview-for-activity-unit-testing,"['android', 'unit-testing', 'android-animation', 'android-imageview', 'android-espresso']",935,TRUE,0,1
Adobe AIR mobile applications unit testing integration tests test automations,"<p>We are developing mobile games based on Adobe AIR and stage3D technology.
Is there any possibility to do unit tests, integrations tests, UI testing in such applications?
Are there any continues integration tools? Jenkins plugins or anything else?</p>

<p>After some researches we've found several tools for AS3 Unit testing but most of them are supposed to be used with FLEX apps.</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/44483455/adobe-air-mobile-applications-unit-testing-integration-tests-test-automations,"['unit-testing', 'actionscript-3', 'continuous-integration', 'integration-testing', 'stage3d']",60,FALSE,0,1
Unit testing and checking that PDF has been properly generated,"<p>I am trying to easily check that my byte array is a successfully encoded PDF file. When I write all bytes the PDF is successfully created, however I read that a PDF is supposed to start with a particular set of bytes link below:</p>

<p><a href=""https://stackoverflow.com/questions/6186980/determine-if-a-byte-is-a-pdf-file"">Determine if a byte[] is a pdf file</a></p>

<p>Mine however starts like this:</p>

<pre><code>var test = new byte[] { 37, 80, 68, 70, 45, 49, 46, 52, 10, 37... 
</code></pre>

<p>Would a ""SAFE"" unit test check to see if these 10 first elements match? For example create the byte[] iterate through the first 10 elements and make sure that they follow the sequence of test. </p>
",https://stackoverflow.com/questions/44852866/unit-testing-and-checking-that-pdf-has-been-properly-generated,"['c#', 'unit-testing']",721,FALSE,0,0
Enable unit testing of a method my making it protected,"<p>Let me explain the problem scenario. My task is to modify the complicated function testFunc() which looks like below.</p>

<pre><code>public String testFunc() {
    String a = func1();
    String b = func2(a);
    String c = func3(b);
    return c;
} 
private String func1(){
    return ""hello"";
}
private String func2(String p1){
    return ""a"" + p1;
}
private String func3(String p1){
    return ""b"" + p1;
}
</code></pre>

<p>I modify the testFunc method and include my logic. But being a good developer, I wish to write untit tests for the extra logic i have written. 
But i do not have time nor the patience to test the entire method. I wish to test only the logic i have added.</p>

<pre><code> public String testFunc() {
     String a = func1();
     String b = func2(a);
     String c = func3(b);
     String d = func4(c)
     return d;
 }
 protected final String func4(String p1) {
     return ""1"" + p1;
 }
</code></pre>

<p>Does it make sense for me to make the method func4 as protected final so that I can unit test the logic thoroughly. Or is it bad coding practise?</p>
",https://stackoverflow.com/questions/45030845/enable-unit-testing-of-a-method-my-making-it-protected,"['java', 'styles', 'tdd']",175,TRUE,0,4
tSqlt - Unit Testing Procedures which output XML using Schema Collections,"<p>We are currently developing SQL stored procedures for an integration project which requires XML payloads, which we have implemented using Schema Collections to ensure strict adherence to the defined schema.</p>

<p>We want to write unit tests for these stored procedures but given the output is XML, I am not sure how ( or if ) I can do this with the assert stored procedures in tsqlt (without having to convert everything into a table / table variable.)</p>

<p>Can someone please point me in the right direction - whether it can/can't be done, and if its not possible, how should I approach trying to create a new asset stored procedure for XML payloads ?</p>

<p>Or would we save a lot of time / heartache by simply converting the expected and actual results from XML into tables in each test ? </p>

<p>Thanks</p>
",https://stackoverflow.com/questions/45084240/tsqlt-unit-testing-procedures-which-output-xml-using-schema-collections,"['sql', 'sql-server', 'unit-testing', 'tsqlt']",567,TRUE,0,1
When unit testing a directive how to pass its controller,"<p>I am new to AngularJS and its unit test. Currently I am trying to test a directive with its controller in the template file:</p>

<p>It's template:</p>

<pre><code>&lt;div ng-controller = ""SomeController"" &gt;
&lt;select ng-model=""data.selectedOption"" 
        ng-options=""data.code for data in data.availableOptions track by data.code""&gt;
&lt;/select&gt;
&lt;/div&gt;
</code></pre>

<p>It's js file:</p>

<pre><code>angular.module('application.directives')
  .directive('selector', function () {
    return {
      restrict: 'E',
      templateUrl: 'templates.html'
     };
  });
</code></pre>

<p>Now I have a unit test like: </p>

<pre><code>describe('selector', function () {
  beforeEach(module('application.directives','application.templates'));

  it('render the correct number of items', inject(function ($rootScope, $compile) {
    var element = $compile('&lt;selector&gt;&lt;/selector&gt;')($rootScope);
    $rootScope.$digest();
    //I'd like to register the selector's controller here.
  }));
});
</code></pre>

<p>In the test code, what would be the best way to register the controller? Do I need to create a mock one?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/42790254/when-unit-testing-a-directive-how-to-pass-its-controller,"['angularjs', 'unit-testing', 'angularjs-directive', 'controller']",20,TRUE,0,1
Need suggestion for unit testing in Vapor using Swift 3.0,"<p><strong>Do we have any unit testing frameworks in Vapor?</strong></p>

<p>I am looking dependencies/framework which will help to do the Unit testing some of my web services and methods in easyway. </p>

<p>I've tried following solutions.</p>

<ul>
<li><a href=""http://seatoncode.com/unit-testing-vapor/"" rel=""nofollow noreferrer"">http://seatoncode.com/unit-testing-vapor/</a></li>
<li><a href=""https://medium.com/@tullio.sebastiani/unit-testing-vapor-toolbox-v-1-0-1-projects-c59a056c3b9b#.qf0kl1pfo"" rel=""nofollow noreferrer"">https://medium.com/@tullio.sebastiani/unit-testing-vapor-toolbox-v-1-0-1-projects-c59a056c3b9b#.qf0kl1pfo</a></li>
</ul>
",https://stackoverflow.com/questions/42265022/need-suggestion-for-unit-testing-in-vapor-using-swift-3-0,"['unit-testing', 'swift3', 'vapor']",520,TRUE,0,1
Karma unit testing showing broken UI overlaid in Angular 4.1.3,"<p>I'm pretty new to Angular and have been building a fun app on the side to get some practice in. </p>

<p>At the moment I'm trying to integrate proper unit-testing and am running into what appears to be some weirdness. </p>

<p>I've build this app using angular-cli and modified the generated unit tests to start fleshing out better code coverage for testing. </p>

<p>However, when running <code>ng test</code> the chrome browser then displays some html elements from my apps ui overlaid on top of the karma report. 
<a href=""https://i.stack.imgur.com/VJb59.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/VJb59.png"" alt=""enter image description here""></a></p>

<p>I have a strong feeling this is likely due to me doing something wrong. My google-fu has been less than helpful in this situation. Is karma supposed to try to render the UI at all?</p>

<p>I reduced the testing to purely just a test against my main app.component and even then part of the ui tries to render. In the following code if I remove the reference to PlayerService then UI elements no longer render overlaid on top of the Karma output but of course then the tests fail.</p>

<p><strong>app.component.spec.ts</strong></p>

<pre><code>import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';

import { AppComponent } from './app.component';
import { NavigationComponent } from './navigation/navigation.component';
import { PlayerService } from './players/shared/player.service';

describe('AppComponent', () =&gt; {
  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent,
        NavigationComponent
      ],
      providers: [ PlayerService ]
    }).compileComponents();
  }));

  it('should create the app', async(() =&gt; {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));
});
</code></pre>

<p><a href=""https://i.stack.imgur.com/yJzdI.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/yJzdI.png"" alt=""enter image description here""></a></p>

<p>This seems strange to me. </p>

<p>Full source code can be found here:</p>

<p><a href=""https://github.com/joshuahysong/TICompanion/tree/20170606_tests"" rel=""nofollow noreferrer"">https://github.com/joshuahysong/TICompanion/tree/20170606_tests</a></p>

<p>Any suggestions?</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/44412711/karma-unit-testing-showing-broken-ui-overlaid-in-angular-4-1-3,"['angular', 'unit-testing', 'typescript', 'karma-jasmine']",2161,TRUE,0,2
How to validate mock response in karma jasmine unit testing,"<p>I need to validate the response after success and error states of a service. My service as belows.</p>

<pre><code>   vm.onSupportFileDeleted = function (file) {
        DocumentService.deleteDocument(file.fileId).then(function () {
            var index = vm.supportingDocuments.indexOf(file);
            vm.supportingDocuments.splice(index, 1);
            vm.dzRemoveFile(file);
            setSupportFileStatusA11yAlert('Document removed');
            //advanced-options-link
            angular.element('#advanced-options-link').trigger('focus');
        }, function (msg) {
            $log.error('Document not deleted - ' + JSON.stringify(msg));
            showSupportingDocumentError('Unable to delete file');
            setSupportFileStatusA11yAlert('Unable to remove document');
        });

    };
</code></pre>

<p>I need to validate index, supportingDocuments variables.
I have created a mock as below.</p>

<pre><code>            DocumentServiceMock = jasmine.createSpyObj('DocumentService', [
            'deleteDocument'
        ]);
</code></pre>

<p>How can i do this?</p>
",https://stackoverflow.com/questions/45452513/how-to-validate-mock-response-in-karma-jasmine-unit-testing,"['angularjs', 'karma-jasmine']",744,FALSE,0,1
Angular 2 - unit testing - &quot;No provider for Token translations&quot; error,"<p>I have an Angular 2 application and i'm using karma and jasmin for unit testing.
I get the following error when i'm running the tests:
""Error: No provider for Token translations!""</p>

<p>this is the component constructor(it's the app component):</p>

<pre><code>constructor(private _ccmApiService: CcmApiService,
          private _usersService: UsersService,
          private _foldersService: FoldersService,
          private _hubService: HubService,
          private _router: Router,
          private _navigationService: NavigationService,
          private _translate: TranslateService,
          private _busyLoaderService: BusyLoaderService,
          private _infoModal: InfoModal) {
</code></pre>

<p>}</p>

<p>it doesn't need to be provided with any service or module similar to what is in the error.</p>

<p>Any ideas?</p>

<p>Thanks :) </p>
",https://stackoverflow.com/questions/47513893/angular-2-unit-testing-no-provider-for-token-translations-error,"['angular', 'unit-testing', 'karma-jasmine']",863,TRUE,0,1
React Unit Testing: TypeError: Cannot read property &#39;test&#39; of undefined,"<p>I am unit-testing a React App using karma-jasmine. However, there is recurrent error as follows</p>

<blockquote>
  <p><strong>TypeError: Cannot read property 'test' of undefined</strong></p>
</blockquote>

<pre><code>  at ValidatedInput.validateInput (src/components/ValidatedInput.js:47:42)
  at ValidatedInput.isValid (src/components/ValidatedInput.js:33:27)
  at Object.&lt;anonymous&gt; (src/__tests__/validated_input-test.js:64:24)
  at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)
  at process._tickCallback (internal/process/next_tick.js:109:7)
</code></pre>

<p>Following is my test file</p>

<blockquote>
  <p>validated_input-test.js</p>
</blockquote>

<pre><code>    describe('functions', () =&gt; {
        const componentToCheckFunctions = TestUtils.renderIntoDocument(
            &lt;ValidatedInput
                type={'password'}
                name={'password'}
                title={'Password'}
                value={'Sample123Test'}
                placeholder={'Sample Placeholder'}
                onChange={() =&gt; {}}
                onComponentMounted={() =&gt; {}}
                validaions={/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,16}$/}
                validationError={'Invalid Password Format'}
        /&gt;);

        const renderedDOMNode = TestUtils.findRenderedDOMComponentWithClass(
            componentToCheckFunctions, 'form-input'
        );

        it('should check validate password', () =&gt; {
            expect(shallow(&lt;ValidatedInput /&gt;
            ).instance().isValid(renderedDOMNode)).equals(true);
        });

    });
</code></pre>

<p>and the file for testing </p>

<blockquote>
  <p>ValidatedInput.js</p>
</blockquote>

<pre><code>import React, { Component } from 'react';

class ValidatedInput extends Component {
    constructor(props) {
        super(props);

        this.state ={
            validations: this.props.validations,
            validationError: this.props.validationError
        };

        this.handleChangeValue = this.handleChangeValue.bind(this);
        this.isValid = this.isValid.bind(this);
        this.validateInput = this.validateInput.bind(this);
    }

    handleChangeValue(e) {
        this.props.onChange(e.target.value);
        var isValidField = this.isValid(e.target);
    }

    isValid(inputElement) {
        if (inputElement.getAttribute('required') !== null &amp;&amp; inputElement.value === """") {
            inputElement.classList.add('Error');
            inputElement.nextSibling.textContent = this.props.validationError;
            return false;
        } else {
            inputElement.classList.remove('Error');
            inputElement.nextSibling.textContent =  '';
        }

        if(inputElement.value !== """") {
            if(!this.validateInput(inputElement.value)) {
                inputElement.classList.add('Error');
                inputElement.nextSibling.textContent = this.props.validationError;
                return false;
            } else {
                inputElement.classList.remove('Error');
                inputElement.nextSibling.textContent =  '';
            }
        }
            return true;
    }

    validateInput(value) {
        var regularExpressionToBeMatched = this.props.validations;
        return this.state.validations.test(value);
    }

    componentDidMount() {
        if (this.props.onComponentMounted) {
            this.props.onComponentMounted(this);
        }
    }

    render () {
        return (
            &lt;div className=""form-group""&gt;
                &lt;div className=""col-5 text-center""&gt;
                    &lt;label htmlFor={this.props.name}&gt;{this.props.title}&lt;/label&gt;
                &lt;/div&gt;
                &lt;div className=""col-5 text-center""&gt;
                    &lt;input
                        className=""form-input text-center""
                        type={this.props.type}
                        ref={this.props.name}
                        name={this.props.name}
                        value={this.props.value}
                        required={this.props.isRequired}
                        placeholder={this.props.placeholder}
                        onChange={this.handleChangeValue}
                    /&gt;
                    &lt;span className='Error'&gt;&lt;/span&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        );
    }
}

export default ValidatedInput;
</code></pre>

<p>Logging <code>this.props.validations</code> produces <code>undefined</code>. I tried passing props in <code>shallow&lt;ValidatedInput /&gt;</code> but the error still persists. Any suggestions on how to deal with error or structure of code?
Thanks.</p>
",https://stackoverflow.com/questions/45927502/react-unit-testing-typeerror-cannot-read-property-test-of-undefined,"['javascript', 'reactjs', 'unit-testing']",5013,TRUE,0,1
javascript unit testing with jest: how to mock async call,"<p>I am new to TypeScript,  earlier worked on Java. I am looking for java junit(Mockito) equivalent to TypeScript.
In junit in each test we can define the dependency behavior and return the response as per the test case demand. 
is there similar way available in jest also ?
in which i can simply define.
    when(dependencyFunction()).then(mockResponse1);</p>

<p>and in different test 
    when(dependencyFunction()).then(mockResponse2);</p>

<p>Here is how my typescript class look like:</p>

<pre><code>class ABC {
   static fun1(){
       const xyz = await dependency();
       return xyz === 'DONE';
   }
}
</code></pre>

<p>Here i want to write test cases in which i can define the mocked response in each test cases.</p>
",https://stackoverflow.com/questions/47975849/javascript-unit-testing-with-jest-how-to-mock-async-call,"['javascript', 'unit-testing', 'typescript', 'jestjs']",360,TRUE,0,1
Unit Testing Rest API | Need to Disable Authorization| Spring Boot,"<p>I have developed a REST API using Spring Boot.I need to unit test POST method of REST API developed. Since i have used </p>

<blockquote>
  <p>@EnableSecurity in Application.class
  @@Authorization(authorizedGroups = {""CN=APP-XYG-Group""} in Controller</p>
</blockquote>

<p>I am not able to test using Junit, since i have Enabled Security and i get 403 error , when actually i would like to test for 200 OK http status code.</p>

<p>I would like to disable the security checking while doing testing, Is it possible. Please find the code snippet below:</p>

<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ParseInput {

    @Autowired
    TestRestTemplate restTemplate;

    @Test
    public void testRate() throws Exception {

        //setting up input for test case
        QReq qReq= new QReq();
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            qReq = objectMapper.readValue(new File(""src/main/resources/input.json""), QReq.class);
        }catch (Exception e){
            System.out.println(""Error message here is "" + e.getMessage());
        }

        //Executing the test case

        ResponseEntity&lt;QResp&gt; subject = restTemplate.postForEntity(""/tax_rates/v1/quotations"", qReq, QResp.class);
        Assert.assertEquals(HttpStatus.OK, subject.getStatusCode());
    }

}
</code></pre>

<p>Any help appreciated</p>
",https://stackoverflow.com/questions/46374089/unit-testing-rest-api-need-to-disable-authorization-spring-boot,"['spring-mvc', 'spring-boot', 'junit', 'mockito']",1851,TRUE,0,1
"Unit Testing(Mocking) Databases, How To Verify Database Methods With Mocking?","<p>As a person has no experience before in unit testing and mocking, I followed beginner tutorials about JUnit with Mockito and I do some practice.</p>

<p>Now, I need to unit test some class methods which do basic database operations on a MySQL database. I don't want to make real changes on the database.</p>

<p>In my code:</p>

<pre><code>@InjectMocks private DBConnection dbConnection;
@Mock private DBConnection mockDBConnection;

@Test
public void testDropTable() {

    Mockito.when(mockDBConnection.dropTable()).thenReturn(0);

    // dropTable() returns 0 if table dropped
    int result = dbConnection.dropTable();
    Assert.assertEquals(result, 0);
}
</code></pre>

<p>To verify(with assertEquals() ) result of the test, I am calling real dropTable() method, and it really drops table( Actually it is obvious, because I'm calling on real DBConnection instance)</p>

<p>Is there anyway to verify the methods like that, without accessing the real database? Or did I misunderstand the concept of Unit Testing and Mocking?</p>
",https://stackoverflow.com/questions/47547255/unit-testingmocking-databases-how-to-verify-database-methods-with-mocking,"['unit-testing', 'junit', 'mocking', 'mockito', 'tdd']",18906,TRUE,6,3
Error when unit testing a VS project that uses winsqlite3,"<p>I have a project in Visual Studio 2017 that runs some code that uses winsqlite3. The project executes fine, I have winsqlite3 as an additional linker dependency. I added a test project to write unit tests for this code. When I add winsqlite3.lib as an additional linker dependency in my unit test project, I get the error message
<code>Unable to start program 'C:\my\path\project.dll'. C:\my\path\project.dll is not a valid Win32 application.</code></p>

<p>But without this dependency I get linker errors. How do I resolve this?</p>

<p>I am building for x64, as a console application.</p>
",https://stackoverflow.com/questions/43598317/error-when-unit-testing-a-vs-project-that-uses-winsqlite3,"['c++', 'visual-studio', 'unit-testing', 'sqlite']",161,FALSE,0,0
Unit testing using Moq and setting up GetAll with include,"<p>I have this strange problem with MOQ and I cant use the GetAll('include') method to test my controller.</p>

<p>My Tests initialization</p>

<pre><code>// GetAll
menusDb.Setup(m =&gt; m.GetAll()).Returns(menus.AsQueryable());
menusDb.Setup(m =&gt; m.GetAll(It.IsAny&lt;Expression&lt;Func&lt;Menu, object&gt;&gt;&gt;()))
       .Returns((Expression&lt;Func&lt;Menu,object&gt;&gt; pred) =&gt; { 
           return menus.AsQueryable();
       });
// FindByIdAsync
menusDb.Setup(m =&gt; m.FindByByIdAsync(It.IsAny&lt;int&gt;()))
       .Returns((int x) =&gt; Task.FromResult(menus.Find(m =&gt; m.ID == x)));
menusDb.Setup(m =&gt; m.FindByByIdAsync(It.IsAny&lt;int&gt;(), It.IsAny&lt;Expression&lt;Func&lt;Menu, object&gt;&gt;[]&gt;()))
       .Returns((int x, Expression&lt;Func&lt;Menu,
           object&gt;&gt;[] includeProperties) =&gt; Task.FromResult(menus.Find(m =&gt; m.ID == x)));
</code></pre>

<p>Now whenever I am trying to test </p>

<pre><code>_menusDB.GetAll(s=&gt;s.Sections)
</code></pre>

<p>The moq version of menusdb.getAll() method is not fired at all</p>

<p>All other Moq methods are triggered correctly...
examples </p>

<pre><code>_menusDB.GetAll();
_menusDB.FindByByIdAsync(id,
                m =&gt; m.Sections.Select(s =&gt; s.Image),
                m =&gt; m.Sections.Select(s =&gt; s.MenuItems.Select(mi =&gt; mi.Image)));
</code></pre>

<p>And these are the Getall and find functions with includes in my generic repository.</p>

<pre><code>public IQueryable&lt;TEntity&gt; GetAll&lt;TProperty&gt;(Expression&lt;Func&lt;TEntity, TProperty&gt;&gt; propertyToInclude) {            
    return ObjectSet.Include(propertyToInclude);
}

public async Task&lt;TEntity&gt; FindByByIdAsync(int id, params Expression&lt;Func&lt;TEntity, object&gt;&gt;[] propertiesToInclude) {            
    var query = propertiesToInclude.Aggregate(ObjectSet as IQueryable&lt;TEntity&gt;, (current, property) =&gt; current.Include(property));
    return await query.SingleOrDefaultAsync(entity =&gt; entity.ID == id).ConfigureAwait(false);
}
</code></pre>
",https://stackoverflow.com/questions/42697452/unit-testing-using-moq-and-setting-up-getall-with-include,"['c#', 'nunit', 'moq', 'vs-unit-testing-framework']",1712,TRUE,0,1
How to write Unit testing for email and password validation?,"<p>I do have the following small function for http POST request where I check the email and password regarding validation...</p>

<p>What would be the best approach to implement a unit testing for it?</p>

<pre><code>MAIL_RegExp = /^\w+([d\\+1\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/i;
Pass_RegExp = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$@!%&amp;*?])[A-Za-z\d#$@!%&amp;*?]{8,30}$/i;
storeUser(uemail:string, upass:string) {
    if (!this.MAIL_RegExp.test(uemail)) {
        return false;
    } else if (!this.Pass_RegExp.test(upass)) {
        return false;
    } else {
        this.uService.regUser(uemail, upass)
        .subscribe(
            (res) =&gt; {this.openDialog(uemail);},
            (err) =&gt; {this.errMsg = err;}
        );
    }
}
</code></pre>
",https://stackoverflow.com/questions/47395593/how-to-write-unit-testing-for-email-and-password-validation,"['angular', 'unit-testing', 'jasmine']",1037,TRUE,0,1
Unit-Testing for synchronize method in java using Test-NG,"<p>How can I start writing test case for below synchronize java method. Thanks.</p>

<pre class=""lang-java prettyprint-override""><code>public synchronized boolean isUser(String username) {
   if (rememberMeMap.containsKey(username)) {
       long timestamp = rememberMeMap.get(username);
       long curtime = Calendar.getInstance().getTimeInMillis();
       if (curtime - timestamp &gt; 1200000) { 
           log.warn(""RememberMe"");
            return false;
       }
       return true;
    }
    return false;
}
</code></pre>
",https://stackoverflow.com/questions/46753172/unit-testing-for-synchronize-method-in-java-using-test-ng,"['java', 'unit-testing']",27,FALSE,0,0
Java Unit Testing method that uses new Date() for current date,"<p>So I have a class that has a method ""getDaysUntil(Date date)"" which returns the number of days until the date given as parameter. I mention that I cannot change the class below:</p>

<pre><code>public class A {

public int getDaysUntil(Date givenDate) {

    ... // code

    Date currentDate = new Date() //it creates a date object holding the current day

    ...// code that calculates the nr of days between currentDate and givenDate.

}
</code></pre>

<p>I have to do some unit testing and you might see the problem, it creates currentDate inside the method and the returned value will be different from day to day. I have tried to mock a Date object or ""override"" System.currentTimeMillis() with PowerMock but to no avail.</p>

<p>Is there any way to properly test these kind of methods?</p>
",https://stackoverflow.com/questions/42573000/java-unit-testing-method-that-uses-new-date-for-current-date,"['java', 'unit-testing', 'date', 'mocking']",24632,TRUE,5,3
Angular 2 Unit Testing prepare mocking to share in components,"

<p>I'm doing unit test in my Angular2 application and very new to angular2 test framework.</p>

<p>I have 2 components and calling same method from a service.</p>

<p>Firstly, I need to import the service and model to create the mock</p>

<pre class=""lang-ts prettyprint-override""><code>import { MyService } from '../../shared/my.service';
import { MyModel } from '../../shared/my.model';
</code></pre>

<p>Secondly, arrange the model and service to mock</p>

<pre class=""lang-ts prettyprint-override""><code>describe('MyComponent', () =&gt; {
  let component: MyComponent;
  let fixture: ComponentFixture&lt;MyComponent&gt;;
  const mockMyModel: MyModel[] = [];
  const mockMyService = {
    sameMethod: () =&gt; Observable.of(mockMyModel),
  };
</code></pre>

<p>Finally, mock the service</p>

<pre class=""lang-ts prettyprint-override""><code>beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ MyComponent],
    })
    .overrideComponent(MyComponent, {
      set: {
        providers: [
          { provide: MyService , useValue: mockMyService },
        ],
      },
    })
    .compileComponents();
  }));
</code></pre>

<p>I need to do the same thing again for my another component.</p>

<ul>
<li><p>Option 1: is there any way to globally share the preparation for mock
e.g. <code>{ provide: MyService , useValue: global.mockMyService }</code></p></li>
<li><p>Option 2: is it possible to have 'ServiceTestingModule' such as 'RouterTestingModule' just to mock a service.</p></li>
</ul>

<p>Thanks!</p>
",https://stackoverflow.com/questions/41501914/angular-2-unit-testing-prepare-mocking-to-share-in-components,"['unit-testing', 'angular', 'mocking']",357,FALSE,0,1
Visual Studio 2017 Live Unit Testing Fails To Build Upon Start,"<p>This is my first attempt at using the new <em>Live Unit Testing</em> feature in VS 2017.</p>

<p>When I click on <code>Test | Live Unit Testing | Start</code>, I see the following in the output window:</p>

<pre><code>[13:55:37.376 Verbose] - Orchestrator - Request to start Live Unit Testing. (Source = MenuItem)
[13:55:37.376 Verbose] - Orchestrator - Handling request to start LiveUnitTesting.
[13:55:37.633 Verbose] - Orchestrator - Connected to LiveUnitTesting process
[13:55:37.653 Verbose] - BuildManager - Allow to send a single build event.
[13:55:37.653 Info] - Orchestrator - Live Unit Testing started.
[13:55:37.653 Verbose] - TestExplorerServiceClient - Updating client state from Disabled to Enabled
[13:55:37.653 Verbose] - StatusMargin - Received a SystemStatusChangedEvent: Started
[13:55:37.663 Verbose] - BuildManager - Building solution.
[13:55:37.664 Verbose] - BuildManager - Building project ExcelLibrary.Tests.
[13:55:37.666 Verbose] - RemoteOrchestrator - Received SubscriptionEvent for 'C:\VS\ExcelLibrary\ExcelLibrary.Tests\ConMetPartNumberUtilsTests.cs - C:\VS\ExcelLibrary\ExcelLibrary.Tests\ExcelLibrary.Tests.csproj' (Subscribe)
[13:55:37.669 Verbose] - Aggregator - Received subscription request for 'C:\VS\ExcelLibrary\ExcelLibrary.Tests\ConMetPartNumberUtilsTests.cs - C:\VS\ExcelLibrary\ExcelLibrary.Tests\ExcelLibrary.Tests.csproj'
[13:55:37.680 Verbose] - Aggregator - Adding 0 methods from 'C:\VS\ExcelLibrary\ExcelLibrary.Tests\ConMetPartNumberUtilsTests.cs - C:\VS\ExcelLibrary\ExcelLibrary.Tests\ExcelLibrary.Tests.csproj' to the coverage aggregation work list
[13:55:37.685 Verbose] - Aggregator - Starting coverage aggregation cycle - work list has 0 methods
[13:55:37.687 Verbose] - Aggregator - Finished coverage aggregation cycle - work list had 0 methods of which 0 methods were defined in 1 open files
[13:55:38.106 Verbose] - BuildManager - C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\VisualStudio\v15.0\OfficeTools\Microsoft.VisualStudio.Tools.Office.targets(176,9): error MSB4008: A conflicting assembly for the task assembly ""C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\VisualStudio\v15.0\OfficeTools\Microsoft.VisualStudio.Tools.Office.BuildTasks.dll"" has been found at ""C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\VisualStudio\v15.0\OfficeTools\Microsoft.VisualStudio.Tools.Office.BuildTasks.dll"".
[13:55:38.118 Verbose] - BuildManager - C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\VisualStudio\v15.0\OfficeTools\Microsoft.VisualStudio.Tools.Office.targets(176,9): error MSB4061: The ""FindRibbons"" task could not be instantiated from ""C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\VisualStudio\v15.0\OfficeTools\Microsoft.VisualStudio.Tools.Office.BuildTasks.dll"". Value cannot be null.
Parameter name: key
[13:55:38.118 Verbose] - BuildManager - C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\VisualStudio\v15.0\OfficeTools\Microsoft.VisualStudio.Tools.Office.targets(176,9): error MSB4060: The ""FindRibbons"" task has been declared or used incorrectly, or failed during construction. Check the spelling of the task name and the assembly name.
[13:55:38.136 Info] - BuildManager - Build completed (failed).
[13:55:38.136 Verbose] - BuildManager - Interrupting build queue -&gt; no new assemblies.
[13:55:38.136 Verbose] - BuildManager - Interrupting build queue -&gt; no new assemblies.
</code></pre>

<p>Thus it seems the culprit is a conflicting assembly for <code>Microsoft.VisualStudio.Tools.Office.BuildTasks.dll</code>. However it's not clear why VS is reporting this error since there is only one such file in the indicated folder (no <em>BuildTasks.dll.bak</em> or similar) and no other instances of <code>devenv.exe</code> are running, and all add-ins are disabled. And I've tried killing all but essential processes and rebooting, etc.</p>

<p>Interestingly in Visual Studio 2017 Installer dialog, the installed enterprise SKU is labelled as <code>Visual Studio Enterprise 2017 (2)</code>. Perhaps this issue is correlated with the <code>(2)</code> suffice. Originally I installed the Professional, later installed the Enterprise, and finally uninstalled Professional.</p>

<p>Any ideas?</p>
",https://stackoverflow.com/questions/42820786/visual-studio-2017-live-unit-testing-fails-to-build-upon-start,['visual-studio-2017'],1032,TRUE,4,1
Unit Testing Tag Helper in ASP.NET Core - Populating Tag Public Properties,"<p>Trying to implement best practices on a new project, I figured I'd see how far I can extend unit testing to the MVC Tag Helpers. In this instance, I have a very simple helper taken from the Tag Helper section of the <a href=""https://learn.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/authoring"" rel=""nofollow noreferrer"">MVC documentation</a>, so now I have <code>&lt;email mail-to=""Support""&gt;&lt;/email&gt;</code>.</p>

<p>The actual code for this is below.</p>

<pre><code>public class EmailTagHelper : TagHelper
{
    private const string EmailDomain = ""contoso.com"";

    public string MailTo { get; set; }

    public override void Process(TagHelperContext ctx, TagHelperOutput output)
    {
        output.TagName = ""a"";
        var addr = $""{MailTo}@{EmailDomain}"";
        output.Attributes.SetAttribute(""href"", $""mailto:{addr}"");
        output.Content.SetContent(addr);
    }
}
</code></pre>

<p>The resulting HTML is as expected and if I set a breakpoint when running the code I can see that the pascal-case <code>mail-to</code> is correctly populating the camel-case <code>MailTo</code> inside the C# class.</p>

<p>Now I have the following unit test:</p>

<pre><code>[TestMethod]        
public void EmailTagHelper_GeneratesExpectedHtml()
{
    var emailHelper = new EmailTagHelper();

    var ctx = new TagHelperContext(new TagHelperAttributeList
    {
        {""mail-to"", ""Support""}
    }, new Dictionary&lt;object, object&gt;(), Guid.NewGuid().ToString(""N""));

    var output = new TagHelperOutput(""email"",
        new TagHelperAttributeList(), (useCachedResult, htmlEncoder) =&gt;
        {
            var tagHelperContent = new DefaultTagHelperContent();
            tagHelperContent.SetContent(string.Empty);
            return Task.FromResult&lt;TagHelperContent&gt;(tagHelperContent);
        });

    emailHelper.Process(ctx, output);
    Assert.AreEqual(""a"", output.TagName);
    Assert.AreEqual(""mailto:Support@contoso.com"", output.Attributes[""href""].Value);
}
</code></pre>

<p>The first assert is passing and if I breakpoint inside the tag helper class I can see that the attributes are matching those that are passed when running the application normally, but for some reason the mapping of pascal to camel case <code>MailTo</code> is not occurring during testing.</p>

<p>I am basing my work on the source code of the <a href=""https://github.com/aspnet/Mvc/tree/master/test/Microsoft.AspNetCore.Mvc.TagHelpers.Test"" rel=""nofollow noreferrer"">MVC Tag Helper Unit Tests</a> as found on Github but I think I am missing something.</p>

<p>Any advice or am I going to have to set <code>emailHelper.MailTo</code> in my test, which in all honesty seems like a bit of a cop out answer if so :( Hoping it's just a nuance I am overlooking! </p>
",https://stackoverflow.com/questions/43324796/unit-testing-tag-helper-in-asp-net-core-populating-tag-public-properties,"['c#', 'unit-testing', 'asp.net-core-mvc', 'tag-helpers']",1432,TRUE,4,1
Unit Testing / Test if a function is present within a file,"<p>I would like to know if there is a way using mocha and chai to test the code for the existence of a whole piece of code, like for instance a function like this.</p>

<pre><code>myfunction(arg1) {
    ......
}
</code></pre>

<p>If the code is present, then the test should return true.</p>

<p>PD: I know that testing for an entire piece of code may look like a nasty thing, but sometimes when conducting a training the students code a lot, and if something is not working we should review the entire set of steps they've done, to avoid that I want to write a test to look for certain pieces of code. I already wrote other tests to check for the existence of arguments, array element length, etc.</p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/42682931/unit-testing-test-if-a-function-is-present-within-a-file,"['javascript', 'node.js', 'unit-testing', 'mocha.js', 'chai']",1656,TRUE,4,1
How to Mock a service inside Controller Advice for Unit Testing,"<p>The problem is I cannot unit test/mock this because the <strong>messageByLocaleService</strong> is null in the <strong>Controller Advice</strong>. Please suggest any way to inject the mock of messageByLocaleSerI have a set up like this:</p>

<p><strong>ExceptionControllerAdvice class:</strong></p>

<pre><code>@Autowired
private MessageByLocaleService messageByLocaleService; //CANNOT MOCK THIS

@ControllerAdvice
public class ExceptionControllerAdvice {

    @ExceptionHandler(UserNotFoundException.class)
    public ResponseEntity&lt;String&gt; handleUnexpectedException(HttpServletRequest request, Exception e) {

        //build response as below
        String s = messageByLocaleService.buildMessage(HttpStatus.ERROR,""User Not Valid""); // GETTING NULL HERE
        //and send the response back to the client here
    }
}
</code></pre>

<p><strong>Controller method:</strong></p>

<pre><code>@RequestMapping(value = ""${foo.controller.requestMappingUrl.login}"",
                                 method = RequestMethod.POST)
public ResponseMessage&lt;String&gt; loginUser(
            @RequestParam(""username"") String username,
               HttpServletRequest httpServletRequest,
               HttpServletResponse httpServletResponse) throws Exception {

       return fooService.login(username);
}
</code></pre>

<p><strong>JUnit setup &amp; test methods:</strong></p>

<pre><code>@InjectMocks
private ProjectController projectController;

@Mock
private FooService fooService;


@Mock
private MessageByLocaleService messageByLocaleService;

@Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    mockMvc = MockMvcBuilders.standaloneSetup(projectController)
                .setMessageConverters(new MappingJackson2HttpMessageConverter())
                .setControllerAdvice(new ExceptionControllerAdvice()).build();
}


@SuppressWarnings(""unchecked"")
@Test
    public void testControllerUserNotFoundException() throws Exception {
        Response resp = new Response();
        resp.setStatusCode(StatusCode.UserNotFoundErrorCode);
        when(fooService.login(any(String.class)).
        thenThrow(UserNotFoundException.class);

        mockMvc.perform(post(""/service-user/1.0/auth/login?&amp;username=test"")
                        .contentType(contentType)).
     andExpect(status().isNotAcceptable())
                .andExpect(jsonPath(""$.statusCode"", is(""ERRORCODE144"")));
}
</code></pre>
",https://stackoverflow.com/questions/43086728/how-to-mock-a-service-inside-controller-advice-for-unit-testing,"['java', 'spring', 'spring-mvc', 'mockito', 'spring-test']",5652,TRUE,4,1
ReferenceError: ga is not defined [Ionic 2.2 Unit Testing With Karma],"<p>I'm adding unit tests to an Ionic 2.2.0 app I manage, but my Components crash at test-time when they encounter Google Analytics code.  I'm using <a href=""https://github.com/driftyco/ionic-unit-testing-example"" rel=""nofollow noreferrer"">Ionic's official unit testing example</a> as a basis, and <a href=""https://github.com/umts/pvta-multiplatform/tree/ionic2/test4"" rel=""nofollow noreferrer"">my current progress can be seen on our public repo</a>.</p>

<p>My project uses Google Analytics, which is added to the HTML and downloaded at runtime (because we have different keys for development vs production).</p>

<p>The code that initializes Analytics is in my <code>main.ts</code>, and it sets a global variable <code>ga</code>, which is subsequently available throughout the application.</p>

<p>I'm beginning the tests for the app's first page, which uses Analytics.  When I run the tests, I'm met with the following error</p>

<blockquote>
  <p>Component should be created FAILED</p>
  
  <p>ReferenceError: ga is not defined</p>
  
  <p>at new <code>MyBusesComponent</code> (webpack:///src/pages/my-buses/my-buses.component.ts:33:6 &lt;- karma-test-shim.js:138419:9)</p>
  
  <p>at new Wrapper_MyBusesComponent (/DynamicTestModule/MyBusesComponent/wrapper.ngfactory.js:7:18)</p>
  
  <p>at CompiledTemplate.proxyViewClass.View_MyBusesComponent_Host0.createInternal (/DynamicTestModule/MyBusesComponent/host.ngfactory.js:15:32)</p>
  
  <p>........</p>
</blockquote>

<p>This is because <code>main.ts</code> doesn't seem to be loaded or executed, and I assume TestBed is doing that purposefully. It's certainly better that I <em>don't</em> have the actual Google Analytics object, but the Component <em>does</em> need a function called <code>ga</code>.</p>

<p>My question, therefore, is as follows: how can I create Google Analytics' <code>ga</code> variable in my test configuration such that it's passed through to my components at test-time?  </p>

<p>I've tried exporting a function from my <code>mocks</code> file and adding it to either the <code>imports</code> or <code>providers</code> arrays in my spec file, but to no avail.</p>

<p>I appreciate any advice!  Feel free to check my code at our repo I linked to above and ask any followups you need.  Thanks!</p>
",https://stackoverflow.com/questions/43788013/referenceerror-ga-is-not-defined-ionic-2-2-unit-testing-with-karma,"['unit-testing', 'ionic-framework', 'google-analytics', 'ionic2', 'karma-jasmine']",1579,TRUE,3,1
"Unit Testing How can I mock `DbContext.Database.SqlQuery&lt;TElement&gt;(sql, params);` call?","<p>How can I mock <code>DbContext.Database.SqlQuery&lt;TElement&gt;(sql, params);</code> call where it returns an instance of <code>DbRawSqlQuery&lt;TElement&gt;</code>?</p>

<p>I have gone through the following article and created my own context.</p>

<p><a href=""https://msdn.microsoft.com/en-us/library/dn314431(v=vs.113).aspx"" rel=""nofollow noreferrer"">Entity Framework Testing with Your Own Test Doubles (EF6 onwards)</a></p>

<p>In the product code, there is a call to <code>DbContext.Database.SqlQuery&lt;TElement&gt;(sql, params);</code> method and the code is consuming <code>ToListAsync</code> method of <code>DbRawSqlQuery&lt;TElement&gt;</code>. </p>

<p>I am stuck here to mock this call.</p>
",https://stackoverflow.com/questions/41908280/unit-testing-how-can-i-mock-dbcontext-database-sqlquerytelementsql-params,"['c#', 'unit-testing', 'entity-framework-6']",903,FALSE,3,0
Angular 4 - Unit testing using Jasmine - Button click code showing error,"<p>I am new to Jasmine. Writing code in Angular 4. I want to test a button. I wrote following code in my spec file. This is the functionality of multi file upload. And on selection of file(s), we are allowing user to upload files.</p>

<pre><code>import {
    async,
    ComponentFixture,
    TestBed
} from '@angular/core/testing';

import {
    UploaddocumentComponent
} from './uploaddocument.component';

describe('UploaddocumentComponent', () =&gt; {
    let component: UploaddocumentComponent;
    let fixture: ComponentFixture &lt; UploaddocumentComponent &gt; ;

    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
                declarations: [UploaddocumentComponent]
            })
            .compileComponents();
    }));

    beforeEach(() =&gt; {
        fixture = TestBed.createComponent(UploaddocumentComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    // it('should create', () =&gt; {
    //   expect(component).toBeTruthy();
    // });
    it('should', async(() =&gt; {
        spyOn(component, 'uploadFileByRest');

        let button = fixture.debugElement.nativeElement.querySelector('button');
        button.click();

        fixture.whenStable().then(() =&gt; {
            expect(component.uploadFileByRest).toHaveBeenCalled();
        })
    }));
});
</code></pre>

<p>In PhantomJS browser, seeing following issue. How to resolve?</p>

<pre><code>invoke@webpack:///~/zone.js/dist/zone.js:490:0 &lt;- src/polyfills.ts:3454:
PhantomJS 2.1.1 (Windows 7 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.981 
secs/ 0.127 secs)
</code></pre>

<p><code>HTML</code></p>

<pre><code>&lt;button pButton type=""button"" icon=""fa-check"" class=""form-control"" 
(click)=""uploadFileByRest(); file.value = ''"" [disabled]=""!isFileSelected""
label=""Upload""&gt;&lt;/button&gt;
</code></pre>

<p><code>TS</code></p>

<pre><code>doUploadByRest() {
   //Saving file to Alfresco and DB
}
</code></pre>

<p>Chrome showing as </p>

<p><a href=""https://i.stack.imgur.com/amtm2.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/amtm2.png"" alt=""enter image description here""></a></p>

<p>HTML 21 line it's showing issue I think, isRequestFromView - how to give input to testing code?</p>

<pre><code>    21 line &lt;div class=""row"" *ngIf=""!isRequestFromView""&gt;
        &lt;p-messages [(value)]=""msgs""&gt;&lt;/p-messages&gt;            
        &lt;div class=""col-md-4""&gt;
            &lt;label&gt;Add File:&lt;/label&gt;
            &lt;input multiple type=""file"" name=""filedata"" class=""form-control"" #file (change)=""fileChangeEvent(file.files)"" /&gt;
        &lt;/div&gt;
        &lt;div class=""col-md-2""  style=""margin-top:25px""&gt;
            &lt;button pButton type=""button"" icon=""fa-check"" class=""form-control"" (click)=""uploadFile(); file.value = ''"" [disabled]=""!isFileSelected""
                label=""Upload""&gt;&lt;/button&gt;
        &lt;/div&gt;
    &lt;/div&gt;
</code></pre>
",https://stackoverflow.com/questions/45037537/angular-4-unit-testing-using-jasmine-button-click-code-showing-error,"['html', 'angular', 'typescript', 'jasmine', 'karma-jasmine']",1915,FALSE,2,1
"Unit testing in Vuex throwing AssertionError to equal { Object (type, text) }","<p>So far unit testing Vuex actions have been a nightmare, I can't seem to understand what it's actually looking for. I'm following <a href=""https://vuex.vuejs.org/en/testing.html"" rel=""nofollow noreferrer"">https://vuex.vuejs.org/en/testing.html</a> and using their action helper function.</p>

<p>I have a simple action that will add text to a button.</p>

<pre><code>createButton({ commit, state }, payload) {
    let btnString = '';

    if (payload.hasCookie) {
        btnString = 'Welcome back';
    } else if (payload.isLoggedIn) {
        btnString = 'Sign out';
    } else {
        btnString = 'Sign up';
    }

    commit({ type: 'CREATE_BUTTON_TEXT', text: btnText });
},
</code></pre>

<p>In my test...</p>

<pre><code>describe('Create Button Text', () =&gt; {
        it('should render the buttons string ', (done) =&gt; {
            const expectedString = 'Welcome back';
            const mock = {
                hasCookie: true,
                isLoggedIn: false,
            };

            testAction(actions.createButton, mock, state, [
                { type: 'CREATE_BUTTON_TEXT', text: expectedString },
            ], done);
        });
    });
</code></pre>

<p>It's returning <code>AssertionError: expected 'CREATE_BUTTON_TEXT' to equal { Object (type, text) }</code>... Am I not providing the expected <code>text</code> with <code>expectedString</code> correctly? Any guidance on this matter would be greatly appreciated.</p>

<p>(Using Mocha + Chai as per recommendation in the docs).</p>
",https://stackoverflow.com/questions/42863283/unit-testing-in-vuex-throwing-assertionerror-to-equal-object-type-text,"['unit-testing', 'vue.js', 'mocha.js', 'chai', 'vuex']",356,FALSE,2,1
How do I go about unit testing with Entity Framework and Moq?,"<p>I'm new to Moq, and wanting to use it like a backing store for data - but without touching the live database.</p>

<p>My setup is as follows:</p>

<ul>
<li>A UnitOfWork contains all repositories, and is used for data access throughout the application.</li>
<li>A Repository represents a direct hook into a DbSet, provided by a DbContext.</li>
<li>A DbContext contains all DbSets.</li>
</ul>

<p>Here is my test so far:</p>

<pre><code>        // ARRANGE
        var user = new User()
        {
            FirstName = ""Some"",
            LastName = ""Guy"",
            EmailAddress = ""some.guy@mockymoqmoq.com"",
        };

        var mockSet = new MockDbSet&lt;User&gt;();
        var mockContext = new Mock&lt;WebAPIDbContext&gt;();

        mockContext.Setup(c =&gt; c.Set&lt;User&gt;()).Returns(mockSet.Object);

        // ACT
        using (var uow = UnitOfWork.Create(mockContext.Object))
        {
            uow.UserRepository.Add(user);
            uow.SaveChanges();
        }

        // ASSERT
        mockSet.Verify(u =&gt; u.Add(It.IsAny&lt;User&gt;()), Times.Once());
</code></pre>

<p>My test seems to be successful, as it can verify that a user was added to the mock DbSet - but what I need to do is actually get that data back and perform further assertions on it (this is just an ad-hoc test).</p>

<p>Please advise, testing frameworks are doing my head in. Also, I have the option to move to other testing frameworks if they are easier to use.</p>

<p>Thank you.</p>

<p><strong>Update: Here is my working code.</strong></p>

<p><em>Unit Test</em></p>

<pre><code>        // ARRANGE
        var user = new User()
        {
            FirstName = ""Some"",
            LastName = ""Guy"",
            EmailAddress = ""some.guy@mockymoqmoq.com"",
        };

        var mockSet = new MockDbSet&lt;User&gt;();
        var mockContext = new Mock&lt;WebAPIDbContext&gt;();

        mockContext.Setup(c =&gt; c.Set&lt;User&gt;()).Returns(mockSet.Object);

        // ACT
        using (var uow = UnitOfWork.Create(mockContext.Object))
        {
            uow.UserRepository.Add(user);
            uow.SaveChanges();
        }

        // ASSERT
        mockSet.Verify(u =&gt; u.Add(It.IsAny&lt;User&gt;()), Times.Once());

        // TODO: Further assertations can now take place by accessing mockSet.BackingStore.
    }
</code></pre>

<p><em>MockDbSet</em></p>

<pre><code>class MockDbSet&lt;TEntity&gt; : Mock&lt;DbSet&lt;TEntity&gt;&gt; where TEntity : class
{
    public ICollection&lt;TEntity&gt; BackingStore { get; set; }

    public MockDbSet()
    {
        var queryable = (this.BackingStore ?? (this.BackingStore = new List&lt;TEntity&gt;())).AsQueryable();

        this.As&lt;IQueryable&lt;TEntity&gt;&gt;().Setup(e =&gt; e.Provider).Returns(queryable.Provider);
        this.As&lt;IQueryable&lt;TEntity&gt;&gt;().Setup(e =&gt; e.Expression).Returns(queryable.Expression);
        this.As&lt;IQueryable&lt;TEntity&gt;&gt;().Setup(e =&gt; e.ElementType).Returns(queryable.ElementType);
        this.As&lt;IQueryable&lt;TEntity&gt;&gt;().Setup(e =&gt; e.GetEnumerator()).Returns(() =&gt; queryable.GetEnumerator());

        // Mock the insertion of entities
        this.Setup(e =&gt; e.Add(It.IsAny&lt;TEntity&gt;())).Returns((TEntity entity) =&gt;
        {
            this.BackingStore.Add(entity);

            return entity;
        });

        // TODO: Other DbSet members can be mocked, such as Remove().
    }
}
</code></pre>
",https://stackoverflow.com/questions/45558470/how-do-i-go-about-unit-testing-with-entity-framework-and-moq,"['c#', 'entity-framework', 'unit-testing', 'entity-framework-6', 'moq']",11850,TRUE,8,1
EmberJS 2.13 unit testing: wrapping synchronous code in a run loop?,"<p>This is repeated a few times in the current Ember documentation, so I feel like I must be missing something. Let's take the <a href=""https://guides.emberjs.com/v2.13.0/testing/testing-models/"" rel=""nofollow noreferrer"">simplest example I found</a>.</p>

<p>Why is the call to levelUp considered asynchronous to warrant wrapping it in the run loop?<br>
<a href=""https://github.com/emberjs/ember.js/blob/299c1ab3d804fd92b0ec9b9c2e7a1fa100335753/packages/ember-runtime/lib/mixins/observable.js#L428"" rel=""nofollow noreferrer"">incrementProperty</a> is synchronous, and as far as I can tell, so is <a href=""https://github.com/emberjs/ember.js/blob/ee8ab348484421f254fe995c6f04f0d4a0859cfa/packages/ember-metal/lib/property_set.js#L18"" rel=""nofollow noreferrer"">set</a> (but I could be mistaken here)</p>

<p>player.js</p>

<pre><code>import DS from 'ember-data';

export default DS.Model.extend({
  level:     DS.attr('number', { defaultValue: 0 }),
  levelName: DS.attr('string', { defaultValue: 'Noob' }),

  levelUp() {
    let newLevel = this.incrementProperty('level');
    if (newLevel === 5) {
      this.set('levelName', 'Professional');
    }
  }
});
</code></pre>

<p>player-test.js</p>

<pre><code>import { moduleForModel, test } from 'ember-qunit';
import Ember from 'ember';

moduleForModel('player', 'Unit | Model | player', {
  // Specify the other units that are required for this test.
  needs: []
});

test('should increment level when told to', function(assert) {
  // this.subject aliases the createRecord method on the model
  const player = this.subject({ level: 4 });

  // wrap asynchronous call in run loop
  Ember.run(() =&gt; player.levelUp());

  assert.equal(player.get('level'), 5, 'level gets incremented');
  assert.equal(player.get('levelName'), 'Professional', 'new level is called professional');
});
</code></pre>
",https://stackoverflow.com/questions/43794454/emberjs-2-13-unit-testing-wrapping-synchronous-code-in-a-run-loop,"['ember.js', 'ember-data', 'ember-testing']",474,TRUE,2,2
Xamarin.Forms unit testing of a View page fail with static resources,"<p>I'm trying to build a unit test for a View page in my XF application, although I can't really find any detail around this on the web, I've gotten Xamarin.Forms.Mocks package installed, but I'm running into a snag.</p>

<p>Take my View page:</p>

<pre><code>public partial class WelcomePage : ContentPage
{
    public WelcomePage()
    {
        InitializeComponent();
        NavigationPage.SetHasNavigationBar(this, false);
        WelcomeTransaction();
    }

    public async void WelcomeTransaction()
    {
        ButtonRegister.Opacity = 0;
        ButtonRegisterNewDevice.Opacity = 0;

        await Task.WhenAny&lt;bool&gt;
        (
          ButtonRegister.FadeTo(1, 1000, Easing.SinIn),
          ButtonRegisterNewDevice.FadeTo(1, 1000, Easing.SinIn)
        );
    }
}
</code></pre>

<p>Very simple class.</p>

<p>My issue is that my tests keep failing on ""InitializeComponent"" because I have static resources attached.</p>

<p>My XAML:</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;ContentPage xmlns=""http://xamarin.com/schemas/2014/forms"" xmlns:x=""http://schemas.microsoft.com/winfx/2009/xaml"" xmlns:prism=""clr-namespace:Prism.Mvvm;assembly=Prism.Forms"" prism:ViewModelLocator.AutowireViewModel=""True"" x:Class=""Sandbox.Views.WelcomePage""&gt;
    &lt;ContentPage.Content&gt;
        &lt;AbsoluteLayout VerticalOptions=""FillAndExpand"" HorizontalOptions=""FillAndExpand""&gt;
            &lt;Image Source=""splashscreen.png"" Aspect=""Fill"" AbsoluteLayout.LayoutFlags=""All"" AbsoluteLayout.LayoutBounds=""0, 1, 1, 1"" /&gt;
            &lt;StackLayout Padding=""15"" Spacing=""1"" AbsoluteLayout.LayoutFlags=""All"" AbsoluteLayout.LayoutBounds=""1, 1, 1, 0.5"" VerticalOptions=""EndAndExpand""&gt;
                &lt;Button x:Name=""ButtonRegister"" AutomationId=""ButtonRegister"" Text=""REGISTER"" Style=""{StaticResource ButtonNormal}"" Command=""{Binding RegisterCommand}""&gt;
                &lt;/Button&gt;
                &lt;Button x:Name=""ButtonRegisterNewDevice"" AutomationId=""ButtonRegisterNewDevice"" Text=""REGISTER A NEW DEVICE"" Style=""{StaticResource ButtonHighlighted}"" Command=""{Binding RegisterNewDeviceCommand}"" /&gt;
            &lt;/StackLayout&gt;
        &lt;/AbsoluteLayout&gt;
    &lt;/ContentPage.Content&gt;
&lt;/ContentPage&gt;
</code></pre>

<p>My unit test:</p>

<pre><code>[TestFixture]
public class ViewTest
{
    private Views.WelcomePage _welcome;

    [SetUp]
    public void BeforeEach()
    {
        Xamarin.Forms.Mocks.MockForms.Init();
    }

    [Test]
    [Category(""Welcome Page View"")]
    public void Can_Call_Constructor()
    {
        _welcome = Substitute.For&lt;Views.WelcomePage&gt;();

    }
}
</code></pre>

<p>I'm using NSubstitute, Xamarin.Forms.Mock, Moq and NUnit.</p>

<p>I'm trying to do this as part of a learning scenario, and would appreciate any input.</p>
",https://stackoverflow.com/questions/46789225/xamarin-forms-unit-testing-of-a-view-page-fail-with-static-resources,"['c#', 'unit-testing', 'xamarin.forms']",1353,TRUE,2,2
How to mock promisified Mysql data using sinon for Unit Testing,"<p>Is it possible to mock promisified queries in NodeJS using sinon for <code>require('promise-mysql')</code>  npm package. As Sinon allows us to mock and / or stub out methods on objects. Say I want to override the createConnection() method so that it returns a valid object regardless of whether the database settings were right or not, I'd stub out that method. I am able to mock that using <code>require('mysql')</code> npm package which is having callbacks.</p>

<p>But, as <code>require('promise-mysql')</code> package returns promise, I am not sure about how to mock test data for same.</p>

<p>For <code>require('mysql')</code> package this is working perfectly</p>

<pre><code>var successConnectionObject = {
        connect: function(cb) {
            cb();
        },
        query: function(sqlQury, cb) {
            if (sqlQury === 'SELECT * FROM USERS') {
                cb(null, constants.USERQueryResp);
            } else {
                cb(null, '');
            }
        },
        end: function() {} 
}

var testMysqlDriver = require('mysql');
var stub = sinon.stub(testMysqlDriver, 'createConnection');
stub.returns(successConnectionObject);

 publish.handler(some_JSON_Request, some_Context_Values, function(err, data) {
    expect(data.message).toBe(USER_Query_Response);
    done();
}); 
</code></pre>

<p>how can we achieve same this using <code>require('promise-mysql');</code></p>
",https://stackoverflow.com/questions/42072666/how-to-mock-promisified-mysql-data-using-sinon-for-unit-testing,"['mysql', 'node.js', 'unit-testing', 'sinon', 'sinon-chai']",1910,TRUE,2,1
can we emulate print mode (media query print) for unit testing?,"<p>can we emulate print mode (media query print) for unit testing?
(Ract, enzyme, jest) i try:</p>

<pre><code>window.matchMedia('print')
</code></pre>

<p>but it does not work for me, style media print not applied;</p>
",https://stackoverflow.com/questions/47219643/can-we-emulate-print-mode-media-query-print-for-unit-testing,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'enzyme']",636,TRUE,2,1
Good practice to add protected methods for sake of unit testing?,"<p>Say I have the following class:</p>

<pre><code>public class ProblematicObject {
    public static void methodToTest() {
        SomeDependency dep = DependencyGetter.getDependency(SomeDependency.class);
        dep.doStuff();
    }
}
</code></pre>

<p>Is it an acceptable practice to modify and add methods to this class for the sake of making unit testing cleaner (aka avoiding PowerMock)?  Here's what the class above would look like:</p>

<pre><code>public class ProblematicObject {

    // new
    private static SomeDependency dep;

    // updated
    public static void methodToTest() {
        getSomeDependency().doStuff();
    }

    // new
    private SomeDependency getSomeDependency() {
        if (this.dep == null) {
            return DependencyGetter.getDependency(SomeDependency.class);
        }
        return dep;
    }

    // new, only used for testing, not in any impl code
    @Deprecated
    protected void setDependencyGetter(SomeDependency dep) {
        this.dep = dep;
    }

}
</code></pre>

<p>I seem to recall reading somewhere that adding methods for the sake of testing (instead of refactoring the problematic class) is looked down upon.</p>
",https://stackoverflow.com/questions/46735521/good-practice-to-add-protected-methods-for-sake-of-unit-testing,"['java', 'unit-testing', 'junit', 'dependency-injection']",476,TRUE,2,1
Unit testing a stored proc called with Entity Framework Core 1.1.2,"<p>I have a method that uses Entity Framework to call a stored proc, the stored proc returns some data.</p>

<p>Something like the following </p>

<pre><code>public async Task&lt;IActionResult&gt; Get(int customerId)
{
   List&lt;Product&gt; products = _context.Products.FromSql(""EXECUTE dbo.SpGatherProductInfo {0}"", customerId)
        .ToList();

   if (!products.Any())
   {
      return NotFound();
   }

   return Ok(products);
}
</code></pre>

<p>If this were a simple query to a table, I would create an in-memory db, add some fake entries and everything would be fine. </p>

<p>But this uses a stored proc, how do I unit test this? </p>
",https://stackoverflow.com/questions/46104480/unit-testing-a-stored-proc-called-with-entity-framework-core-1-1-2,"['entity-framework', 'unit-testing', 'testing', 'entity-framework-core']",3608,TRUE,2,2
How to mock an imported subroutine when unit-testing a module,"

<p>Consider a module which exports a subroutine that connects to the Internet and returns a result:</p>

<pre class=""lang-perl6 prettyprint-override""><code>unit module A;

sub download is export {
     ""result from internet""  # Not the actual implementation, obviously.
}
</code></pre>

<p>And another module which imports and calls that subroutine:</p>

<pre class=""lang-perl6 prettyprint-override""><code>use A;  # imports &amp;download into this lexical scope
unit module B;

sub do-something is export {
     download().uc ~ ""!!""   # Does something which involves calling &amp;download
}
</code></pre>

<p>Now I'd like to write unit tests for module <code>B</code>.<br>
But I don't want the tests to actually connect to the Internet; I'd like them to use a mock version of subroutine <code>download</code> that is controlled by my test script:</p>

<pre class=""lang-perl6 prettyprint-override""><code>use Test;
plan 2;

use B;

my $mock-result;
my &amp;mock-download = -&gt; { $mock-result }

# ...Here goes magic code that installs &amp;mock-download
# as &amp;download in B's lexical scope...

$mock-result = ""fake result"";
is do-something(), ""FAKE RESULT!!"", ""do-something works - 1"";

$mock-result = ""foobar"";
is do-something(), ""FOOBAR!!"", ""do-something works - 2"";
</code></pre>

<p>The problem is the missing magic code to override sub <code>download</code>...</p>

<p>In Perl 5, I think this could be achieved pretty easily using glob assignment, or even nicer with the help of <a href=""https://metacpan.org/pod/Sub::Override"" rel=""nofollow noreferrer"">Sub::Override</a> or <a href=""https://metacpan.org/pod/Test::MockModule"" rel=""nofollow noreferrer"">Test::MockModule</a>.</p>

<p>But in Perl 6, the lexical scope of module <code>B</code> closes when it has finished compiling, and can thus no longer be modified by the time the test script is run (correct me if I'm wrong). So this approach doesn't seem possible.</p>

<p>How would one solve this task in Perl 6, then?<br>
I.e. how would one write unit tests for <code>B::do-something</code>, without letting it call the real <code>A::download</code>?</p>
",https://stackoverflow.com/questions/42645801/how-to-mock-an-imported-subroutine-when-unit-testing-a-module,"['unit-testing', 'mocking', 'raku']",596,TRUE,2,1
Unit Testing - Services in ngOnInit: error &#39;map is not a function&#39;,"<p>I try to test a component using Jasmine &amp; Karma, but when I want to test whether the my services have been called in ngOnInit() I get an error that I don't understand:</p>

<pre><code>Failed: Uncaught (in promise): TypeError: tagelers.map is not a function
TypeError: tagelers.map is not a function
    at tagelerService.getTagelers.then (http://localhost:9876/base/src/test.ts?779e448059ef6555f776fac9a62a71930cc82ee7:68007:38)
    ....
</code></pre>

<p>My component looks like this:</p>

<pre><code>import ..

@Component({
  selector: 'app-group-details',
  templateUrl: 'group-details.component.html',
  styleUrls: ['group-details.component.css'],
})

export class GroupDetailsComponent implements OnInit {
  @Input()
  tageler: Tageler;
  tagelers: Tageler[];
  group: Group;

  constructor(
    private route: ActivatedRoute,
    private groupService: GroupService,
    private tagelerService: TagelerService) {
  }

  ngOnInit() {
    console.log(""Init Details"");
    this.route.params
      .switchMap((params: Params) =&gt; this.groupService.getGroup(params['id']))
      .subscribe(group =&gt; this.group = group);

    this.tagelerService
      .getTagelers()
      .then((tagelers: Tageler[]) =&gt; {
        this.tagelers = tagelers.map((tageler) =&gt; {
          if (!tageler.title) {
            tageler.title = 'default';
          }
          return tageler;
        });
      });
  }
}
</code></pre>

<p>This is how the method looks like in the tagelerService:</p>

<pre><code>getTagelers(): Promise&lt;Tageler[]&gt; {
return this.http.get(this.tagelersUrlGet)
  .toPromise()
  .then(response =&gt; response.json() as Tageler[])
  .catch(this.handleError);
}
</code></pre>

<p>And this my test is my spec.ts file that fails:</p>

<pre><code>it('should get tagelers when ngOnInit is called', async(() =&gt; {
    spyOn(tagelerService, 'getTagelers').and.returnValue(Promise.resolve(Tageler));
    component.ngOnInit();
    fixture.detectChanges();
    expect(tagelerService.getTagelers).toHaveBeenCalled();
}));
</code></pre>

<p>Does anyone know why there is a '.map is not a function' error? I guess the problem is a wrong implementation of the 'spyOn' (it does not return what I need), but I don't know how to change it. </p>

<p>Thanks for your help!</p>
",https://stackoverflow.com/questions/43374000/unit-testing-services-in-ngoninit-error-map-is-not-a-function,"['unit-testing', 'angular', 'jasmine']",4785,TRUE,2,1
How do I create an LLVM machine instruction for unit testing?,"<p>I am writing a piece of code that recognizes certain patterns at the machine function level of the LLVM stack.  I would like to write a test driver for this component. The test driver would need to create a snippet of machine code and pass an instruction pointer to my matcher:</p>

<pre><code>MachineInstruction* mi = createSnipit(...);
bool result = matcher(mi, ...);
ASSERT_TRUE(result);
</code></pre>

<p>If this were not a stand-alone test driver, creating a new instruction or set of instructions in a specific basic-block would be easy.  However, the test driver is a stand-alone program and is not invoked from the compiler.  Somehow, it seems, I need to create a machine function, a basic block, and an instance of MachineRegisterInfo before I can create any instructions.  How do I do that so that everything is correctly linked up and the LLVM infrastructure is in a consistent state?</p>
",https://stackoverflow.com/questions/47006976/how-do-i-create-an-llvm-machine-instruction-for-unit-testing,"['llvm', 'machine-instruction']",178,FALSE,1,0
django unit testing with fixtures - object matching query does not exist,"<p>I am trying to set up unit testing in django using fixtures.</p>

<p>I can successfully load my fixtures, but when I attempt to retrieve data from them I get the error: </p>

<p><code>DoesNotExist: BlogIndexPage matching query does not exist.</code></p>

<p>Here is my code for the test (I'm using the Wagtail CMS, which extends unittest with <a href=""http://docs.wagtail.io/en/v1.12.2/advanced_topics/testing.html?highlight=allowed_subpage_models"" rel=""nofollow noreferrer"">a few additional methods</a>):</p>

<pre><code>class BlogTests(WagtailPageTests):
    fixtures = ['demosite.json']

    def test_can_create_blog_entry(self):
        blog_index_page = BlogIndexPage.objects.get(pk=5)
        self.assertCanCreate(blog_index_page, BlogPage, {
            'title': 'Post 2',
            'date': '2017-10-11',
            'intro': 'Post 2',
            'body': '&lt;p&gt;Test Post&lt;/p&gt;'
        })
</code></pre>

<p>And this is my fixture:</p>

<pre><code>[
{
    ""pk"": 1,
    ""model"": ""wagtailcore.page"",
    ""fields"": {
        ""title"": ""Root"",
        ""draft_title"": ""Root"",
        ""numchild"": 1,
        ""show_in_menus"": false,
        ""live"": true,
        ""seo_title"": """",
        ""depth"": 1,
        ""search_description"": """",
        ""content_type"": [
            ""wagtailcore"",
            ""page""
        ],
        ""has_unpublished_changes"": false,
        ""owner"": null,
        ""path"": ""0001"",
        ""url_path"": ""/"",
        ""slug"": ""root""
    }
},
{
    ""pk"": 2,
    ""model"": ""wagtailcore.page"",
    ""fields"": {
        ""title"": ""Home page"",
        ""draft_title"": ""Home page"",
        ""numchild"": 5,
        ""show_in_menus"": true,
        ""live"": true,
        ""seo_title"": """",
        ""depth"": 2,
        ""search_description"": """",
        ""content_type"": [
            ""home"",
            ""homepage""
        ],
        ""has_unpublished_changes"": false,
        ""owner"": null,
        ""path"": ""00010002"",
        ""url_path"": ""/home-page/"",
        ""slug"": ""home-page""
    }
},
{
    ""pk"": 5,
    ""model"": ""wagtailcore.page"",
    ""fields"": {
        ""title"": ""Blog index"",
        ""draft_title"": ""Blog index"",
        ""numchild"": 3,
        ""show_in_menus"": true,
        ""live"": true,
        ""seo_title"": """",
        ""depth"": 3,
        ""search_description"": """",
        ""content_type"": [
            ""blog"",
            ""blogindexpage""
        ],
        ""has_unpublished_changes"": false,
        ""owner"": null,
        ""path"": ""000100020002"",
        ""url_path"": ""/blog/"",
        ""slug"": ""blog""
    }
},
{
    ""pk"": 16,
    ""model"": ""wagtailcore.page"",
    ""fields"": {
        ""title"": ""Blog post"",
        ""draft_title"": ""Blog post"",
        ""numchild"": 0,
        ""show_in_menus"": false,
        ""live"": true,
        ""seo_title"": """",
        ""depth"": 4,
        ""search_description"": ""The origin of the genus appears to be in the general area of Eastern Siberia/Mongolia. Wagtails spread rapidly across Eurasia and dispersed to Africa in the Zanclean (Early Pliocene) where the sub-Saharan lineage was later isolated. The African Pied Wagtail (and possibly the Mekong Wagtail) diverged prior to the massive radiation of the white-bellied black-throated and most yellow-bellied forms, all of which took place during the late Piacenzian (early Late Pliocene), c. 3 mya."",
        ""content_type"": [
            ""blog"",
            ""blogpage""
        ],
        ""has_unpublished_changes"": false,
        ""owner"": null,
        ""path"": ""0001000200020001"",
        ""url_path"": ""/home-page/blog-index/blog-post/"",
        ""slug"": ""blog-post""
    }
}
]
</code></pre>

<p>So basically I just want to grab that blog index page, and test whether I can create a blogpage (blog post) underneath it. What am I doing wrong?</p>
",https://stackoverflow.com/questions/46720446/django-unit-testing-with-fixtures-object-matching-query-does-not-exist,"['python', 'django', 'unit-testing', 'python-unittest', 'wagtail']",760,TRUE,1,1
How to properly setup unit testing for my c++ game project?,"<p>I'm currently creating a 2d game in C++ using visual studio and utilizing gtest/gmock for my testing framework. The problem I'm having is I'm not sure what my best option is for testing. I'm using SDL and opengl and if I try and test normally my test project crashes when it hits any opengl calls. I'm using glew to access opengl so in my game I setup glew and call glew.init() within my window class:</p>

<pre><code>void Window::Initialize()
    {
        if (SDL_Init(SDL_INIT_VIDEO) != 0)
        {
            SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, ""SDL Error"", ""SDL did not initialize"", nullptr);
            SDL_Quit();
        }

        /** All attributes need to be set before window creation **/

        p_window = SDL_CreateWindow(""Shadow Gods"", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1024, 768, SDL_WINDOW_OPENGL);
        if (!p_window)
        {
            LOG(""ERROR: SDL window failed to initialize! SDL error: %s\n"", SDL_GetError());
            SDL_Quit();
        }

        glContext = SDL_GL_CreateContext(p_window);

        glewExperimental = GL_TRUE;
        if (glewInit() != GLEW_OK)
        {
            LOG(""ERROR: GLEW failed to initialize!"");

            SDL_GL_DeleteContext(glContext);
            SDL_DestroyWindow(p_window);
            SDL_Quit();
        }

        //Sets the values that the depth and color buffers will be set to when glClear is called
        glClearDepth(1.0);
        glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
    }
</code></pre>

<p>Now in order to test any of my classes that utilize openGL calls I need to make sure to create a window object first and initialize before calling any other code:</p>

<pre><code>#include &lt;gtest\gtest.h&gt;
#include ""GameEngine\Window.h""
#include ""GameEngine\Sprite.h""

TEST(SpriteClassTest, SpriteInitialize_True)
{
    Blz::Window win;
    win.Initialize();
    Sprite sprite;
    ASSERT_TRUE(sprite.Init(23, 32, 100, 100, ""../Game/CharImage.png""));
}
</code></pre>

<p>I don't want to have to do this for every class that utilizes opengl since 1.) It's redundant and 2.) My tests might be failing because there is something wrong with the window initialize() function instead of what tests were designed for. So is there a better way? </p>
",https://stackoverflow.com/questions/44611035/how-to-properly-setup-unit-testing-for-my-c-game-project,"['c++', 'unit-testing', 'opengl', 'sdl']",743,FALSE,1,0
Unit Testing Angular with Jasmine : Trigger a click on a button,"<p>I'm testing a component within my Angular app:</p>

<pre><code>it('should not save empty alert after click on save button (async)', async(() =&gt; {
            fixture.detectChanges();
            fixture.whenStable().then(() =&gt; {
                let Btn = fixture.debugElement.query(By.css('#btn-createAlert')).nativeElement;
                comp.setCurrentAlert({});
                expect(comp.getCurrentAlert().title).toBeUndefined();
                expect(comp.getCurrentAlert().shops).toBeUndefined();
                // click(saveBtn); ???
                saveBtn.trigger('click');
                fixture.detectChanges();
                expect(saveSpy.calls.any()).toBe(false, 'alertService.saveAlert called');
                expect(saveAlertShopsSpy.calls.any()).toBe(false, 'alertService.saveAlertShops called');
                expect(loadAllSpy.calls.count()).toBe(1, 'alertService.getAllAlerts called only on ngOnInit');
            });
        }));
</code></pre>

<p>Within my test case like you have seen , i'm getting the reference of my button :</p>

<pre><code>let Btn = fixture.debugElement.query(By.css('#btn-createAlert')).nativeElement;
</code></pre>

<p>Not to get my test case working i need to trigger a click on it.</p>

<p>Unfortenately , i cannot find any native jasmine tool to do it .</p>

<p>The following suggestion is not working :</p>

<pre><code>saveBtn.trigger('click');
</code></pre>

<p>And i don't want to import any external library to do it (neither <strong>jquery</strong> , nor <strong>jasmine-matchers</strong>)</p>

<p><strong>Any suggestions ?</strong></p>
",https://stackoverflow.com/questions/47053646/unit-testing-angular-with-jasmine-trigger-a-click-on-a-button,"['javascript', 'angular', 'unit-testing', 'typescript', 'jasmine']",326,FALSE,1,0
Unit testing legacy php application — how to prevent unexpected database calls,"<p>I'm adding unit tests to a legacy PHP application that uses a MySQL compatible database. I want to write genuine unit tests that don't touch the database.</p>

<p>How should I avoid accidentally using a database connection?</p>

<p>Lots of parts of the application use static method calls to get a reference to a database connection wrapper object. If I'm looking at one of these calls I know how to use dependency injection and test doubles to avoid hitting the database from a test, but I'm not sure what to do about all the database queries that I'm not looking at at any one time, which could be some way down the call stack from the method I'm trying to test.</p>

<p>I've considered adding a public method to the database access class that would be called from the PHPUnit bootstrap file and set a static variable to make any further database access impossible, but I'm not keen on adding a function to the application code purely for the sake of the tests that would be harmful if called in production.</p>
",https://stackoverflow.com/questions/45724687/unit-testing-legacy-php-application-how-to-prevent-unexpected-database-calls,"['php', 'mysql', 'database', 'unit-testing', 'phpunit']",380,TRUE,1,1
Karma unit testing - finding out which abstract class a component implements,"<p>I'm quite new to AngularJS and Karma. Nevertheless I'm ordered to write meaningful unit tests. As we are asked to implement the classes <code>OnInit</code> and <code>OnDestroy</code> in each component we create, I wonder whether there is a way to check with Karma if a component actually implements them.</p>

<p>Has anybody got an idea?</p>
",https://stackoverflow.com/questions/41889683/karma-unit-testing-finding-out-which-abstract-class-a-component-implements,"['unit-testing', 'angular', 'karma-runner']",545,TRUE,1,1
Mocha / Sinon - Unit testing / stubbing function with child_process.exec inside ES6 Promise,"<p>I have a function that returns an ES6 promise for use in another external promise chain. The function scans for wifi networks using child_process.exec. The output from exec is sent via the callback to a synchronous parsing function that will return the output in a formatted object, and then resolve the outer promise:</p>

<pre><code>var exec = require('child_process').exec;

function scan() {
    return new Promise((resolve, reject) =&gt; {

        // getCurrent returns a promise
        getCurrent().then(network =&gt; {
            exec('iwlist wlan0 scan', function(err, stdout, stderr) {
                (err) ? reject(stderr) : resolve(parseOutput(stdout, network));                 
            });
        })
        .catch(err =&gt; {
            reject(err);
        }); 
    }); 
}
</code></pre>

<p>The problem is, I can't seem to get sinon stubs working properly to get the stubbed version of exec to be called.  Currently I have something along the lines of:</p>

<pre><code>var wifi = require('./wifi');

describe('#scan', function() {

    it('Should scan and return networks object', function() {

        var fakeNetwork = '(fake iwlist output goes here)';  
        var exec = sinon.stub(child_process, 'exec').yields(false, fakeNetwork);
        var getCurrent = sinon.stub(wifi, 'getCurrent').returns(Promise.resolve('current-ssid'));

        wifi.scan().then(function(networks) {
            console.log(networks);
            sinon.assert.calledOnce(getCurrent);
            sinon.assert.calledOnce(exec);
        });

        getCurrent.restore();
        exec.restore();

    });
});
</code></pre>

<p>I have also tried stubbing like:</p>

<pre><code>var getCurrent = sinon.stub(wifi, 'getCurrent', function() {
    return Promise.resolve('current-ssid').then(network =&gt; {
        exec('iwlist wlan0 scan', function(err, data) {
            return(wifi.parseOutput(data, network));                
        });
    });
});
</code></pre>

<p>The behavior seems to be that either exec never gets called, or more strangely, that the stubbed exec does get called, but the 'real' functions get called anyway.  </p>

<p>With all of the stubs, all I am really ""testing"" is the parseOutput method, so should I just ditch testing the 'scan' function completely and only focus on the parse function (which would be simple to test), or is there another way I should be looking at this?  </p>

<p>I believe I am just doing something obviously wrong, and have been hitting a wall here for several hours.  I'm hoping someone has run into this before and can suggest an alternative/better approach.</p>
",https://stackoverflow.com/questions/41770314/mocha-sinon-unit-testing-stubbing-function-with-child-process-exec-inside,"['javascript', 'unit-testing', 'mocha.js', 'sinon']",2159,TRUE,1,1
TypeError: studentsList.forEach is not a function. Jasmine Unit Testing (Angular 2),"<p>How to test the forEach loop in jasmine using karma??
The component code is as follows:-</p>

<pre><code>getData(studentsList:any, day:any, game:any){
let strength:any;
let location:string;
   if(studentsList){
    studentsList.forEach( value =&gt; {
     strength=value.schedule[day][game].strength;
     location=value.schedule[day][game].location;
});
}
}
</code></pre>

<p>the data present in studentsList is:-</p>

<p><strong>(Edit:- the data is updated it looks like this)</strong></p>

<pre><code>    [{
        ""activityName"": ""tournament1"",
        ""schedule"": {
            ""first"": {
                ""Baseball"": {
                    ""strength"": 23,
                    ""location"": ""abc""
                }
            },
            ""second"": {
                ""Cricket"": {
                    ""strength"": 20,
                    ""location"": ""bcd""
                }
            },
            ""third"": {
                ""Football"": {
                    ""strength"": 19,
                    ""location"": ""cde""
                }
            }
        }
    },
{
        ""activityName"": ""tournament2"",
        ""schedule"": {
            ""first"": {
                ""Baseball"": {
                    ""strength"": 23,
                    ""location"": ""abc""
                }
            },
            ""second"": {
                ""Cricket"": {
                    ""strength"": 20,
                    ""location"": ""bcd""
                }
            },
            ""third"": {
                ""Football"": {
                    ""strength"": 19,
                    ""location"": ""cde""
                }
            }
        }
    },{
        ""activityName"": ""tournament3"",
        ""schedule"": {
            ""first"": {
                ""Baseball"": {
                    ""strength"": 23,
                    ""location"": ""abc""
                }
            },
            ""second"": {
                ""Cricket"": {
                    ""strength"": 20,
                    ""location"": ""bcd""
                }
            },
            ""third"": {
                ""Football"": {
                    ""strength"": 19,
                    ""location"": ""cde""
                }
            }
        }
    }]
</code></pre>

<p>This is the test that I tried:-</p>

<pre><code>it('should check getData()', () =&gt; {
        fixture = TestBed.createComponent(GameComponent);
        const app = fixture.debugElement.componentInstance;
        const data={
    ""activityName"": ""tournament"",
    ""schedule"": {
        ""first"": {
            ""Baseball"": {
                ""strength"": 23,
                ""location"": ""abc""
            }
        },
        ""second"": {
            ""Cricket"": {
                ""strength"": 20,
                ""location"": ""bcd""
            }
        },
        ""third"": {
            ""Football"": {
                ""strength"": 19,
                ""location"": ""cde""
            }
        }
    }
}

app.getData(data, 'first', 'Baseball');
fixture.detectChanges();
expect(app.location).toContain('abc');
expect(app.location).toContain('bcd');
expect(app.location).toContain('cde');
}
</code></pre>

<p>But I keep on getting this forEach is not a function. Instead of giving static data in the test should I go for some other way?</p>
",https://stackoverflow.com/questions/46429788/typeerror-studentslist-foreach-is-not-a-function-jasmine-unit-testing-angular,"['javascript', 'angularjs', 'angular2-routing', 'karma-jasmine']",13141,TRUE,1,1
TypeError: undefined is not an object when unit testing with jasmine,"<p>I'm trying to write a unit test for a function and I'm getting an error. I'm also unsure how to test other parts of the function correctly.</p>

<pre><code>private dictionaryMap (loggedIn, response) {
    const translations = this.convertToArrays(response.data.translations);

    this.configureMomentLocale(language);

    if (!loggedIn) {
        this.cachePublicDictionary(translations);
    }

    // not testing this part
    this.dictionary = new Dictionary({
        translationMap: Object.assign({}, this.getPublicDictionaryFromCache() || {}, translations),
    });

    return this.rx.Observable.of(this.dictionary);
}
</code></pre>

<p>And my unit test so far looks like this:</p>

<pre><code>describe('dictionaryMap', () =&gt; {

    it('calls configureMomentLocale()', () =&gt; {
        const foo = {
            'foo':'bar',
        };
        spyOn(service, 'configureMomentLocale');
        service.dictionaryMap({}, false);
        expect(service.configureMomentLocale).toHaveBeenCalled();
    });

});
</code></pre>

<p>And when I run this test I get this error:</p>

<blockquote>
  <p>TypeError: undefined is not an object (evaluating 'response.data.translationMap') </p>
</blockquote>

<p>Do I need to mock response.data.translations or assign the json structure? (translationMap: {'email': 'email', 'forgotPassword': 'Forgot password?'})</p>

<p>Also, I'm not sure how to properly test the other parts of the function, like the if statement or returning the observable. I am new to unit testing.</p>
",https://stackoverflow.com/questions/44959901/typeerror-undefined-is-not-an-object-when-unit-testing-with-jasmine,"['javascript', 'unit-testing', 'jasmine']",4773,TRUE,1,1
How to test fragment in Robolectric Unit Testing in android studio,"<p>In my project,first screen is login screen than fragment with recylerview, on clicking recylerview item, fragment get replace and next fragment appears containing recyler view.How to write test cases for unit testing using roboelectric. I am using roboelectric for the first time.Please help me.</p>

<p>Below is my code for loginScreen Test cases class</p>

<pre><code>@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class,packageName = ""com.project.app"")
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class LoginScreenActivityTest {
    LoginScreenActivity activity;
    @Test
    public void a_loginPriceguide() throws Exception {
        activity = Robolectric.setupActivity(LoginScreenActivity.class);
        assertEquals(""abc@gmail.com"",activity.getUsername(0));
        assertEquals(""abc123$"",activity.getPassword(0));
        CheckBox remember_me = (CheckBox) activity.findViewById(R.id.remember_me);
        remember_me.performClick();
        Button btn = (Button)activity.findViewById(R.id.btn_login);
        btn.performClick();
    }

 @Test
    public void b_loginDialog() throws Exception{
        activity = Robolectric.setupActivity(LoginScreenActivity.class);
        try {
            Thread.sleep(10000);
            Intent i = new Intent(activity,MainActivity.class);
            activity.startActivity(i);

        } catch(InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
    }
</code></pre>

<p>This is what i have done for login screen test cases,and this class is working fine.</p>

<p>But fragment with recylerView gives Null Pointer exception</p>

<p>Code for fragment test cases</p>

<pre><code>@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class,packageName = ""com.project.app"")
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ProductTest {
    private Product fragment ;
    private LinearLayoutManager mockLayoutManager;
    ActivityController&lt;FragmentActivity&gt; activityController;
    @Before
    public void setUp() {
        mockLayoutManager = Mockito.mock(LinearLayoutManager.class);
        fragment = new Product();
    }
    @Test
    public void l_clickProduct() throws Exception {
        activityController = Robolectric.buildActivity(FragmentActivity.class);
        activityController.create().start();
        RecyclerView recyclerView = (RecyclerView) fragment.getView().findViewById(R.id.list);
        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        assertThat(layoutManager).isEqualTo(mockLayoutManager);
}
</code></pre>
",https://stackoverflow.com/questions/43407431/how-to-test-fragment-in-robolectric-unit-testing-in-android-studio,"['android', 'unit-testing', 'robolectric']",808,FALSE,1,0
How to do unit testing on timer functions on a microcontroller,"<p>
I am new to the concept of unit testing, and I am currently trying to get more comfortable with it.</p>

<p>I have to do unit testing on a timer driver for a microcontroller written in C. Now, I heard that a unit test on a function should not depend on the outcome of another function. My problem is, how can we test a function that is supposed to stop a timer in these conditions ? Don't we need to start the timer, heck, we even need to initialize it !</p>

<p>I would like to know at which level we need to consider our unit test ; is it at the level of one function (in that case, we get the problem above), or is it at the level of the driver itself (in that case, we can use multiple functions of the driver in one unit test) ?</p>

<p>I would love to hear from more experienced people their feeling about this subject, as I feel I'm going nowhere at the moment.</p>






",https://stackoverflow.com/questions/47696579/how-to-do-unit-testing-on-timer-functions-on-a-microcontroller,"['c', 'unit-testing', 'embedded']",836,TRUE,1,2
How to shadow a header file with CMake for unit-testing,"<p>This is the simplified folder structure I have:</p>

<pre><code>+ production
+-- ClassToTest.cpp (contains '#includes ""DragonHeader.h""')
+-- ClassToTest.h
+-- DragonHeader.h (has a lot of dependencies, ClassToTest only need one simple static function with no dependencies at all.)
+ tests
+-- tst_ClassToTest.cpp
+-- DragonHeader.h (which defines and implements the needed simple function)
</code></pre>

<p>So for the test case I'd like that tests/DragonHeader.h shadows production/DragonHeader.h. => ClassToTest.cpp includes tests/DragonHeader.h. How can that be achieved? (I am working with MSVC 2015 if it is relevant...)</p>

<p>The CMakeLists.txt in the tests folder looks like</p>

<pre><code>project( tst_ClassToTest )
set( ${PROJECT_NAME}_SOURCES tst_ClassToTest.cpp DragonHeader.h ../production/ClassToTest.cpp )
# How to force ClassToTest.cpp to use DragonHeader.h, not production/DragonHeader.h?
add_executable( ${PROJECT_NAME} WIN32 ${${PROJECT_NAME}_SOURCES} )
</code></pre>

<p>Thanks!</p>

<p>Disclaimer: I seek for a solution that does not require me to touch ClassToTest.cpp or to touch the code in production including the related CMakeLists.txt files at all. One solution, however, is to use CMake to copy ClassToTest.cpp/h into the tests folder, but I consider it sub-optimal. </p>
",https://stackoverflow.com/questions/43364475/how-to-shadow-a-header-file-with-cmake-for-unit-testing,"['c++', 'unit-testing', 'cmake']",902,TRUE,1,1
karma unit testing does not works after the void function excuted,"<blockquote>
  <p>unit testing code in spec.ts </p>
</blockquote>

<pre><code>  it('Should test LoadMenus method', () =&gt; {
            let arrays = [{ ""Id"": 1, ""MenuType"": ""A00"", ""MenuName"": ""Search"", ""UserDetail"": { ""UserName"": ""rajendranra"" } 
            alert(11);// executed  
                        this.modalNota.LoadMenus(arrays, 'A00', 'A', '0');
            alert(12);// does not execute
            expect(this.modalNota.cocmenuitems[0].MenuName).toBe('Search');
        });
</code></pre>

<blockquote>
  <p>Component method which am testing </p>
</blockquote>

<pre><code>LoadMenus(lstMenu, menustring, submenustartstring, submenuendstring) {
        alert(menustring);
        this.subitems = [];
        let menu = lstMenu.find(myObj =&gt; myObj.MenuType === menustring);
        if (menu !== null) {
            this.menufilter = lstMenu.filter(myObj =&gt; myObj.MenuType.startsWith(submenustartstring))
                .filter(x =&gt; x.MenuType.endsWith(submenuendstring));
            if (this.menufilter.length &gt; 1) {
                for (let menuType = 0; menuType &lt; this.menufilter.length; menuType++) {
                    if (this.menufilter[menuType].MenuType !== menustring) {
                        this.subitems.push({
                            label: this.menufilter[menuType].MenuName,
                            routerLink: [this.GetLink(this.menufilter[menuType].MenuName)]
                        });
                    }
                }
                alert(menu.MenuName);
                this.cocmenuitems.push({ label: menu.MenuName, routerLink: [this.GetLink(menu.MenuName)], items: this.subitems });
            } else {
                alert(menu.MenuName);
                this.cocmenuitems.push({ label: menu.MenuName, routerLink: [this.GetLink(menu.MenuName)] });
            }
        }
    }
</code></pre>

<p>This unit test showing the result is failed. the main problem is <strong>Alert <code>alert(12);</code> does not fire</strong>. Why my alert(12) does not hit after this <code>this.modalNota.LoadMenus(arrays, 'A00', 'A', '0');</code> component code is executed??</p>

<blockquote>
  <p>Am struggling  a whole day for this. kindly give me the solution. </p>
</blockquote>
",https://stackoverflow.com/questions/43783350/karma-unit-testing-does-not-works-after-the-void-function-excuted,"['unit-testing', 'angular', 'typescript', 'jasmine', 'karma-runner']",78,FALSE,1,0
Unable to reference a target web app project for Unit Testing,"<p>I created a .NET Core web app in VS2015 using the empty web app template. It targets the full framework 4.6.1. It is for a middleware which I am using across a number of other web apps. I followed the instructions <a href=""https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware#writing-middleware"" rel=""nofollow noreferrer"">here</a>, and the middleware works when I integrate it with another web app.</p>

<p>Now I want to write some unit tests for it, so I created a unit test project (using the Test Project template) that is targetting the same framework. Then I referenced the project that has the middleware class I want to unit test. But when I try to use the middleware class in my unit test method, VS would complain and say it could not find it, even if I type with fully qualified namespace. In fact, Intellisense is not bringing up any class in the target project. And if I try to build the unit test project, it would return an error: <code>The type or namespace name 'xxxxMiddleware' could not be found (are you missing a using directive or an assembly reference?)</code>. And when I go into my test unit's <strong>References</strong> and double-click the project that is the target of my unit test, VS pops the message <code>The project cannot be viewed in the object browser because it is unavailable or not yet built. Please ensure that the project is available and built.</code></p>

<p>What am I doing wrong?</p>

<p><strong>UPDATE</strong></p>

<p>If I reference the <code>.exe</code> for my target project, it manages to resolve my middleware class. Very odd! I may have to do that workaround for now until I get a better answer.</p>

<p><strong>UPDATE 2</strong></p>

<p>I spoke too soon. Adding the <code>.exe</code> lets me compile my unit test project. But if I run the test, I get an error saying <code>System.BadImageFormatException: Could not load file or assembly '{assembly for the target of my test}' or one of its dependencies. An attempt was made to load a program with an incorrect format.</code>. What a nightmare.</p>
",https://stackoverflow.com/questions/42051259/unable-to-reference-a-target-web-app-project-for-unit-testing,"['c#', 'asp.net', 'unit-testing', 'visual-studio-2015', 'owin-middleware']",479,FALSE,1,0
Wagtail unit testing: Adding child pages converts them to base type,"<p>Trying to create some unit tests for Wagtail and running into the following problem:</p>

<pre><code>&gt;&gt; root = FrontPage.add_root(instance=FrontPageFactory.build())
&gt;&gt; root
&lt;FrontPage: article0&gt;

&gt;&gt; root.add_child(instance=ArticlePageFactory.build())
&lt;ArticlePage: article1&gt;

&gt;&gt; root.get_tree()
&lt;PageQuerySet [&lt;Page: article0&gt;, &lt;Page: article1&gt;]&gt;
</code></pre>

<p>""article0"" goes from being type ArticlePage to type Page in the page tree.  Is this Page object a reference to the ArticlePage and there's a method I'm not aware of to fetch it, or am I missing something obvious here?</p>

<p>In the meantime I've worked around the problem by just storing the added article pages in a separate list, but I'd really like to understand what's going on here.</p>
",https://stackoverflow.com/questions/46529294/wagtail-unit-testing-adding-child-pages-converts-them-to-base-type,"['django', 'django-testing', 'wagtail']",562,TRUE,1,1
How to write a test for login component for angular2 (unit testing),"<p>This is login.component.ts</p>
<pre><code>    import { Component, OnInit } from '@angular/core';
    import { Router, ActivatedRoute } from '@angular/router';
    import { FormBuilder, FormGroup, Validators } from '@angular/forms';
    import { CommonModule } from  '@angular/common';

    import { LoginUser } from './loginUser.model'
    import { UserService } from './user.service';
    import { LoaderService } from '../shared/loader.service';

    import 'rxjs/add/operator/toPromise';

    @Component({
        templateUrl: './login.component.html'
    })
    export class LoginComponent implements OnInit {
        errorMessage: string;
        loginForm: FormGroup;
        loginObj = new LoginUser();

        constructor(private userService: UserService, private loaderService: LoaderService, private router: Router, fb: FormBuilder) {
            this.loginForm = fb.group({
                userName: [null, Validators.required],
                password: [null, Validators.required]
            })
            console.log(this.loginForm);
        }

    test() : void{
        console.log(&quot;This is a test&quot;);
    }
        login(loginObjValue: any): void {
            if (loginObjValue.userName == null || loginObjValue.password == null) {
                console.log('error');
            } else {
                this.loginObj.userName = loginObjValue.userName;
                this.loginObj.password = loginObjValue.password;
                this.loaderService.displayLoader(true);

                this.userService.login(this.loginObj)
                    .then((res) =&gt; {
                        console.log(&quot;data&quot;, res);
                        console.log(&quot;$localStorage.currentUser&quot;, localStorage);
                        let link = ['customercare/customer-ticket'];
                        this.loaderService.displayLoader(false);

                        this.router.navigate(link);
                    })
                    .catch(error =&gt; this.handleError(error));
            }
        }

        private handleError(error: any): Promise&lt;any&gt; {
            this.loaderService.displayLoader(false);

            if (error._body) {
                this.errorMessage = JSON.parse(error._body).error_description;
            }

            console.log('An error occurred', error);
            return Promise.reject(error.message || error);
        }

        ngOnInit(): void {

        }
    }

   
    @Component({
        templateUrl: './login.component.html'
    })
    export class LoginComponent implements OnInit {
        errorMessage: string;
        loginForm: FormGroup;
        loginObj = new LoginUser();
    
        constructor(private userService: UserService, private loaderService: LoaderService, private router: Router, fb: FormBuilder) {
            this.loginForm = fb.group({
                userName: [null, Validators.required],
                password: [null, Validators.required]
            })
            console.log(this.loginForm);
        }
    
   
        login(loginObjValue: any): void {
            if (loginObjValue.userName == null || loginObjValue.password == null) {
                console.log('error');
            } else {
                this.loginObj.userName = loginObjValue.userName;
                this.loginObj.password = loginObjValue.password;
                this.loaderService.displayLoader(true);
    
                this.userService.login(this.loginObj)
                    .then((res) =&gt; {
                        console.log(&quot;data&quot;, res);
                        console.log(&quot;$localStorage.currentUser&quot;, localStorage);
                        let link = ['customercare/customer-ticket'];
                        this.loaderService.displayLoader(false);
    
                        this.router.navigate(link);
                    })
                    .catch(error =&gt; this.handleError(error));
            }
        }
    }
</code></pre>
<p>Partial code of userservice.ts</p>
<pre><code>@Injectable()
export class UserService {
    private URL = &quot;&quot;;

    constructor(private http: Http) { }

    login(loginObj: LoginUser) {

        let body = 'userName=' + loginObj.userName + '&amp;password=' + loginObj.password + '&amp;grant_type=password';

        let headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');

        return this.http.post(this.URL + '/token', body, { headers: headers })
            .toPromise()
            .then((res: Response) =&gt; {
                let data = res.json();
                if (data &amp;&amp; data.access_token) {
                    localStorage.setItem('currentUser', JSON.stringify(data));
                }
                return data;
            })
    }
}
</code></pre>
<p>So far I have written: I am unable to call login function.</p>
<pre><code>    describe('LoginComponent', () =&gt; {
      let component: LoginComponent;
      let UserService:UserService;
      let fixture: ComponentFixture&lt;LoginComponent&gt;;
      
    beforeEach(async(() =&gt; {
      TestBed.configureTestingModule({
        declarations: [ LoginComponent ],
        providers: [
            { provide: UserService, useValue: UserService },
                   ]
      })
 
      it('should call the login method from the UserService', 
        inject([TestBed, UserService], fakeAsync((tcb: TestBed, mockUserService: UserService) =&gt; {
          spyOn(mockUserService, 'login');
    tcb
            .createComponent(LoginComponent)
            .then((fixture: ComponentFixture&lt;LoginComponent&gt;) =&gt; {
              tick();
               fixture.detectChanges();
              expect(mockUserService.login).toHaveBeenCalled();
            });
        }))
      );
    });
</code></pre>
",https://stackoverflow.com/questions/44006440/how-to-write-a-test-for-login-component-for-angular2-unit-testing,"['angular', 'jasmine', 'karma-jasmine']",7879,FALSE,6,1
What&#39;s the Microsoft unit-testing alternative to the InlineData or TestCase attributes?,"<p>Unit test frameworks other than Microsoft have options to add input parameters and expected results using attributes. </p>

<p>For example, </p>

<p>NUnit has </p>

<pre><code>[TestCase(12,4,3)]
</code></pre>

<p>and xUnit has </p>

<pre><code>[InlineData(5, 1, 3, 9)]
</code></pre>

<p>What's the Microsoft way to accomplish this?</p>
",https://stackoverflow.com/questions/46953568/whats-the-microsoft-unit-testing-alternative-to-the-inlinedata-or-testcase-attr,"['c#', 'unit-testing', 'vs-unit-testing-framework']",2141,TRUE,6,1
How to implement a custom clock in Hazelcast for unit testing?,"<p>When testing some of my code with custom expiry durations, I needed to set the clock time in an Hazelcast instance, very much like how I could set the time using a custom Ticker in Caffeine caches.</p>

<p>I found that this isn't documented anywhere and there isn't any questions on it.</p>
",https://stackoverflow.com/questions/45180454/how-to-implement-a-custom-clock-in-hazelcast-for-unit-testing,"['java', 'testing', 'junit', 'hazelcast', 'caffeine']",187,TRUE,1,1
unit testing a method that takes a list as an argument,"<p>I need to test a method that is taking a list as an argument. Below is the sample code:</p>

<pre><code>public class C
{
    private int x;
    private String y;
    //getters and setters
}
public class B
{
    public void collectC(List&lt;C&gt; cList)
    {
        for(C c : cList)
        {
            System.out.println(""int: "" + c.getX() + ""String: ""+ c.getY());
        }
    }
}
</code></pre>

<p>So class B is simply collecting objects of class C and iteration on it using enhanced for loop.
Now, I want to test a method of class B. Below is the testing code.</p>

<pre><code>public class BTest
{
    private List&lt;C&gt; cList;
    @Mock private C c;
    @InjectMocks private B b;

    @Before
    public void setUp()
    {
        cList = new ArrayList&lt;&gt;();
        cList.add(c);
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testCollectC()
    {
        Mockito.when(c.getX()).thenReturn(5);
        Mockito.when(c.getY()).thenReturn(""Hello There"");
        b.collectC(cList);
    }
}
</code></pre>

<p>So, this is giving me error <code>NullPointerException</code> on <code>System.out.println()</code> one line where I am invoking methods on 'c' object.
I then changed the code where I mocked a list and iterator too, so now my code is working fine. But I want to know that what is the problem with above-mentioned code and why it is failing? </p>
",https://stackoverflow.com/questions/46053990/unit-testing-a-method-that-takes-a-list-as-an-argument,"['java', 'unit-testing', 'arraylist', 'mockito']",2082,TRUE,1,1
C# Unit Testing with Rhino Mocks unable to find assembly Rhino.Mocks,"<p>When I execute my unit test cases with NUnit + Rhino Mocks, I get the following error. </p>

<pre><code>System.TypeInitializationException : The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception.
  ----&gt; System.Runtime.Serialization.SerializationException : Unable to find assembly 'Rhino.Mocks, Version=3.6.0.0, Culture=neutral, PublicKeyToken=0b3305902db7183f'.
   at System.Data.Entity.Internal.AppConfig.get_DefaultInstance()
   at System.Data.Entity.Internal.LazyInternalConnection..ctor(DbContext context, String nameOrConnectionString)
   at System.Data.Entity.DbContext..ctor(String nameOrConnectionString)
   at SHS.SMI.CustomerSettingsService.DatabaseContext..ctor()

Server stack trace: 
   at System.Runtime.Serialization.Formatters.Binary.BinaryAssemblyInfo.GetAssembly()
   at System.Runtime.Serialization.Formatters.Binary.ObjectReader.GetType(BinaryAssemblyInfo assemblyInfo, String name)
   at System.Runtime.Serialization.Formatters.Binary.ObjectMap..ctor(String objectName, String[] memberNames, BinaryTypeEnum[] binaryTypeEnumA, Object[] typeInformationA, Int32[] memberAssemIds, ObjectReader objectReader, Int32 objectId, BinaryAssemblyInfo assemblyInfo, SizedArray assemIdToAssemblyTable)
   at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.ReadObjectWithMapTyped(BinaryObjectWithMapTyped record)
   at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.ReadObjectWithMapTyped(BinaryHeaderEnum binaryHeaderEnum)
   at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.Run()
   at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
   at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
   at System.Runtime.Remoting.Channels.CrossAppDomainSerializer.DeserializeObject(MemoryStream stm)
   at System.Runtime.Remoting.Messaging.SmuggledMethodCallMessage.FixupForNewAppDomain()
   at System.Runtime.Remoting.Channels.CrossAppDomainSink.DoDispatch(Byte[] reqStmBuff, SmuggledMethodCallMessage smuggledMcm, SmuggledMethodReturnMessage&amp; smuggledMrm)
   at System.Runtime.Remoting.Channels.CrossAppDomainSink.DoTransitionDispatchCallback(Object[] args)

Exception rethrown at [0]: 
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&amp; msgData, Int32 type)
   at System.AppDomain.get_Evidence()
   at System.AppDomain.get_EvidenceNoDemand()
   at System.AppDomain.get_Evidence()
   at System.Configuration.ClientConfigPaths.GetEvidenceInfo(AppDomain appDomain, String exePath, String&amp; typeName)
   at System.Configuration.ClientConfigPaths.GetTypeAndHashSuffix(AppDomain appDomain, String exePath)
   at System.Configuration.ClientConfigPaths..ctor(String exePath, Boolean includeUserConfig)
   at System.Configuration.ClientConfigPaths.GetPaths(String exePath, Boolean includeUserConfig)
   at System.Configuration.ClientConfigurationHost.RequireCompleteInit(IInternalConfigRecord record)
   at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object&amp; result, Object&amp; resultRuntimeObject)
   at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
   at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
   at System.Configuration.ConfigurationManager.GetSection(String sectionName)
   at System.Data.Entity.Internal.AppConfig..ctor()
   at System.Data.Entity.Internal.AppConfig..cctor()
</code></pre>

<p>I have included the following in my AssemblyInfo.cs (Assembly file under test)</p>

<pre><code>[assembly: InternalsVisibleTo(""Rhino.Mocks"")]
[assembly: InternalsVisibleTo(""DynamicProxyGenAssembly2"")]
</code></pre>

<p>Note: If I add Rhino.Mocks to the Global Assembly Cache, it works fine! </p>

<p>Any help is really appreciated!</p>

<p>Let me know if you need any other information</p>
",https://stackoverflow.com/questions/43040936/c-unit-testing-with-rhino-mocks-unable-to-find-assembly-rhino-mocks,"['c#', '.net', 'unit-testing', 'nunit', 'rhino-mocks']",394,FALSE,1,0
SSDT and Unit Testing Stored Procedure That Accesses a Linked Server,"<p>I am learning how to test T-SQL code written on SQL Server 2014 Standard using SSDT. I've used the following walkthrough to get started:</p>

<p><a href=""https://msdn.microsoft.com/en-us/library/jj851212(v=vs.103).aspx#Create%20a%20Database%20Project%20and%20Import%20a%20Schema"" rel=""nofollow noreferrer"">https://msdn.microsoft.com/en-us/library/jj851212(v=vs.103).aspx#Create%20a%20Database%20Project%20and%20Import%20a%20Schema</a></p>

<p>I have several scenarios with stored procedures accessing linked servers.</p>

<ol>
<li>Read local table and write to linked server.</li>
<li>Read linked server and write to local table.</li>
<li>Read data from local table, write to another local table, write same data to linked server (similar to scenario #1).</li>
</ol>

<p>The linked servers I'm using have a test and production environment only which poses several questions:</p>

<p><strike>What would be the correct way(s) to write tests over these stored procedures? </strike> Edit: removed for being too broad.</p>

<p>Should the tests interact with the linked servers or could there be mock connections somehow (similar to WebMock in Ruby)?</p>

<p>What would be the ideal way to setup data for a stored procedure that would normally read data from a linked server?</p>

<p>EDIT: I should mention that the linked servers are not SQL Server instances.</p>
",https://stackoverflow.com/questions/47995134/ssdt-and-unit-testing-stored-procedure-that-accesses-a-linked-server,"['sql-server', 'visual-studio', 'unit-testing', 'tsql', 'stored-procedures']",400,TRUE,0,1
unit-testing for values set async in ngOnInit() function of an angular component,"<p>I'm trying to unit-test an array that is set from an async service in the ngOnInit() function of my component.</p>

<pre class=""lang-js prettyprint-override""><code>export class DashboardComponent implements OnInit {
  todos: Todo[] = [];

  constructor(public todoService: TodoService) {}

  ngOnInit(): void {
    this.todoService.getTodos()
      .then(todos =&gt; this.todos = todos.slice(1, 5));
  }
}
</code></pre>

<p>When I try to test this with a function like that:</p>

<pre class=""lang-js prettyprint-override""><code>  it('should load four todos for dashboard', function(done) {
    expect(component.todos.length).toEqual(4);
  });
</code></pre>

<p>I get an error that 0 is not equal to 4, as the promise is not resolved yet. The only way I could get this to work is by making the service public and running ""dirty"" code like that:</p>

<pre class=""lang-js prettyprint-override""><code>  it('should load four todos for dashboard', function(done) {
    var todos = component.todoService.getTodos();
    todos.then(x =&gt; {
      expect(x.length).toEqual(6);
      expect(component.todos.length).toEqual(4)
    });
    done();
  });
</code></pre>

<p>But there sure is a better and cleaner way to do this, so any suggestings for improvements are welcome!</p>

<p><strong>Edit 1:</strong> After the hint of dbandstra, which points in the right direction, I came up with this code:</p>

<pre class=""lang-js prettyprint-override""><code>describe('DashboardComponent', () =&gt; {
  beforeEach( async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [
        DashboardComponent, EmptyComponent,
        RouterLinkStubDirective, RouterOutletStubComponent
      ],
      providers: [{provide: TodoService, useClass: FakeTodoService}]
    })
      .overrideComponent(TodoSearchComponent, EmptyComponent)
      .compileComponents()
      .then(() =&gt; {
        fixture = TestBed.createComponent(DashboardComponent);
        comp    = fixture.componentInstance;
      });
  }));

  beforeEach(() =&gt; {
    // TodoService actually injected into the component
    let todoService = fixture.debugElement.injector.get(TodoService);

    let spy = spyOn(todoService, 'getTodos')
      .and.returnValue(Promise.resolve(todos));

    // trigger initial data binding
    fixture.detectChanges();
  });

  it('should load four todos for dashboard', () =&gt; {
    fixture.whenStable().then(() =&gt; { // wait for async getTodos
      fixture.detectChanges();        // update view with todos
      expect(comp.todos.length).toEqual(4);
    });
  })
});
</code></pre>

<p>This works like a charm, thanks!</p>

<p><strong>Edit 2:</strong> I also got it to work with the suggested solution from <a href=""https://stackoverflow.com/a/39445420/3368833"">https://stackoverflow.com/a/39445420/3368833</a> by making the fake service synchronous like this:</p>

<pre class=""lang-js prettyprint-override""><code>class TodoServiceMock{
  private data: Todo[];

  getTodos() {
    let todos = [ ...insert fake data here... ];
    this.data = todos;
    return this;
  }

  then(callback) {
    callback(this.data);
  }
}
</code></pre>
",https://stackoverflow.com/questions/44294960/unit-testing-for-values-set-async-in-ngoninit-function-of-an-angular-component,"['angular', 'unit-testing', 'typescript']",5811,FALSE,12,0
Unit testing and mocking a legacy wrapper that calls another service,"<p>I will gladly remove this question should duplicates be provided. Lack of knowledge in this area makes finding solutions a little more difficult.</p>

<hr>

<p>We're beginning to implement unit &amp; integration testing throughout the organisation; starting with new projects. </p>

<p>Testing code we fully own seems pretty straight forward and there are many resources we can utilize. </p>

<p>Testing code that calls out to a third-party service on the other hand is a little more difficult. I understand that mocking is what we should be looking to do, though am a little hard pressed to figure out the actual implementation for a particular piece of code. </p>

<p>In this particular case we have a new library that will be sitting between business layers &amp; a third-party exception logger (Sentry) - so it's a legacy wrapper.</p>

<p>By way of an example, the following code is a slimmed down extract.</p>

<p><strong>Interface</strong></p>

<pre><code>public interface IExceptionLogging
{
    void Capture(string endpointKey, string message, params KeyValuePair&lt;string, string&gt;[] tag);
    void Capture(string endpointKey, Exception exception, params KeyValuePair&lt;string, string&gt;[] tag);
}
</code></pre>

<p><strong>Abstract, helps to enforce constructor</strong></p>

<pre><code>public abstract class ExceptionLogging : IExceptionLogging
    {
        internal Dictionary&lt;string, Uri&gt; LoggerEndpoints;

        protected ExceptionLogging(Dictionary&lt;string, Uri&gt; loggerEndpoints)
        {
            LoggerEndpoints = loggerEndpoints;
        }

        public abstract void Capture(string endpointKey, string message, params KeyValuePair&lt;string, string&gt;[] tag);
        public abstract void Capture(string endpointKey, Exception exception, params KeyValuePair&lt;string, string&gt;[] tag);

    }
</code></pre>

<p><strong>An implementation</strong></p>

<pre><code>public class GetSentry : ExceptionLogging
{
    private Dictionary&lt;string, RavenClient&gt; _clients = new Dictionary&lt;string, RavenClient&gt;();

    public GetSentry(Dictionary&lt;string, Uri&gt; loggerEndpoints)
        : base(loggerEndpoints)
    {
        LoggerEndpoints.ToList().ForEach(ep =&gt;
        {
            _clients.Add(ep.Key, new RavenClient(ep.Value.ToString()));
        });
    }

    public override void Capture(string endpointKey, Exception ex, params KeyValuePair&lt;string, string&gt;[] tag)
    {
        RavenClient client = _clients[endpointKey];
        if (client != null)
        {
            SentryEvent se = new SentryEvent(ex);
            tag.ToList().ForEach(t =&gt; se.Tags.Add(t));
            client.Capture(se);

        }
    }    

    public override void Capture(string endpointKey, string message, params KeyValuePair&lt;string, string&gt;[] tag)
    {
        RavenClient client = _clients[endpointKey];
        if (client != null)
        {
            SentryEvent se = new SentryEvent(message);
            tag.ToList().ForEach(t =&gt; se.Tags.Add(t));
            client.Capture(se);
        }
    }
</code></pre>

<p>What would be the approach to test something like this?</p>

<p>As mentioned, I will happily remove this Q if there are valid duplicates. I am just unsure where to start.</p>
",https://stackoverflow.com/questions/43981975/unit-testing-and-mocking-a-legacy-wrapper-that-calls-another-service,"['c#', 'unit-testing', 'mocking']",147,FALSE,0,0
Jest: How to utilize its features in unit testing an application,"<p>I am new to jest and unit-testing as well, and I'm wondering what type of scenarios can be covered using Jest. </p>

<p>I have some specific questions before I get started:</p>

<ul>
<li>What should be covered in unit-testing the react application?</li>
<li>Do I need any other library with Jest for assertions, mocking etc? I read about Chai, sinon etc. Not aware why they are used and if they are needed with Jest.</li>
<li>What exactly is Enzyme used for? Is it a must-use with Jest?</li>
<li>Do I need any task-runner with Jest like Karma? Or does Jest have one built-in? How do I set it up.</li>
</ul>
",https://stackoverflow.com/questions/45587085/jest-how-to-utilize-its-features-in-unit-testing-an-application,"['reactjs', 'unit-testing', 'karma-runner', 'enzyme', 'jestjs']",55,TRUE,0,1
React unit testing with Ava: Why is the function already wrapped?,"<p>Even though I am using the afterEach I still get the following error:Attempted to wrap setTimeout which is already wrapped.What am I doing wrong?I am using ava to do this unit test. The test I am trying to create is very simple. It is pretty much check the render and  a click action. There is also a test to check if the setTimeOut function has been called with the right arguments.</p>

<pre><code>import test from 'ava';
import React from 'react';
import { CartMessage } from 'components/Cart/CartMessage';
import { shallow, mount } from 'enzyme';
import { spy, stub } from 'sinon';

let props;
let popError;
let cartmessage;
let timeoutSpy;


test.beforeEach(() =&gt; {
  props = {
    message: 'testing',
    count: 2,
    popError: stub().returns(Promise.resolve()),
  };
  cartmessage = shallow(&lt;CartMessage {...props}/&gt;)

  timeoutSpy = spy(window, 'setTimeout');
});

test.afterEach(()=&gt;{
  timeoutSpy.restore()
})

test('renders okay?', (t) =&gt; {
  t.truthy(Cartmessage)
});

test('componentDidMount calls setTimeout with proper args', t =&gt; {
  t.true(timeoutSpy.calledWithExactly(() =&gt; this.setState({ MessageOpen: true }), 1))
})

test('onClose called?', t =&gt; {
  const wrapper = shallow(&lt;CartMessage {...props}  /&gt;);
  wrapper.find('i').simulate('click');
  t.true(timeoutSpy.calledWithExactly(this.props.popError, 1))
})

test('timeout i called with the right args', (t) =&gt; {
  t.true(timeoutSpy.calledWithExactly(this.props.popError, 1));
})
</code></pre>
",https://stackoverflow.com/questions/41798862/react-unit-testing-with-ava-why-is-the-function-already-wrapped,"['javascript', 'reactjs', 'testing', 'ava']",444,TRUE,0,1
Patterns for unit testing a Flask app that depends on timestamps?,"<p>I have a Flask app that's part of a task scheduling system. The business logic in many of the routes relies on the current time.</p>

<pre><code>@app.route(""/do_stuff"")
def do_stuff():
  now = datetime.datetime.now()
  call_func(request.args.get(""some_arg""), now)
</code></pre>

<p>I need to bring these functions under test. The tests will need to spoof timestamps, so that I can verify that the app responds properly depending on when various commands arrive.</p>

<p>Are there standard patterns for writing these kinds of tests in Flask? I can think of a bunch of clunky, non-DRY ways to do it. Wondering if there are any more elegant patterns/tools...?</p>
",https://stackoverflow.com/questions/42464808/patterns-for-unit-testing-a-flask-app-that-depends-on-timestamps,"['python', 'unit-testing', 'flask']",270,TRUE,0,2
How to properly abstract system objects when unit testing in C#?,"<p>Even though I've understood the principle of mocks, stubs and class abstraction for a testable design, there's something that's still very unclear to me.  </p>

<p>Working with .NET, there are a lot of built-in classes, such as StackTrace for example, located under the Diagnostics namespace.<br>
Some of those classes contain collections of other classes, and those classes contain other classes as well, etc. etc. etc... - The containment principle.<br>
For example: The <code>StackTrace</code> class contains an array of <code>StackFrame</code> objects, which itself has a method returning a <code>MethodBase</code> object.  </p>

<p>Say none of those classes are abstract, meaning they can't be mocked directly - How could one design the code to be able to mock those classes, <strong>without creating tons of wrapping classes and wasting a lot of crutial time on it</strong>?  </p>

<p>I hope I'm clear enough on that one.</p>
",https://stackoverflow.com/questions/42115236/how-to-properly-abstract-system-objects-when-unit-testing-in-c,"['c#', '.net', 'unit-testing', 'nunit', 'moq']",65,FALSE,-2,1
"Simple Calculator, Unit testing using KOTLIN with Spek (Exit code -1)","<p>I am very new to android developing and recently did my first project. It is only a basic calculator with addition, subtraction, multiplication and division.</p>

<p>I am now trying to do unit testing to test the functions of my calculator but i am receiving this output(shown below). I have no idea what is causing this to happen. Please help</p>

<p>Output:
<a href=""https://i.stack.imgur.com/ba7iB.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ba7iB.png"" alt=""enter image description here""></a></p>

<p>FunctionsTest.kt:</p>

<pre><code>@RunWith(JUnitPlatform::class)
class FunctionsTest : Spek({

    given(""a calculator"") {

        on(""adding the first number to the second number"") {
            val sum = Functions.addFunction(2.0, 3.0)
            it(""should return the result of adding the first number to the second number"") {
                assertEquals(5, sum)
            }
        }

        on(""subtracting the second number from the first number"") {
            val sub = Functions.minusFunction(5.0,2.0)
            it(""should return the value of subtracting the second number from the first number"") {
                assertEquals(3, sub)
            }
        }

        on(""Multiplying the first number and the second number"") {
            val mul = Functions.multiFunction(5.0,2.0)
            it(""should return the value of multiplying the first and second number"") {
                assertEquals(10, mul)
            }
        }

        on(""Dividing the second number from the first number"") {
            val div = Functions.divFunction(9.0,3.0)
            it(""should return the value of dividing the second number from the first number"") {
                assertEquals(3, div)
            }
        }
    }

})
</code></pre>

<p>Gradle Build:</p>

<pre><code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'

android {
compileSdkVersion 25
buildToolsVersion ""25.0.3""
defaultConfig {
    applicationId ""com.example.zhiwen.calculator""
    minSdkVersion 21
    targetSdkVersion 25
    versionCode 1
    versionName ""1.0""
    testInstrumentationRunner 
""android.support.test.runner.AndroidJUnitRunner""
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
compile ""org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version""

compile ""org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version""

androidTestCompile 'com.android.support:support-annotations:25.3.1'
androidTestCompile 'com.android.support.test:runner:0.5'

testCompile""org.jetbrains.spek:spek-api:1.1.2""
testCompile""org.jetbrains.spek:spek-junit-platform-engine:1.1.2""
testCompile""org.junit.platform:junit-platform-runner:1.0.0-M4""




configurations.all {
    resolutionStrategy.force ""org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version""
}

dependencies {
    testCompile ""com.nhaarman:mockito-kotlin:1.3.0""
}



}
repositories {
maven { url ""http://dl.bintray.com/jetbrains/spek"" }
mavenCentral()
}
</code></pre>
",https://stackoverflow.com/questions/44252286/simple-calculator-unit-testing-using-kotlin-with-spek-exit-code-1,"['android', 'unit-testing', 'kotlin']",645,FALSE,0,0
&#39;Module is not available&#39; when unit testing a component using typescript,"<p>Any ideas why the module is not found during the tests?</p>

<p>In <code>karma.conf.js</code> I've specified all the dependencies under the <code>files</code> property i.e <code>angular</code>, <code>angular-mocks</code></p>

<p>But I have a feeling that <code>app.component.ts</code> and <code>main.ts</code> are not being compiled hence why they're not being found?</p>

<p><code>karma.conf.js</code></p>

<pre><code>var webpackConfig = require('./webpack.test.config');

module.exports = function(config) {
  'use strict';
  var _config = {
    basePath: '',
    frameworks: ['jasmine', 'karma-typescript'],
    files: [
      'node_modules/angular/angular.js',
      'node_modules/angular-mocks/angular-mocks.js',
      'src/app/app.component.ts',
      'src/main.ts',
      {
        pattern: 'src/app/**/*.+(ts|html)'
      }
    ],
    preprocessors: {
      '**/*.ts': ['karma-typescript']
    },
    webpack: webpackConfig,
    karmaTypescriptConfig: {
      bundlerOptions: {
        entrypoints: /\.spec\.ts$/
      },
      compilerOptions: {
        lib: ['ES2015', 'DOM']
      }
    },
    reporters: ['progress', 'karma-typescript'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: false,
    browsers: ['Chrome'],
    singleRun: true
  };

  config.set(_config);
};
</code></pre>

<p><code>webpack.test.config.js</code></p>

<pre><code>var webpack = require('webpack');
var path = require('path');

module.exports = {
  devtool: 'inline-source-map',

  resolve: {
    extensions: ['.ts', '.js']
  },

  module: {
    rules: [{
        test: /\.ts$/,
        loaders: [{
          loader: 'awesome-typescript-loader',
          options: {
            configFileName: path.join(__dirname, 'src', 'tsconfig.json')
          }
        }]
      },
      {
        test: /\.html$/,
        loader: 'html-loader'
      }
    ]
  }
};
</code></pre>

<p><code>app.component.spec.ts</code></p>

<pre><code>import { AppComponent } from './app.component';

describe('Component: AppComponent', () =&gt; {
  let Users;
  beforeEach(function() {
    angular.mock.module('myapp');
  });
  beforeEach(inject(function(_Users_: any) {
    console.log(_Users_);
  }));
});
</code></pre>

<p><code>app.component.ts</code></p>

<pre><code>export class AppComponent implements ng.IComponentOptions {
  static registeredName = 'dummy';

  template: any;

  constructor() {
    this.template = require('./app.component.html');
  }
}
</code></pre>

<p><code>main.ts</code></p>

<pre><code>import { AppComponent } from ""./app/app.component"";

angular.module(""myapp"", ['pascalprecht.translate'])
  .component(AppComponent.registeredName, new AppComponent())
  .config([""$translateProvider"", function($translateProvider: any) {
    $translateProvider.determinePreferredLanguage();
  }]);
</code></pre>
",https://stackoverflow.com/questions/44698119/module-is-not-available-when-unit-testing-a-component-using-typescript,"['angularjs', 'unit-testing', 'typescript', 'karma-runner']",451,FALSE,0,0
Unit testing service in EmberJS: How to prevent interaction between tests?,"<p>I'm seeing a strange interaction when writing unit tests for services in ember.js. It only occurs on arrays.</p>

<p>I'm having a service which has an array as property. The state of array is shared between different tests. I don't see this behavior if property has a simple type (e.g. number). Do you have any hint what's going on?</p>

<p>Here is a ember-twiddle demonstrating the issue: <a href=""https://ember-twiddle.com/068e0c0fd7240e54c98972002fc2e34f?openFiles=tests.unit.services.my-service-test.js%2C"" rel=""nofollow noreferrer"">https://ember-twiddle.com/068e0c0fd7240e54c98972002fc2e34f?openFiles=tests.unit.services.my-service-test.js%2C</a></p>

<p>Update: I noticed it works fine if I'm initialize the array in <code>init()</code> but not if I declare it as property of service object. Are complex types like array and object sharing states between different instances?</p>

<p>So this won't work:</p>

<pre><code>import Ember from 'ember';
export default Ember.Service.extend({
  array: [],
});
</code></pre>

<p>Will this is working as expected:</p>

<pre><code>import Ember from 'ember';
export default Ember.Service.extend({
  array: undefined,
  init() {
    this.set('array', []);
  }
});
</code></pre>
",https://stackoverflow.com/questions/41936055/unit-testing-service-in-emberjs-how-to-prevent-interaction-between-tests,"['unit-testing', 'ember.js']",62,TRUE,0,1
Unit Testing &#39;Employee&#39; is a namespace but used like a type,"<p>In Visual Studio 2017, I've Project files structured in this way.</p>

<p><strong>[Source Code]</strong></p>

<pre><code>Project
    Employee (namespace)
         Employee  (.cs file)

Tests (Unit Test within the same solution referencing Project)
     Employee (namespace)
          EmployeeTest (.cs unit test)
</code></pre>

<p><strong>Tests/Employee/EmployeeTest.cs</strong></p>

<pre><code>namespace Tests.Employee
{
    [TestClass]
    public class EmployeeTest
    {
        [TestMethod]
        public void TestConstructor()
        {
            Employee employee = new Employee(); // error

        }
    }
}
</code></pre>

<p><strong>Error:</strong> </p>

<pre><code>'Employee' is a namespace but used like a type
</code></pre>

<p><strong>Question:</strong></p>

<p>Besides fixing the error, what's the recommended way to structure my files so I don't run into names conflict, There's a requirement that I've to keep the namespace name same as class name and also match the folder structures, can't avoid that.</p>

<p><strong>Note:</strong> </p>

<p>I'm a newbie to .net development</p>
",https://stackoverflow.com/questions/41773916/unit-testing-employee-is-a-namespace-but-used-like-a-type,"['c#', '.net', 'unit-testing']",1177,TRUE,0,2
Unit Testing - how do I stub boolean value from protected method?,"<p>So here is the scenario</p>

<pre><code>public class Report {

    public void Generate {
       if (!isValidDate) {
       return;
       }

       //calling other method
    }

    protected boolean isValidDate() {
       boolean isValid = true;
       //some logic here to change to false
       return isValid;
    }
}
</code></pre>

<p>And in my test, I have this as I want to set the boolean value to be true. </p>

<pre><code>@InjectMocks
Report report;

@Before
public void setUp() throws Exception {
    Whitebox.setInternalState(report, ""isValidParameters"", true);
}

@Test
public void testReport() throws Exception {
    //test logic to be added here
}
</code></pre>

<p>Then I got the RuntimeException: Unable to set internal state on a private field.  Can someone please help on how I can set the boolean value of that protected method for my test here?  TIA</p>
",https://stackoverflow.com/questions/46498140/unit-testing-how-do-i-stub-boolean-value-from-protected-method,"['unit-testing', 'junit', 'mockito', 'powermockito']",1746,FALSE,-2,1
How to convert a Laravel-5.4 function as unit testing code,"<p>How can I convert this Laravel-5.4 function as unit testing code:</p>

<pre><code>public function addQtCart($id)
{
    $item = Cart::get($id);

    $products = MarketProduct::find($item-&gt;id);

    $available_quantity = $products-&gt;product-&gt;available_quantity;

    // Checking cart quantity with available item quantity in DB
    if($item-&gt;qty &lt; $available_quantity){
      Cart::update($id, $item-&gt;qty + 1);
      Session::flash('alert-success', 'Quantity added to the cart!');
      return redirect()-&gt;back();
    }
    else{
        Session::flash('alert-danger', 'Product quantity is not available!');
        return redirect()-&gt;back();
    }

}
</code></pre>

<p>Please do not mention the documentation link, its bit complicated for me to understand the <strong>""foo"" and ""bar""</strong> examples as I am new in testing section.</p>

<p>N.B. Cart:: is a LaravelShoppingcart package.</p>
",https://stackoverflow.com/questions/47107826/how-to-convert-a-laravel-5-4-function-as-unit-testing-code,"['php', 'laravel', 'unit-testing', 'laravel-5.4']",51,FALSE,0,0
More elegant way to disable my LOG messages when unit testing?,"<p>Right now, in visual studio 2017, I'm trying to unit test my code using google's testing framework gtest. I'm coding in C++. The problem I'm having is I want to be able to disable my LOG and assert macros for my debug build when unit testing by I'm not sure how to do this properly. This is currently how I have my macros setup:</p>

<pre><code>#if (DEBUG)

#define RUNTIME_ASSERT \
    BOOST_ASSERT_MSG 

#define COMPILETIME_ASSERT(expr, msg) \
    static_assert(expr, msg) 

#define LOG(...) \
    do { fprintf_s(stderr, __VA_ARGS__); } while (0)

#else
#define NDEBUG
#define RUNTIME_ASSERT 
#define COMPILETIME_ASSERT(expr, msg)
#define LOG(...) ((void)0)
#endif
</code></pre>

<p>My solution consists of two projects, my actual application (a video game project) and a unit test project which takes my game project as a lib to run the tests.</p>

<p>I've tried creating another build configuration like ""Debug unit test"" though I couldn't quite get things to work and it seems like a sloppy way of doing things as then I would have to keep maintaining changes to both debug and debug unit testing build configurations. Any other suggestions?</p>
",https://stackoverflow.com/questions/44432256/more-elegant-way-to-disable-my-log-messages-when-unit-testing,"['c++', 'unit-testing', 'testing']",156,FALSE,0,1
Angular2 / Jasmine: Spy on unit testing methods doesn&#39;t see called method,"<p>I've got a problem with detecting spy have called an function. It's a unit test of service.
I've tried two different approaches with TestBed.get on method (in ' it should check only status') and spy on injected dummy class  (""in it should login unknown to facebook""), but neither of them doesnt seem to work
I've done some print to see if method is used, and there are shown.
Here's a spec file:</p>

<pre><code>import { TestBed, inject, async } from '@angular/core/testing';

import {FacebookServiceMock } from './../test-helpers/facebook-service-mock';
import { SocialsServiceDummy } from './../test-helpers/socialsServiceDummy';
import { ErrorDouble } from './../test-helpers/errorDouble';

import { ErrorsService } from './../../app/services/errors.service';
import { social_config, SocialConfig, SOCIAL_CONFIG } from './../../app/socials/social-config';
import { SocialsService } from './../../app/services/socials.service';
import { FacebookLoginService } from './../../app/services/facebook-login.service';
import { FacebookService } from 'ngx-facebook';

describe('Facebook-login-service test', () =&gt; {
    let socialsServiceSpy: any;

    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            providers: [
                FacebookLoginService,
                { provide: FacebookService, useFactory: () =&gt; { return new FacebookServiceMock() }},
                { provide: SocialsService, useFactory: () =&gt; {  return new SocialsServiceDummy() }},
                { provide: ErrorsService, useFactory: () =&gt; { return new ErrorDouble() } },
                { provide: social_config, useValue: SOCIAL_CONFIG }
            ]
        });


    });

    beforeEach(() =&gt; {
        socialsServiceSpy = TestBed.get(SocialsService);
        spyOn(socialsServiceSpy, 'updateAccount');

    });

    afterEach(()=&gt;{
        TestBed.resetTestingModule();

    });

    it('should login unknown to facebook',
        async(inject([FacebookLoginService, FacebookService, SocialsService, ErrorsService, social_config], (facebookLoginService, FacebookServiceMock, SocialsServiceDummy, ErrorDouble, SOCIAL_CONFIG) =&gt; {
                let mockReturn = {
                    status: ""unknown"",
                    authResponse: {
                        userID: '123456',
                        accessToken: 'token',
                        expiresIn: 3600
                    }
                };

                spyOn(FacebookServiceMock, 'getLoginStatus').and.returnValue(Promise.resolve(mockReturn));
                spyOn(SocialsServiceDummy, 'addNewSocialAccount').and.callThrough();
                spyOn(facebookLoginService, 'loginToFacebook').and.callThrough();

                facebookLoginService.checkLoginStatus();
                expect(facebookLoginService.loginToFacebook).toHaveBeenCalled();
                expect(SocialsServiceDummy.addNewSocialAccount).toHaveBeenCalledWith('facebook', mockReturn.authResponse.userID, mockReturn.authResponse.accessToken, mockReturn.authResponse.expiresIn);
            })
        ));

    it('should check only status',
        async(inject([FacebookLoginService, FacebookService, SocialsService, ErrorsService, social_config], (facebookLoginService, FacebookServiceMock, SocialsServiceDummy, ErrorDouble, SOCIAL_CONFIG) =&gt; {
                let mockReturn = {
                    status: ""connected"",
                    authResponse: {
                        userID: '123456',
                        accessToken: 'token',
                        expiresIn: 3600
                    }
                };
                spyOn(FacebookServiceMock, 'getLoginStatus').and.returnValue(Promise.resolve(mockReturn));
               // spyOn(SocialsServiceDummy, 'updateAccount').and.callThrough();

                facebookLoginService.checkLoginStatus();
                expect(socialsServiceSpy.updateAccount).toHaveBeenCalledWith('facebook', mockReturn.authResponse.userID, mockReturn.authResponse.accessToken, mockReturn.authResponse.expiresIn);


            })
        ));
});
</code></pre>

<p>The FacebookLoginService looks like this:</p>

<pre><code>/**
 * Created by Daniel on 2017-06-19.
 */
import { Injectable, Inject } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { FacebookService, LoginResponse, LoginOptions } from 'ngx-facebook';
import { ErrorsService } from './errors.service';
import { social_config, SocialConfig } from './../socials/social-config';
import { NewSocialAccount } from './../shared/models/new-social-account';
import { SocialsService } from ""./socials.service"";

@Injectable()

export class FacebookLoginService {
    private loginOptions : LoginOptions = {
        scope: this.socialConfig.facebook.scope
    }

    private attemptToLogin =  new Subject&lt;boolean&gt;()
    private newSocialAccount =  new Subject&lt;any&gt;();

    login$ = this.attemptToLogin.asObservable();
    newSocial$ = this.newSocialAccount.asObservable();

    constructor(
        private facebookService: FacebookService,
        private socialsService: SocialsService,
        private errorsService: ErrorsService,
        @Inject(social_config) private socialConfig: SocialConfig
    ) {}

    initSocials() : void {
        this.facebookService.init({appId: this.socialConfig.facebook.appId, version: this.socialConfig.facebook.version});
    }

    checkLoginStatus() : void{
        this.facebookService.getLoginStatus().then(
            (res) =&gt; {
                if(res.status == ""connected"") {
                    const updatedAccount = this.createNewAccountObject('facebook', res.authResponse.userID, res.authResponse.accessToken, res.authResponse.expiresIn);
                    this.socialsService.updateAccount(updatedAccount).then(
                        () =&gt; {
                            this.attemptToLogin.next(true);
                        },
                        error =&gt; {
                            this.errorsService.startErrorAction(error);
                        }
                    )
                } else {
                   this.loginToFacebook();
                }
            },
            error =&gt; {
                alert('Unable to connect with Facebook. Please try later');
            }
        )
    }

    loginToFacebook() : void {
        this.facebookService.login(this.loginOptions).then(
            (res: LoginResponse) =&gt; {
                const newAccount = this.createNewAccountObject('facebook', res.authResponse.userID, res.authResponse.accessToken, res.authResponse.expiresIn);
                this.socialsService.addNewSocialAccount(newAccount).then(
                    (res) =&gt; {
                        this.confirmLoginNewSocialAccount(res, 'facebook');
                    },
                    error =&gt; {
                        this.errorsService.startErrorAction(error);
                    }
                )
            },
            error =&gt; {
                alert('Unable to connect with Facebook. Please try later');
            }
        )

    }

    logout(): void {
        this.facebookService.logout();
    }

    private createNewAccountObject(socialStr: string, userStr: string, tokenStr: string, expiresNr: number): NewSocialAccount {
            return {
                social: socialStr,
                userID: userStr,
                token: tokenStr,
                expires:  expiresNr
            };
        }

    private confirmLoginNewSocialAccount(response: any, accountType: string) {
        this.newSocialAccount.next({login: response.login, social: accountType});

    }
}
</code></pre>

<p>Here is dummy file from injected social service</p>

<pre><code>import { SocialAccount} from './../../app/shared/models/social-account';
import { NewSocialAccount} from './../../app/shared/models/new-social-account';

export class SocialsServiceDummy {

    getSocials(): Promise&lt;SocialAccount[]&gt; {
      let socials =  [

      ];
      return Promise.resolve(socials);
    }

    addNewSocialAccount(newAccount: NewSocialAccount) : Promise&lt;any&gt;{
      let social4 = {login: 'facebook', userId: '1fsdf42343', token: 'some_token', expire: 3600};
      return Promise.resolve(social4);
    }

    deleteAccount(id: number): Promise&lt;void&gt; {
      return Promise.resolve(null);
    }

    updateAccount(account: SocialAccount ):  Promise&lt;void&gt;{
        return Promise.resolve(null);
    }

}
</code></pre>

<p>I've resigned from FacebookServiceMock and use it only as injected stub, and return result from spy.
Error double and social_config are also stub.</p>

<p>I would be very glad for some help in what am I doing wrong</p>

<p>Cheers.</p>
",https://stackoverflow.com/questions/44908621/angular2-jasmine-spy-on-unit-testing-methods-doesnt-see-called-method,"['angular', 'unit-testing', 'testing', 'jasmine', 'karma-runner']",792,FALSE,0,1
Unit testing method that uses callback and SynchronousQueue to track results,"<p>I'm using Mockito to test a method that internally makes a networking call and returns a value based on the result of the networking call. This method uses a SynchronousQueue to wait for the result, and the result is set by the callback for the networking call:</p>

<pre><code>HelperClass helperClassObject = new HelperClassObject();

...

public SomeResultCode methodWithNetworkCall() {
    SynchronousQueue&lt;SomeResultCode&gt; resultQueue = new SynchronousQueue&lt;&gt;();

    // some condition checking code

    helperClassObject.makeNetworkCall(new GenericCallback() {
        @Override
        public void onSuccess(JSONObject response) {
            resultQueue.offer(SomeResultCode.SUCCESS);
        }

        @Override
        public void onFailure(VolleyError error) {
            resultQueue.offer(SomeResultCode.FAILURE);
        }
    });

    SomeResultCode resultCode = null;
    try {
        resultCode = resultQueue.poll(1, TimeUnit.MINUTES);
    } catch (InterruptedException e) {

    }
    return resultCode == null ? SomeResultCode.FAILURE : resultCode;
}
</code></pre>

<p>In one of my unit test methods I'm trying to verify that SUCCESS is returned upon successful network call. I've tried using ArgumentCaptor and doAnswer to trigger the callback's onSuccess. However, the method is returning FAILURE. I put a breakpoint in the onSuccess, and it looks like when I use the ArgumentCaptor way the onSuccess is triggered AFTER the poll has timed out. When I use the doAnswer way, I see onSuccess called during the setup (doAnswer.when) but not after I actually call the method. What am I doing wrong?</p>

<p><strong>EDIT</strong>
Stepping through the code again, it looks like answer is called from within the method I'm testing (i.e. when I call testObject.methodWithNetworkCall during my test), NOT during setup. So it is doing exactly what it is supposed to do: responding with onSuccess. But it is responding with onSuccess BEFORE poll is called. So it seems the problem is not that answer and mocking in general is not working/set up wrong, it is an issue with testing with SynchronousQueue.</p>

<p>Here is my test code:</p>

<pre><code>public class TestClassUnitTest {
    TestClass sut;
    HelperClass helperClassObject = mock(HelperClass.class);

    @Before
    public void setup() {
        sut = new TestClass();
        injectField(sut, ""helperClassFieldName"", helperClassObject);
    }

    public void injectField(Object testObject, String fieldName, T mockToInject) {
        // some code using reflection to inject the mock object into the test object
    }

    @Test
    public void testMethodWithNetworkCallWithCaptor() {
        ArgumentCaptor&lt;GenericCallback&gt; captor = ArgumentCaptor.forClass(GenericCallback.class);
        SomeResultCode result = sut.methodWithNetworkcall();
        verify(helperClassObject, times(1)).makeNetworkCall(captor.capture());
        captor.getValue().onSuccess(new JSONObject());
        Assert.assertEquals(SomeResultCode.SUCCESS, result);
    }

    @Test
    public void testMethodWithNetworkCallWithDoAnswer() {
        doAnswer(new Answer(){
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                ((GenericCallback)invocation.getArguments()[0]).onSuccess(new JSONObject());
                return null;
            }
        }).when(helperClassObject).makeNetworkCall(any(GenericCallback.class));
        SomeResultCode result = sut.methodWithNetworkcall();
        Assert.assertEquals(SomeResultCode.SUCCESS, result);
     }
}
</code></pre>
",https://stackoverflow.com/questions/47148082/unit-testing-method-that-uses-callback-and-synchronousqueue-to-track-results,"['java', 'unit-testing', 'callback', 'mockito']",1266,TRUE,0,2
AppDomainUnloadedException when unit-testing a WinForms form with an animated gif,"<p>Some of our integration tests (implemented as Visual Studio Unit Tests) show WinForms forms. For some of them, we happen to get the following message in the test output window:</p>

<pre><code>------ Run test started ------
System.AppDomainUnloadedException: Attempted to access an unloaded AppDomain. This can happen if the test(s) started a thread but did not stop it. Make sure that all the threads started by the test(s) are stopped before completion.
========== Run test finished: 1 run (0:00:00,1699987) ==========
</code></pre>

<p>I narrowed it down to forms which include animated gifs in a PictureBox and managed to create an MCVE:</p>

<pre class=""lang-vb prettyprint-override""><code>&lt;TestMethod()&gt;
Public Sub AppDomainException()
    Using f As New Testform()
        f.Show()
        f.Close()
    End Using
End Sub

Public Class Testform
    Inherits Form

    Private Const Gif = ""R0lGODdhAQABAOcAAAAAAAEBAQICAgMDAwQEBAUFBQYGBgcHBwgICAkJCQoKCgsLCwwMDA0NDQ4ODg8PDxAQEBERERISEhMTExQUFBUVFRYWFhcXFxgYGBkZGRoaGhsbGxwcHB0dHR4eHh8fHyAgICEhISIiIiMjIyQkJCUlJSYmJicnJygoKCkpKSoqKisrKywsLC0tLS4uLi8vLzAwMDExMTIyMjMzMzQ0NDU1NTY2Njc3Nzg4ODk5OTo6Ojs7Ozw8PD09PT4+Pj8/P0BAQEFBQUJCQkNDQ0REREVFRUZGRkdHR0hISElJSUpKSktLS0xMTE1NTU5OTk9PT1BQUFFRUVJSUlNTU1RUVFVVVVZWVldXV1hYWFlZWVpaWltbW1xcXF1dXV5eXl9fX2BgYGFhYWJiYmNjY2RkZGVlZWZmZmdnZ2hoaGlpaWpqamtra2xsbG1tbW5ubm9vb3BwcHFxcXJycnNzc3R0dHV1dXZ2dnd3d3h4eHl5eXp6ent7e3x8fH19fX5+fn9/f4CAgIGBgYKCgoODg4SEhIWFhYaGhoeHh4iIiImJiYqKiouLi4yMjI2NjY6Ojo+Pj5CQkJGRkZKSkpOTk5SUlJWVlZaWlpeXl5iYmJmZmZqampubm5ycnJ2dnZ6enp+fn6CgoKGhoaKioqOjo6SkpKWlpaampqenp6ioqKmpqaqqqqurq6ysrK2tra6urq+vr7CwsLGxsbKysrOzs7S0tLW1tba2tre3t7i4uLm5ubq6uru7u7y8vL29vb6+vr+/v8DAwMHBwcLCwsPDw8TExMXFxcbGxsfHx8jIyMnJycrKysvLy8zMzM3Nzc7Ozs/Pz9DQ0NHR0dLS0tPT09TU1NXV1dbW1tfX19jY2NnZ2dra2tvb29zc3N3d3d7e3t/f3+Dg4OHh4eLi4uPj4+Tk5OXl5ebm5ufn5+jo6Onp6erq6uvr6+zs7O3t7e7u7u/v7/Dw8PHx8fLy8vPz8/T09PX19fb29vf39/j4+Pn5+fr6+vv7+/z8/P39/f7+/v///ywAAAAAAQABAAAIBAD/BQQAOw==""
    Private Const AnimatedGif = ""R0lGODlhAQABAOcAAAAAAAEBAQICAgMDAwQEBAUFBQYGBgcHBwgICAkJCQoKCgsLCwwMDA0NDQ4ODg8PDxAQEBERERISEhMTExQUFBUVFRYWFhcXFxgYGBkZGRoaGhsbGxwcHB0dHR4eHh8fHyAgICEhISIiIiMjIyQkJCUlJSYmJicnJygoKCkpKSoqKisrKywsLC0tLS4uLi8vLzAwMDExMTIyMjMzMzQ0NDU1NTY2Njc3Nzg4ODk5OTo6Ojs7Ozw8PD09PT4+Pj8/P0BAQEFBQUJCQkNDQ0REREVFRUZGRkdHR0hISElJSUpKSktLS0xMTE1NTU5OTk9PT1BQUFFRUVJSUlNTU1RUVFVVVVZWVldXV1hYWFlZWVpaWltbW1xcXF1dXV5eXl9fX2BgYGFhYWJiYmNjY2RkZGVlZWZmZmdnZ2hoaGlpaWpqamtra2xsbG1tbW5ubm9vb3BwcHFxcXJycnNzc3R0dHV1dXZ2dnd3d3h4eHl5eXp6ent7e3x8fH19fX5+fn9/f4CAgIGBgYKCgoODg4SEhIWFhYaGhoeHh4iIiImJiYqKiouLi4yMjI2NjY6Ojo+Pj5CQkJGRkZKSkpOTk5SUlJWVlZaWlpeXl5iYmJmZmZqampubm5ycnJ2dnZ6enp+fn6CgoKGhoaKioqOjo6SkpKWlpaampqenp6ioqKmpqaqqqqurq6ysrK2tra6urq+vr7CwsLGxsbKysrOzs7S0tLW1tba2tre3t7i4uLm5ubq6uru7u7y8vL29vb6+vr+/v8DAwMHBwcLCwsPDw8TExMXFxcbGxsfHx8jIyMnJycrKysvLy8zMzM3Nzc7Ozs/Pz9DQ0NHR0dLS0tPT09TU1NXV1dbW1tfX19jY2NnZ2dra2tvb29zc3N3d3d7e3t/f3+Dg4OHh4eLi4uPj4+Tk5OXl5ebm5ufn5+jo6Onp6erq6uvr6+zs7O3t7e7u7u/v7/Dw8PHx8fLy8vPz8/T09PX19fb29vf39/j4+Pn5+fr6+vv7+/z8/P39/f7+/v///yH/C05FVFNDQVBFMi4wAwEAAAAh+QQACgD/ACwAAAAAAQABAAAIBAABBAQAIfkEAAoA/wAsAAAAAAEAAQAACAQA/wUEADs=""

    Private pib As PictureBox

    Public Sub New()
        MyBase.New()

        pib = New PictureBox()

        ' Change AnimagedGif to Gif and the problem disappears
        Using ms As New MemoryStream(Convert.FromBase64String(AnimatedGif))
            pib.Image = New Bitmap(ms)
        End Using

        Me.Controls.Add(pib)
    End Sub

    Protected Overrides Sub Dispose(disposing As Boolean)
        If disposing Then
            pib.Dispose()
        End If
        MyBase.Dispose(disposing)
    End Sub
End Class
</code></pre>

<p>Apparently, the PictureBox starts some kind of background thread to animate the gif and does not properly stop it when it is disposed. Is there a way to force it to do so or is this a bug in the PictureBox control?</p>
",https://stackoverflow.com/questions/42979071/appdomainunloadedexception-when-unit-testing-a-winforms-form-with-an-animated-gi,"['c#', 'vb.net', 'winforms', 'unit-testing', 'animation']",238,FALSE,0,0
Dynamics CRM - Unit Testing a plugin with RhinoMocks give weird result,"<p>I am writing a unit test for a plugin using Dynamics CRM with RhinoMocks.
After stubbing out the OrganizationService.Retrieve() method, when I invoke the stubbed out method, I am getting null back.</p>

<p>From what I can see (correct me if I'm wrong), is that the stubbed out method signature must the same as the invocation signature.</p>

<p>Here is my code:</p>

<p><strong>TestSetup</strong></p>

<pre><code>var someGuid = Guid.Empty;
var organisationServiceMock = MockRepository.GenerateMock&lt;IOrganizationService&gt;();
</code></pre>

<p>organisationServiceMock.Expect(x => x.Retrieve(""someCrmEntity"", someGuid, SomeCrmEntityColumnSetQuery.ColumnSet))
                .Return(new Entity
                {
                    LogicalName = ""someCrmEntity"",
                    Id = Guid.NewGuid(),
                });</p>

<p><strong>SomeCrmEntityColumnSetQuery Code</strong></p>

<pre><code>public static class SomeCrmEntityColumnSetQuery
{
public static ColumnSet ColumnSet =&gt; new ColumnSet(""column1"", ""column2"");
}
</code></pre>

<p><strong>Invocation Code</strong></p>

<pre><code>var someEntity = organisationServiceMock.Retrieve(""someCrmEntity"", someGuid, SomeCrmEntityColumnSetQuery.ColumnSet);
</code></pre>

<p>//someEntity is null</p>

<p><strong>Things I have tried</strong></p>

<ol>
<li>Removed the ColumnSet and replaced it with null - this works</li>
<li>Replaced the static class SomeCrmEntityColumnSetQuery with a default instance (new ColumnSet())</li>
<li>I have set the someGuid to Guid.Empty thinking that it was not ""joining"" on the correct Guid hence the null return value.</li>
<li>I have tried to replace .Expect() with .Stub() - no joy</li>
</ol>

<p><strong>Edit</strong>
In the expectation, I have tried the .WhenCalled(...) and that is how I found out that if I replace the columnSet argument with a null in the expectation and the invocation, it works. So it's go to do with something in my static class that represents a ColumnSet. The code works as I have it running in my DEV environment.</p>

<p>If anyone can share some light on this, that would be magic!</p>

<p>Charles</p>
",https://stackoverflow.com/questions/41935746/dynamics-crm-unit-testing-a-plugin-with-rhinomocks-give-weird-result,"['plugins', 'dynamics-crm']",285,TRUE,0,1
fakeAsync and tick when unit testing code with Promise and Observables,"<p>I assume that when testing code with Promises it is required to use fakeAsync/tick combination to guarantee that promises are resolves/rejects. This is because tick drains microtasks queue when invoked.</p>

<p>However, what about Observables? Should we also use fakeAsync/tick to guarantee that subscribe handler is invoked?
Looks like unit tests with Observables are completed fine, with all the subscribed Observer instances notified, without fakeAsync/tick so I'm not sure if this is required or not.</p>

<p>Thank you</p>
",https://stackoverflow.com/questions/42747954/fakeasync-and-tick-when-unit-testing-code-with-promise-and-observables,"['unit-testing', 'angular', 'rxjs5']",793,FALSE,0,1
Unit testing a void method with Redis async command in java,"<p>I'm trying to write a unit test for the following function.</p>

<p><strong>responseHandler</strong> and <strong>ErrorHandler</strong> are both methods that are passes using the Command Pattern
and are used to continue the program's flow.
<strong>futureCommand</strong> is a lettuce object (Redis implementation in java).
I'm having difficulties with how to test this method since is both using a future and does not return anything.</p>

<pre><code>public void getOfferData(EventRequestContext&lt;? extends BaseEvent&gt; ctx, int offerId, ResponseHandler&lt;T1Offer&gt; responseHandler,
        ErrorHandler&lt;Throwable&gt; errorHandler) throws Exception {
    String redisKey = keyPrefix + offerId;
    RedisFuture&lt;List&lt;String&gt;&gt; futureCommand = connectionWrapper.getHashValues(redisKey, getRequiredParams());
    futureCommand.thenAccept(valuesList -&gt; {
        TrackerScheduler.processT1GenreicPool.execute(ctx, () -&gt; {
            Map&lt;String, String&gt; resultMap = reconstructMapValues(valuesList, getRequiredParams(), redisKey, ctx);
            T1Offer offerData;
            if(!resultMap.isEmpty()) {
                offerData = new T1Offer(resultMap);
            } else {
                offerData = new T1Offer();
            }
            if(!offerData.isValid()) {
                errorHandler.onError(new Exception(""Invalid fields in offerData""));
            } else {
                responseHandler.onResponse(offerData);
            }
        });
    });
}
</code></pre>

<p>My best attempt was to send the assertion using the <strong><code>responseHandler</code></strong> method like this:</p>

<pre><code>@Test
public void getOfferData_offerFullData_parseSuccess() throws Exception {
    T1ClickOfferDao.instance.getOfferData(null, Integer.parseInt(OFF_ID), resultOffer -&gt; { 
        Assert.assertEquals("""", resultOffer.getActivationDate());
    }, error -&gt; {
    });
}
</code></pre>

<p>but the Test context is finished before the future is evaluated. And even if I <code>Threas.sleep</code> for a second - the assertion does not affect the test result.</p>
",https://stackoverflow.com/questions/48005733/unit-testing-a-void-method-with-redis-async-command-in-java,"['java', 'asynchronous', 'junit', 'redis', 'lettuce']",612,FALSE,0,1
How to setup Jest for Unit testing normal with php project?,"<p>I need to setup the front end unit test for my PHP project.
I decided to go with Jest.</p>

<p>So this is my package.json.</p>

<pre><code>{
  ""name"": ""staging-deploy"",
  ""version"": ""1.0.0"",
  ""description"": ""Staging deploy"",
  ""main"": ""GulpFile.js"",
  ""author"": ""some one"",
  ""license"": ""BSD-2-Clause"",
  ""dependencies"": {
    ""bower"": ""^1.8.0"",
    ""gulp"": ""^3.9.1"",
    ""gulp-autoprefixer"": ""^3.1.1"",
    ""gulp-chmod"": ""^2.0.0"",
    ""gulp-closure-compiler"": ""^0.4.0"",
    ""gulp-concat"": ""^2.6.1"",
    ""gulp-cssnano"": ""^2.1.2"",
    ""gulp-duration"": ""0.0.0"",
    ""gulp-jasmine"": ""^2.4.2"",
    ""gulp-less"": ""^3.3.2"",
    ""gulp-load-plugins"": ""^1.4.0"",
    ""gulp-pixrem"": ""^1.0.0"",
    ""gulp-postcss"": ""^6.3.0"",
    ""gulp-replace"": ""^0.5.4"",
    ""gulp-sourcemaps"": ""^1.11.0"",
    ""gulp-update"": ""0.0.2"",
    ""gulp-update-modul"": ""^1.5.5"",
    ""gulp-watch-less"": ""^1.0.1"",
    ""run-sequence"": ""^2.0.0""
  },
  ""devDependencies"": {
    ""jest"": ""^20.0.4""
  },
  ""scripts"": {
    ""test"": ""jest""
  }
}
</code></pre>

<p>Then I made <code>__tests__</code> folder and making my first testing function like this.</p>

<p>// homepage.test.js</p>

<pre><code>require('../modules/homepage.js');

test('adds 1 + 2 to equal 3', function() {
    expect(Homepage.sum.sumNumber(1, 2)).toBe(3);
});
</code></pre>

<p>And this is my homepage.js</p>

<p>// homepage.js</p>

<pre><code>var Homepage = {};

(function() {
    ""use strict"";

    Homepage.sum = {
        sumNumber: function(num1, num2) {
            return num1 + num2
        }
    };
})();
</code></pre>

<p>Then I ran <code>npm run test</code>
This is what I got:</p>

<pre><code>FAIL  __tests__/homepage.test.js
  ● adds 1 + 2 to equal 3

    ReferenceError: Homepage is not defined

      at Object.&lt;anonymous&gt; (__tests__/homepage.test.js:4:12)
      at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)
      at process._tickCallback (internal/process/next_tick.js:109:7)

  ✕ adds 1 + 2 to equal 3 (2ms)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        3.138s, estimated 11s
</code></pre>

<p>Seems like my test file can not access the function inside my Homepage.js file.</p>

<p>How can I fix this and make it works?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/45475763/how-to-setup-jest-for-unit-testing-normal-with-php-project,"['javascript', 'unit-testing', 'jestjs']",1486,FALSE,0,1
Unit testing a Service method subscribed to an Observable in Angular,"<p>I want to test this component using Jasmine:</p>

<pre><code>export class EditorComponent implements OnInit {
  movimiento: Movimiento;

  constructor(private route: ActivatedRoute, private datosService: DatosService) { }

  ngOnInit() {
    this.route.params
      .subscribe(params =&gt; {
        const _id = params['id'].toString(); // recepción del parámetro
        this.datosService
          .getMovimientoBy_Id$(_id)
          .subscribe(r =&gt; this.movimiento = r); // consulta al servicio
      });
  }

}
</code></pre>

<p>This methods subscribes to an <code>Observable&lt;Movement&gt;</code> returned by the service. This is the <code>DatosService</code> <code>getMovimientoBy_Id$(_id)</code> method:</p>

<pre><code>getMovimientoBy_Id$(_id): Observable&lt;Movimiento&gt; {
  return this.http
    .get(`priv/movimientos/${_id}`)
    .map(r =&gt; r.json());
}
</code></pre>

<p>I've tried this code to test the component:</p>

<pre><code>describe('EditorComponent', () =&gt; {
  let movimiento = new Movimiento(new Date(), 0, 1, 1);
  let component: EditorComponent;
  let fixture: ComponentFixture&lt;EditorComponent&gt;;
  let datosService: DatosService;

  beforeEach(async(() =&gt; {
    let activatedRouteMock = {
      route: Observable.of({ id: 1 })
    }

    TestBed.configureTestingModule({
      imports: [
        HttpModule
      ],
      declarations: [
        EditorComponent
      ],
      providers: [
        DatosService,
        { provide: ActivatedRoute, useValue: activatedRouteMock }
      ]
    })
      .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(EditorComponent);
    component = fixture.componentInstance;
    datosService = fixture.debugElement.injector.get(DatosService);
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });

  it('should create movimiento', (done) =&gt; {
    let spy = spyOn(datosService, 'getMovimientoBy_Id$').and.returnValue(Observable.of(movimiento));
    fixture.detectChanges();
    expect(component.movimiento).toBeTruthy();
    });
});
</code></pre>

<p>The first test passes, but in the second I'm getting this exception</p>

<blockquote>
  <p>Uncaught Error: Error in :0:0 caused by: Cannot read property 'subscribe' of undefined</p>
</blockquote>

<p>I don't understand what I'm doing wrong... Any ideas on what's going on? Thanks.</p>
",https://stackoverflow.com/questions/42261499/unit-testing-a-service-method-subscribed-to-an-observable-in-angular,"['unit-testing', 'angular', 'jasmine', 'observable']",3409,TRUE,0,1
Unit testing when part of the class needs to be mocked,"<p>I have a class that I am trying to unit test.  This class extends another class that I am not interested in unit testing at this time.</p>

<p>The following code is an over simplification of the code I am trying to test.</p>

<pre><code>package com.example.somePackage;
public class ApiBase {
  protected &lt;T extends SomeClass&gt; t getApi(Class&lt;T&gt; apiClass) {/* some logic*/}
}


package com.example.anotherPackage;
public MagicApiImpl extends ApiBase {
  private final MagicApiHandler apiHandler = new MagicApiHandler();

  public String doSomeStuff(String someString) {
    final BookApi bookApi = getApi(BookApi.class);
    // some logic
    return apiHandler.someMethod(bookApi, someString);
  }
}
</code></pre>

<p>I would like to test <code>doSomeStuff()</code> on <code>MagicApiImpl</code> The part I would like to mock is what comes back in <code>getApi()</code>.</p>

<p>At first go I tried simply creating an Instance of MagicApiImpl and setting all the behind the scenes things that happen but that started to become over complex for the scenario I want to test and the number of times I need to test it in other classes.  I will handle the testing of the logic in <code>getApi()</code> in a test of its own.</p>

<p>It would be helpful to use EasyMock to test this as it is what a majority of the tests for this project are written in but I would not be overly apposed to using mockito.</p>

<p>Edit</p>

<p>Okay I was reading about the Mockito.spy()  That would have been wonderful but sadly getApi is protected and in another package.  Worst case I could fall back on placing all the tests in that package but that makes it difficult track code.</p>
",https://stackoverflow.com/questions/47659170/unit-testing-when-part-of-the-class-needs-to-be-mocked,"['java', 'unit-testing', 'junit', 'mockito', 'easymock']",55,FALSE,-1,1
"Jasmine Angular 2 Unit Testing, Array --&gt; Cannot read property of undef","<p>For some Reason this line is failing, but within my logs it shows that the component was initialized with the correct value.</p>

<pre><code>for (let i = 0; i &lt; 20; i++) {
  this['answer_' + (i + 1)] = new FormControl(this.questions[i].answer);
</code></pre>

<p>My Jasmine test spec:</p>

<pre><code> it('should be created', () =&gt; {
    let pvqStepUpService: PVQStepUpService = TestBed.get(PVQStepUpService);

    pvqStepUpService.data = pvqstepUpResponse;
    let questions = [];
    questions = pvqStepUpService.data.pvqs;
    let questionsArr = [];
    let answerControlArr = [];

    component.ngOnInit();

    component.answerControlArr = answerControlArr;
    component.questions = questions;
    console.log('TEST COMPONENT ANSWER CONTROL ARR IS ---&gt; ', component.answerControlArr[0]);
    console.log('Test Component: ANSWER ARRAY ---&gt; ', component.questions[0]);
    console.log('TEST component FORMGROUP ---&gt; ', component.pvqForm);
    console.log(""TEST ANSWER CONTROL ---&gt; {}"", component.answer_1);
    console.log(""TEST ANSWER OF QUESTION ---&gt; "", component.questions[0].answer);


    expect(component).toBeTruthy();
  });
</code></pre>

<p><a href=""https://i.stack.imgur.com/twELx.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/twELx.png"" alt=""enter image description here""></a></p>

<p>I solved it:</p>

<p>Had fixture.detectChanges(); outside of the it block, I placed it just before ngOninit after all my variables were initialized, and it worked.</p>
",https://stackoverflow.com/questions/45403248/jasmine-angular-2-unit-testing-array-cannot-read-property-of-undef,"['angular', 'jasmine']",572,FALSE,0,0
"React unit testing, enzyme/mocha testing (or mocking?) html image api","<p>I have created a component for my project to help with some image loading. The component is working great for me however when trying to unit test I am running into some difficulties with the html Image api:</p>

<p>To start, my component is using the <code>new Image();</code> syntax to load in some images, here is the component</p>

<pre><code>import React from 'react';

require('./progressive-image.scss');

export default class ProgressiveImage extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    const small = this.refs['small-img'];
    const large = this.refs['large-img'];

    const img = new Image();

    img.src = this.props.smallImg;
    img.onload = function() {
      small.classList.add('loaded');
    };

    const imgLarge = new Image();

    imgLarge.src = this.props.largeImg;
    imgLarge.onload = function() {
      imgLarge.classList.add('loaded');
    };

    large.appendChild(imgLarge);
  }

  componentDidUpdate() {
    const small = this.refs['small-img'];
    const large = this.refs['large-img'];
    const sameImg = large.childNodes[2].src === this.props.largeImg;

    // if loading same img, do nothing
    if (!sameImg) {
      // remove loaded
      small.classList.remove('loaded');

      const img = new Image();

      img.src = this.props.smallImg;
      img.onload = function() {
        small.classList.add('loaded');
      };

      // remove old img
      large.childNodes[2].remove();

      const imgLarge = new Image();

      imgLarge.src = this.props.largeImg;
      imgLarge.onload = function() {
        imgLarge.classList.add('loaded');
      };

      large.appendChild(imgLarge);
    }
  }

  render() {
    const imgStyle = { 'paddingBottom': this.props.heightRatio };

    return (
        &lt;div className=""progressive-placeholder"" ref=""large-img""&gt;
          &lt;img className=""img-small"" ref=""small-img"" /&gt;
          &lt;div style={imgStyle} &gt;&lt;/div&gt;
        &lt;/div&gt;
    );
  }
}

ProgressiveImage.displayName = 'ProgressiveImage';

ProgressiveImage.propTypes = {
  bgColor: React.PropTypes.string,
  heightRatio: React.PropTypes.string.isRequired,
  largeImg: React.PropTypes.string.isRequired,
  smallImg: React.PropTypes.string.isRequired,
};
</code></pre>

<p>Using enzymes <code>mount</code> to fully render, i am doing something like this to unit test the componentDidMount (and hopefully the componentdidupdate in the future).</p>

<pre><code>    it('should load images on mount', () =&gt; {
    const instance = mount(
          &lt;FollainProgressiveImage
            bgColor={bgColor}
            heightRatio={heightRatio}
            largeImg={largeImg}
            smallImg={smallImg}
            /&gt;
      );
  });
</code></pre>

<p>However the test runner is yelling at me that <code>Image is not defined</code>. So i tried something like </p>

<pre><code>    it('should load images on mount', () =&gt; {
    global.Image = spy();
    const instance = mount(
          &lt;FollainProgressiveImage
            bgColor={bgColor}
            heightRatio={heightRatio}
            largeImg={largeImg}
            smallImg={smallImg}
            /&gt;
      );
  });
</code></pre>

<p>That spy is a <code>sinon.spy</code>, however this gives me the error of <code>First argument to Node.prototype.appendChild must be a Node</code> , but i can see in the coverage report that the componentDidMount is being hit.</p>

<p>I am not sure how to best approach testing this, should I fully mock the object, or is there some better way to do this?</p>

<p>Just for reference - my test env is set up like : </p>

<pre><code>global.document = jsdom.jsdom('&lt;!doctype html&gt;&lt;html&gt;&lt;body&gt;&lt;/body&gt;&lt;/html&gt;');
global.window = document.defaultView;
global.navigator = {userAgent: 'node.js'};
</code></pre>

<p>Maybe this needs to change?</p>

<p>Really stuck here, looking for any input in how to test this code. Thanks!!</p>
",https://stackoverflow.com/questions/42164114/react-unit-testing-enzyme-mocha-testing-or-mocking-html-image-api,"['javascript', 'unit-testing', 'reactjs', 'enzyme']",733,TRUE,0,2
Android Unit Testing result List&lt;List&lt;Model&gt;&gt; instead of List&lt;Model&gt;,"<p>I have tried to unit testing by <a href=""https://medium.com/upday-devs/android-architecture-patterns-part-3-model-view-viewmodel-e7eeee76b73b"" rel=""nofollow noreferrer"">https://medium.com/upday-devs/android-architecture-patterns-part-3-model-view-viewmodel-e7eeee76b73b</a>. 
Why does Testsubscriber give List of ListModel result instead of ListModel ?</p>

<p>my test</p>

<pre><code>public class MainViewModelTest {

@Mock
private IDataModel mDataModel;

private MainViewModel mMainViewModel;

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

}

@After
public void tearDown() throws Exception {

}

@Test
public void testGetSupportedLanguages_emitsCorrectLanguages() {
    Language de = new Language(""German"", LanguageCode.DE);
    Language en = new Language(""English"", LanguageCode.EN);
    List&lt;Language&gt; languages = Arrays.asList(de, en);

    Observable&lt;List&lt;Language&gt;&gt; mockObservable = Observable.just(languages);

    doReturn(mockObservable).when(mDataModel).getObservableSupportedLanguages();

    Language hr = new Language(""Slovakian"", LanguageCode.HR);
    List&lt;Language&gt; expectedLanguages = Arrays.asList(de, en, hr);

    mMainViewModel = new MainViewModel(mDataModel, new ImmediateSchedulerProvider());
    TestSubscriber&lt;List&lt;Language&gt;&gt; testSubscriber = new TestSubscriber&lt;&gt;();

    mMainViewModel.getObservableSupportedLanguages().subscribe(testSubscriber);

    testSubscriber.assertNoErrors();
    testSubscriber.assertReceivedOnNext(expectedLanguages); //here i get List&lt;List&lt;Language&gt;&gt; instead of one List&lt;Language&gt;


}

}
</code></pre>

<p>in MainViewModel</p>

<pre><code> @NonNull
public Observable&lt;List&lt;Language&gt;&gt; getObservableSupportedLanguages() {
    return mDataModel.getObservableSupportedLanguages();
}
</code></pre>

<p>in DataModel</p>

<pre><code>@NonNull
@Override
public Observable&lt;List&lt;Language&gt;&gt; getObservableSupportedLanguages() {
    return Observable.fromCallable(this::getLanguages);
}

@NonNull
private List&lt;Language&gt; getLanguages() {
    return Arrays
            .asList(new Language(""English"", LanguageCode.EN),
                    new Language(""German"", LanguageCode.DE),
                    new Language(""Slovakian"", LanguageCode.HR));
}
</code></pre>
",https://stackoverflow.com/questions/44066052/android-unit-testing-result-listlistmodel-instead-of-listmodel,"['android', 'unit-testing', 'observable', 'rx-android']",335,TRUE,0,1
Unit testing in boilerplate framework application with angular and asp.net core,"<p>i am developing boilerplate application with asp.net core and angular 2, here i struck at unit testing in asp.net core solution. while doing unit testing my code is not hitting the real database. the test cases are running for only mock data which i have given in seed folder in asp.net core solution. </p>

<p>please give me a solution to hit real database and based on that real database records my unit test cases should work.</p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/46189128/unit-testing-in-boilerplate-framework-application-with-angular-and-asp-net-core,"['angular', 'asp.net-core', 'boilerplate']",41,FALSE,0,0
Unit testing with enzyme got Cannot read property &#39;be&#39; of undefined,"<p>My not working test </p>

<pre><code>import React from 'react';
import {shallow, mount} from 'enzyme';
import TopNav from '../components/topNav';

it('Navbar should existed', () =&gt; {
    const nav = shallow(&lt;TopNav /&gt;);
    expect(nav.find('#topNav').exists()).to.be(true);
});
</code></pre>

<p>My topNav Component.</p>

<pre><code>import { Component } from 'react';

export default class topNav extends Component {
    render(){
        return(
            &lt;div id=""topNav""&gt;&lt;strong className=""testtest""&gt;Nav bar&lt;/strong&gt;&lt;/div&gt;
        )
    }
}
</code></pre>

<p>I have no clue what is wrong here. I took the exact example from the API doc of enzyme. But when I do this, it worked</p>

<pre><code>it('Navbar should existed', () =&gt; {
    expect(shallow(&lt;TopNav /&gt;).is('#topNav')).toBe(true);
});
</code></pre>

<p>This is what the doc says 
<a href=""http://airbnb.io/enzyme/docs/api/ShallowWrapper/exists.html"" rel=""nofollow noreferrer"">http://airbnb.io/enzyme/docs/api/ShallowWrapper/exists.html</a></p>
",https://stackoverflow.com/questions/42477328/unit-testing-with-enzyme-got-cannot-read-property-be-of-undefined,"['reactjs', 'jestjs', 'enzyme']",452,TRUE,0,1
How can i do the unit testing of this c# program?,"<p>The given program is:</p>

<pre><code>public Adoption adoptionProcess(Client theClient, ref int numberToAdopt, 
                ArrayList animalList)
{
    ArrayList adoptedAnimals = new ArrayList();
    int currentAnimal = 0;
    double adoptionFee = 0;
    while (numberToAdopt &gt; 0)
    {
        Animal thisAnimal = (Animal)animalList[currentAnimal];
        if (!thisAnimal.adopted)
        {
            adoptedAnimals.Add(thisAnimal);
            adoptionFee += thisAnimal.getadoptionFee();
            thisAnimal.adopted = true;
            numberToAdopt--;
        }
        currentAnimal++;
    }
    return new Adoption(theClient, adoptionFee, adoptedAnimals);
}
</code></pre>

<p>Unit testing I have tried is:</p>

<pre><code>[TestMethod]
public void adoptionProcessTest()
{
    Client amrit = new Client(""Amrit"", ""Amrit"", "" 1"", ""Melbourne"", 
                            ""9898989898"", ""aamrit10@gmail.com"");
    ArrayList myAL = new ArrayList();
    myAL.Add(""anim1"");
    myAL.Add(""anim2"");
    myAL.Add(""anim3"");


    AdoptAPet adopt = new AdoptAPet();
    Adoption actual = adopt.adoptionProcess(amrit, ref num, myAL);
    Adoption expected = new Adoption(amrit, 1, );
    Assert.AreEqual(expected, actual);
}
</code></pre>

<p>It shows error: Unable to cast object of type 'System.Int32' to type 'amrit.Animal'.</p>
",https://stackoverflow.com/questions/46009113/how-can-i-do-the-unit-testing-of-this-c-program,"['c#', 'nunit']",84,FALSE,-1,1
Unit testing .Net Core Library – could not load file or Assembly,"<p>I wrote a simple Class Library with a method <strong>GetNodes</strong> to examine content of the chosen directory.</p>

<pre><code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

public void GetNodes(string directoryPath)
        {
            if (directoryPath == null)
                throw new ArgumentNullException(""directoryPath"");

            //Remove white-space characters from the start and end of path.
            directoryPath = directoryPath.Trim();

            bool isWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);

(...)

}
</code></pre>

<p><strong><em>project.json:</em></strong></p>

<pre><code>{
  ""version"": ""1.0.0-*"",

  ""dependencies"": {
    ""NETStandard.Library"": ""1.3.0""
  },

  ""frameworks"": {
    ""netstandard1.3"": {
      ""imports"": ""dnxcore50""
    }
  }
}
</code></pre>

<p>Project has been built successfully. </p>

<p>Then in order to perform some unit tests I created a simple Unit Test project (.Net Framework 4.6) </p>

<pre><code>[TestMethod]
        [ExpectedException(typeof(ArgumentNullException))]
        public void DetectException_WhenCorrectExceptionIsThrown()
        {
            FileManager fm = new FileManager();

            fm.GetNodes(@""c:\"");
        }
</code></pre>

<p>Every time I run the test I get this error:</p>

<pre><code>Test Name:  DetectException_WhenCorrectExceptionIsThrown
Test FullName:  Task_2_Test.FileManagerTests.DetectException_WhenCorrectExceptionIsThrown
Test Source:    D:\Git\task_2\Task_2\test\Task_2_Test\FileManagerTests.cs : line 25
Test Outcome:   Failed
Test Duration:  0:00:00,0152049

Result StackTrace:  
at Task_2.FileManager.GetNodes(String directoryPath)
   at Task_2_Test.FileManagerTests.DetectException_WhenCorrectExceptionIsThrown() in D:\Git\task_2\Task_2\test\Task_2_Test\FileManagerTests.cs:line 30
Result Message: 
Test method Task_2_Test.FileManagerTests.DetectException_WhenCorrectExceptionIsThrown threw exception System.IO.FileNotFoundException, but exception System.ArgumentNullException was expected. Exception message: System.IO.FileNotFoundException: Could not load file or assembly 'System.Runtime.InteropServices.RuntimeInformation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. Nie można odnaleźć określonego pliku.=== Pre-bind state information ===
LOG: DisplayName = System.Runtime.InteropServices.RuntimeInformation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
 (Fully-specified)
LOG: Appbase = file:///D:/Git/task_2/Task_2/test/Task_2_Test/bin/Debug
LOG: Initial PrivatePath = NULL
Calling assembly : Task_2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\VISUAL STUDIO EXPRESS 2015\COMMON7\IDE\COMMONEXTENSIONS\MICROSOFT\TESTWINDOW\vstest.executionengine.x86.exe.Config
LOG: Using host configuration file: 
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Post-policy reference: System.Runtime.InteropServices.RuntimeInformation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
LOG: Attempting download of new URL file:///D:/Git/task_2/Task_2/test/Task_2_Test/bin/Debug/System.Runtime.InteropServices.RuntimeInformation.DLL.
LOG: Attempting download of new URL file:///D:/Git/task_2/Task_2/test/Task_2_Test/bin/Debug/System.Runtime.InteropServices.RuntimeInformation/System.Runtime.InteropServices.RuntimeInformation.DLL.
LOG: Attempting download of new URL file:///D:/Git/task_2/Task_2/test/Task_2_Test/bin/Debug/System.Runtime.InteropServices.RuntimeInformation.EXE.
LOG: Attempting download of new URL file:///D:/Git/task_2/Task_2/test/Task_2_Test/bin/Debug/System.Runtime.InteropServices.RuntimeInformation/System.Runtime.InteropServices.RuntimeInformation.EXE.
</code></pre>

<p>I see that this error is connected with System.Runtime.InteropServices (I use this library to check the current OS in order to verify correct syntax of the directory path).</p>

<p>I don’t want to resign from this feature, but I have no idea how to deal with this.</p>

<p>Btw. My Ide is Visual Studio Community 2015.</p>

<p>Thank you in advance for your support.</p>
",https://stackoverflow.com/questions/41485955/unit-testing-net-core-library-could-not-load-file-or-assembly,"['unit-testing', '.net-core']",856,FALSE,0,2
MeteorJS: Dummy for user and its roles to do unit testing,"<p>I would like to do some unit testing (mocha/chai) for my meteor application. I'm using validated methods (which shouldn't matter for this).</p>

<p>In my method I'm checking if the user has admin permission to perform a collection update.</p>

<p>How do I set a 'dummy' in my unit test, as right now the test will always fail with a 403 error throw.</p>

<p><strong>Unit test</strong></p>

<pre><code>describe('method', () =&gt; {
  it('should update document', (done) =&gt; {
    articleUpdate.call({ _id, value })
  }
})
</code></pre>

<p><strong>Method</strong></p>

<pre><code>const articleUpdate = new ValidatedMethod({
  name: 'article.update',
  validate: null,

  run ({ _id, value }) {
    const loggedInUser = Meteor.user()
    const isAdmin = Roles.userIsInRole(loggedInUser, ['group'], 'admin')

    if (!isAdmin) { throw new Meteor.Error(403, 'Access denied') }

    Articles.update(_id, {
      $set: { content: value }
    })
  }
})
</code></pre>
",https://stackoverflow.com/questions/45203169/meteorjs-dummy-for-user-and-its-roles-to-do-unit-testing,"['javascript', 'unit-testing', 'meteor']",41,TRUE,0,1
How to create a data table using fixture while unit testing,"<pre><code>private DataTable GetRuleCategoryTable()
{
      // RuleCategory rc = new RuleCategory();
      DataTable dtRuleCategory = _fixture.Build&lt;DataTable&gt;()
                .With(x =&gt; x.Columns.Add(""RuleCategoryName"", typeof(System.String)))
                .With(x =&gt; x.Columns.Add(""OrganizationID"", typeof(System.Int32)))
                .With(x =&gt; x.Columns.Add(""RuleEntryCode"", typeof(System.Int32)))
                .With(x =&gt; x.Columns.Add(""IsActive"", typeof(System.Boolean)))
                .With(x =&gt; x.Columns.Add(""RuleCategoryLookupId"", typeof(System.Boolean)))                
                 .Create();
            return dtRuleCategory;
}
</code></pre>

<p>Above code throws exception - </p>

<blockquote>
  <p>The expression's Body is not a Member Expression.</p>
</blockquote>

<p>Most likely this is because it does not represent access to a property or field</p>
",https://stackoverflow.com/questions/47792287/how-to-create-a-data-table-using-fixture-while-unit-testing,"['c#', 'unit-testing', 'nunit', 'fixture']",330,FALSE,0,0
How resolve cannot read property &quot;classList&quot; in unit testing with ReactJS?,"<p>i have write a function in my react component as shown below.</p>

<pre><code> myFunction(){
if (this.state.isTrue) {
  document.querySelector("".myClass"").classList.remove('class-false');
} else {
  document.querySelector("".myClass"").classList.add('class-true');
}
</code></pre>

<p>}</p>

<p>but in my test case when i simulate click it is throwing error like ""cannot read property classList"" as shown below</p>

<p><a href=""https://i.stack.imgur.com/cACa3.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/cACa3.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/46673458/how-resolve-cannot-read-property-classlist-in-unit-testing-with-reactjs,"['reactjs', 'react-redux', 'enzyme']",917,FALSE,0,0
How to mock nested directive in Angular 1.x (Unit testing),"<p>Hey I have problem with mock my directive. Look at this code:</p>

<pre><code> &lt;dir-one data=""data""&gt;
&lt;div ng-repeat=""e in data""&gt;
  &lt;div ng-repeat=""e2 in e""&gt;
   &lt;dir-two prop=""e2.some"" prop2=""e2.some""&gt;  &lt;!-- i want to mock this directive --&gt;
   &lt;/dir-two&gt;
 &lt;/div&gt;
&lt;/dir-one&gt;
</code></pre>

<p></p>

<p>Not I want to mock this template to jasmine and reproduce <code>dir-two</code> click event.</p>

<p>I tryed something like this :</p>

<pre><code>var tpl = `&lt;dir-one data=""data""&gt;
&lt;div ng-repeat=""e in data""&gt;
  &lt;div ng-repeat=""e2 in e""&gt;
   &lt;dir-two prop=""e2.some"" prop2=""e2.some""&gt;  &lt;!-- i want to mock this directive --&gt;
   &lt;/dir-two&gt;
 &lt;/div&gt;
&lt;/dir-one&gt;`

    var newScope = $rootScope.$new();
    newScope.DATA = // some data;

    el= angular.element(tpl);
    $compile(el)(newScope);
    $rootScope.$digest();
    catchController = el.controller('dirTwoController'); // undefined
    catchController2 = el.controller('dirOneController'); // no error, catch object
</code></pre>

<p>There is a problem, becouse I cant reproduce dirTwoController using this mock, just dirOneController corectly showing output.</p>

<p>Any ideas for solve this problem ?</p>

<p>Thanks !</p>
",https://stackoverflow.com/questions/42594591/how-to-mock-nested-directive-in-angular-1-x-unit-testing,"['angularjs', 'unit-testing']",152,FALSE,0,1
Angularjs Jasmine unit testing a controller : $scope and ionicPopupProvider is undefined,"<p>I'm trying to test my simple controller but seems like nothing is working.
the controller:</p>

<pre><code>  userCtrlMod.controller('resetCtrl',
  ['$scope', '$ionicPopup', '$timeout','resetPwd',
  function($scope, $ionicPopup, $timeout, resetPwd){

  $scope.reset = function(){
    $scope.resetPopUp = $ionicPopup.show({
     templateUrl:'././templates/popup/reset.html',
     scope: $scope
    });
  }}]);
</code></pre>

<p>my test file :</p>

<pre><code>describe(""resetCtrl"", function () {
var $myScope, $myController,  timeout;

beforeEach(module('dbooks.userCtrl'));

beforeEach(inject(function(
_$controller_,
_$rootScope_,
_$timeout_,
$ionicPopup
){
  $myController = _$controller_;
  $myScope = _$rootScope_;

  $myController = $controller('resetCtrl' , {
    $scope: $myScope,
    $resetPopUp : $ionicPopup
  });
}));

it(""should have a $scope variable"", function() {
    //console.log($myScope);
    expect($myScope).toBeDefined();
});});
</code></pre>

<p>I googled it but i could'nt find any solution, please someone tell me what I'm doing wrong.
the errors :</p>

<blockquote>
  <p>Uncaught Error: [$injector:unpr] Unknown provider: $ionicPopupProvider &lt;- $ionicPopup</p>
  
  <p>Uncaught Expected undefined to be defined.
      at Object.</p>
</blockquote>
",https://stackoverflow.com/questions/42952520/angularjs-jasmine-unit-testing-a-controller-scope-and-ionicpopupprovider-is-u,"['angularjs', 'unit-testing', 'scope', 'controller', 'jasmine']",615,FALSE,0,2
Meteor: using npm packages for unit testing (instead of atmosphere packages),"<p>I want to test my meteor app. Initially I wanted to use some atmosphere package, but it turns out that a lot (almost all of them) are no longer maintained. </p>

<p>Is there a way to use ""pure"" npm packages (like mocha or jest) in meteor app.</p>

<p>My initial logic for this is to <code>npm install --save-dev</code> what I need (e.g. <code>mocha</code> &amp; <code>chai</code>) and then add a script in <code>package.json</code> that would perform the testing. </p>
",https://stackoverflow.com/questions/47945941/meteor-using-npm-packages-for-unit-testing-instead-of-atmosphere-packages,"['javascript', 'unit-testing', 'meteor']",57,FALSE,0,1
Vue unit testing - mocking imported services when using vue-test-utils mount,"<p>I'm playing with mount() from vue-test-utils, have a component that imports services that should be mocked in the unit test.  </p>

<p>I see that mount() has a mocks option, but trying to extrapolate the example given at <a href=""https://github.com/vuejs/vue-test-utils/blob/dev/docs/en/guides/common-tips.md#mocking-injections"" rel=""noreferrer"">guides, common-tips, mocking injections</a> to the scenario of an injected service is eluding me.</p>

<pre><code>mount(Component, {
  mocks: {
    ...?
  }
})
</code></pre>

<p>The component simply imports the service, which is plain JS</p>

<pre><code>import DataService from '../services/data.service'
</code></pre>

<p>I can get it working using the inject-loader which is detailed here <a href=""https://vue-loader.vuejs.org/en/workflow/testing-with-mocks.html"" rel=""noreferrer"">Testing With Mocks</a></p>

<p><strong><em>The code that does work</em></strong></p>

<pre><code>const MyComponentInjector = require('!!vue-loader?inject!./MyComponent.vue')
const mockedServices = {
  '../services/data.service': {
    checkAll: () =&gt; { return Promise.resolve() }
  },
}
const MyComponentWithMocks = MyComponentInjector(mockedServices)

const wrapper = mount(MyComponentWithMocks, { store: mockStore, router })
</code></pre>

<p><strong><em>What is the syntax for mount(MyComponent, { mocks: ... })?</em></strong>  </p>

<p>Since mount() has a mocks option, should it not be possible to pass mockedServices to it in some form?</p>
",https://stackoverflow.com/questions/46553779/vue-unit-testing-mocking-imported-services-when-using-vue-test-utils-mount,"['unit-testing', 'vuejs2']",3766,TRUE,5,1
angularjs unit testing (cannot find propery of &#39;resolve&#39; undefined angularjs testing),"<p>I am trying to do unit test of my angular app with karma. I am getting some error. Am i missing something? A
This my controller</p>

<pre><code>(function () {
""use strict""
angular
    .module(""myApp"")

.controller(""userCtrl"",['$scope', '$state', 'userService', 'appSettings','md5','currentUser','$rootScope',
    function ($scope, $state, userService, appSettings,md5,currentUser, $rootScope) {

    $scope.login = function() {
        $scope.loading = true;
        if($scope.password != null){
        var user ={
            username:$scope.username,
            password:md5.createHash($scope.password)
        }

            var getData = userService.login(user);
            getData.then(function (response) {
                console.log(response);
                $scope.loading = false;

                currentUser.setProfile(user.username, response.data.sessionId);

                $state.go('videos');
            }, function (response) {
                console.log(response.data);
            });
        }else{
            $scope.msg = ""Password field is empty!""
        }
    }
 }])
}());
</code></pre>

<h2>This is my test codes</h2>

<pre><code>'use strict';

describe('userCtrl', function() {
  beforeEach(module('myApp'));
  var scope, userCtrl, apiService,q, deferred, currentUser;

describe('$scope.login', function(){
  beforeEach(function(){
        apiService = {
              login: function () {
                  deferred = q.defer();
                  return deferred.promise;
              };
            };
        });

beforeEach(inject(function($controller, $rootScope, $q, _currentUser_){
    var user ={name:'ali',password:'password'};
    scope = $rootScope.$new();
    q = $q;

    // The injector unwraps the underscores (_) from around the parameter names when matching
    userCtrl = $controller('userCtrl', {
        $scope:scope, 
        userService:apiService
      });
    //userService = _userService_;
    currentUser = _currentUser_;
  }));

    it('should call user service login', function() {
      spyOn(apiService, 'login').and.callThrough();
      scope.login();
      deferred.resolve(user);

      expect(apiService.login).toHaveBeenCalled();
    });

    it('checks the password field', function() {
      scope.login();
      expect(scope.msg).toEqual('Password field is empty!');
    });

});
});
</code></pre>

<p>And i am getting this error
<a href=""https://i.stack.imgur.com/sH9al.jpg"" rel=""nofollow noreferrer"">enter image description here</a></p>
",https://stackoverflow.com/questions/43082785/angularjs-unit-testing-cannot-find-propery-of-resolve-undefined-angularjs-tes,"['angularjs', 'unit-testing', 'karma-jasmine']",54,FALSE,0,1
Segmentation Fault occurs when unit testing with GMock with boost pointers,"<p>I'm having trouble adding a unit test for a class that I have. One of the functions uses a boost pointer (dynamic pool) and there's always a segmentation fault that occurs whenever I compile the test as seen from the backtrace. If run normally, it compiles properly but when using Google Mock it fails. </p>

<p>The Mock::AllowLeak also does not seem to work for me. Unfortunately, I cannot share the code in public so if anybody has experienced testing functions that uses boost pointers with Google Mock feel free to share some tips.</p>

<p>Thank you</p>

<hr>

<p>Function to be tested:</p>

<pre><code>RetObj* Foo::FooFunction(uint32_t param1)
{
  spRetObj_t ptr = pool_storage-&gt;Get&lt;RetObj&gt;(); //error occurs when I use this
  ...
  return ptr;
}
</code></pre>

<p>spRetObj_t initialize:</p>

<pre><code>typedef stdex::IPool&lt;RetObj&gt;::iptr spRetObj_t;
</code></pre>

<p>Pool storage:</p>

<pre><code>#include ""stdex/dynamic_pool.hpp""
...
class PoolStorage
{
...
    template&lt;typename T&gt;
        typename stdex::IPool&lt;T&gt;::iptr Get(void (T::*on_free)(void) = 0);
...
}
</code></pre>

<p>Code in boost where the exception was thrown:</p>

<pre><code>T * operator-&gt;() const
{
    BOOST_ASSERT( px != 0 );
    return px;
}
</code></pre>
",https://stackoverflow.com/questions/47344190/segmentation-fault-occurs-when-unit-testing-with-gmock-with-boost-pointers,"['c++', 'unit-testing', 'pointers', 'boost', 'googlemock']",525,FALSE,0,0
How to inject mock objects into instance attributes in Python unit testing,"<p>I am learning python </p>

<p>I'm wondering if there is a mechanism to ""inject"" an object (a fake object in my case) into the class under test without explicitly adding it in the costructor/setter.</p>

<pre><code>## source file
class MyBusinessClass():
    def __init__(self):
        self.__engine = RepperEngine()

    def doSomething(self):
        ## bla bla ...
        success

## test file
## fake I'd like to inkject
class MyBusinessClassFake():
   def __init__(self):
      pass

def myPrint(self) :
    print (""Hello from Mock !!!!"")

class Test(unittest.TestCase):

    ## is there an automatic mechanism to inject MyBusinessClassFake 
    ## into MyBusinessClass without costructor/setter?
    def test_XXXXX_whenYYYYYY(self):

        unit = MyBusinessClass()
        unit.doSomething()
        self.assertTrue(.....)
</code></pre>

<p>in my test I'd like to ""inject"" the object ""engine"" without passing it in the costructor. I've tried few option (e.g.: @patch ...) without success. </p>
",https://stackoverflow.com/questions/42397189/how-to-inject-mock-objects-into-instance-attributes-in-python-unit-testing,"['python', 'mocking', 'python-unittest']",6500,TRUE,5,4
dependecy injection and unit testing - static helper methods or private instance methods,"<p>From unit testing and dependency injection point of view, what's the usual adopted norm when it comes to helper methods?</p>

<p>Here is my example situation:</p>

<pre><code>public class GoodiesController : Controller
{
   private IMyContext _context;

   public GoodiesController(IMyContext context)
   {
      _context = context
   }

   public async Task&lt;IAction&gt; GetThoseGoodies()
   { 
       if(YouLikeThemThisWay(Request.Path))
        {
           var result = await _context.GoGetThemThisWay()
        } else { }
    }
</code></pre>

<p>My question is am I better off with <code>YouLikeThemThisWay(string path)</code> as a static helper in some class or as a private instance method? Assuming I might have a couple of the likes of <code>YouLikeThemThisWay</code>?</p>
",https://stackoverflow.com/questions/42139747/dependecy-injection-and-unit-testing-static-helper-methods-or-private-instance,"['c#', 'unit-testing', 'dependency-injection']",1038,TRUE,4,1
How do I override passport authentication when unit testing using mocha/chai?,"<p>I tried setting <code>app.request.isAuthenticated = function(){return true;}</code> as was recommended in another answer but this didn't work for me. </p>

<p>This is the authenticate method that I use as middleware on the routes that I want authenticated:</p>

<pre><code>const authenticate = [passport.authenticate(['bearer'], {session: false}), (req, res, next) =&gt; {
    if (req.isAuthenticated()) { 
        return next(null);
    }
    else {
        return res.status(401).send('Unauthorized');
    }
}];
</code></pre>

<p>A typical secured call would look like this</p>

<pre><code>router.get('/securedInfo', authenticate, function(req,res,next){
    // do stuff
});
</code></pre>

<p>I'd also prefer not to authenticate in this test because I'd like to separate testing my RESTful API tests from my authentication logic (because the latter will most likely change over time).</p>
",https://stackoverflow.com/questions/42145919/how-do-i-override-passport-authentication-when-unit-testing-using-mocha-chai,"['javascript', 'node.js', 'authentication', 'ecmascript-6', 'mocha.js']",224,FALSE,4,0
Accessing a key value pairs in a JsonResponse in Django Unit Testing,"<p>I want to access the data returned in the following jsonResponse object:</p>

<pre><code>{""results"": [[1, ""Probability and Stochastic Processes"", 9781118324561, ""Roy D. Yates"", ""2014-01-01"", ""Wiley""], [2, ""Interaction Design"", 9781119020752, ""Rogers Price"", ""2015-01-01"", ""John Wiley &amp; Sons""], [3, ""Microeconomics"", 9780077501808, ""Colander"", ""2013-01-01"", ""McGraw Hill""], [4, ""jfalksdjf"", 123123, ""test"", ""1990-01-01"", ""Penguin""]]}
</code></pre>

<p>I am running into trouble however and I have tried many things</p>

<pre><code>def test_noIDGiven(self):
    response = self.client.get(reverse('allTextbooks')) #returns the json array above
    #check that there are three textbooks in the response
    #print(response.content['results'][0][0]) - this didnt work
    self.assertEquals(response.content[0][0], 1) #basically want to access the id of the first object and make sure it is 1
</code></pre>

<p>Any help on how the best way to go about accessing the key value pairs of this object would be nice. thanks in advance</p>

<p>More information:
- when i reverse 'allTextbooks' the api call returns this:</p>

<pre><code>results = list(Textbook.objects.values_list())
return JsonResponse({'results': results})
</code></pre>
",https://stackoverflow.com/questions/42472353/accessing-a-key-value-pairs-in-a-jsonresponse-in-django-unit-testing,"['django', 'unit-testing']",3981,TRUE,4,4
Vue.JS Unit Testing - Original method is still being called after using sinon.stub(),"<p>I am using Sinon to stub API calls when unit testing my components (written with TypeScript and <a href=""https://github.com/vuejs/vue-class-component"" rel=""nofollow noreferrer""><code>vue-class-component</code></a>). After adding the stub to the unit test, the original method is still being called (not returning the stubbed value).</p>

<pre><code>it('should set the text to bar', async () =&gt; {

  const stubbedApiResponse = () =&gt; {
    return 'bar';
  };

  sinon.stub(MyComponent.prototype, 'getFoo').callsFake(stubbedApiResponse);

  let options = {
    template: '&lt;div&gt;&lt;my-component&gt;&lt;/my-component&gt;&lt;/div&gt;',
    components: {'my-component': MyComponent},
    store: this.store
  };
  this.vm = new Vue(options).$mount();

  Vue.nextTick(() =&gt; {
    expect(this.vm.$el.querySelector('.text').textContent).toBe('bar'); // Still equals 'foo'
  });
});
</code></pre>

<p>The method that I am attempting to stub is called on <code>mounted</code> in the component and sets the text content. Any help would be appreciated, thanks!</p>
",https://stackoverflow.com/questions/46858288/vue-js-unit-testing-original-method-is-still-being-called-after-using-sinon-st,"['typescript', 'vue.js', 'karma-runner', 'sinon', 'sinon-chai']",698,TRUE,4,1
How can I fake a missing dependency for unit testing in python?,"<p>I have written a python module that depends on a third-party package that isn't available on my CI testing machine, so I can't test my module remotely because I can't get past the <code>import dependency</code> statement.</p>

<p>If we assume there's no way I can just manually install the dependency (seems like a pain) on the CI host, what's the easiest way to fake/mock/whatever the missing third-party package so that I can test my code?</p>

<p>I'm only using a single class provided by the dependency, so I would happily just mock that object, if there's a way to just do that, instead of the whole module.</p>
",https://stackoverflow.com/questions/41623500/how-can-i-fake-a-missing-dependency-for-unit-testing-in-python,"['python', 'python-unittest', 'python-mock']",1384,TRUE,4,1
Importing resources for unit testing using pytest: module level or test level?,"<p>I have been learning about the advantages of test-driven development, and am attempting to develop my first TDD app using <a href=""https://docs.pytest.org/en/latest/"" rel=""nofollow noreferrer"">pytest</a> and the <a href=""https://pypi.python.org/pypi/setuptools"" rel=""nofollow noreferrer"">setuptools</a> <code>develop</code> option. Going well so far. One question I have: where should resources that are to be tested be imported in my <code>test_*</code> modules? </p>

<p>For example, I could import thusly, at the module level: </p>

<pre><code>from app.module1 import resource1, resource2

def test_resource1():
    assert test_resource1 == ""expected value 1""

def test_resource2():
    assert test_resource2 == ""expected value 2""
</code></pre>

<p>On the other hand, it seems like it makes more sense to do the imports in each test function: </p>

<pre><code>def test_resource1():
    from app.module1 import resource1
    assert test_resource1 == ""expected value 1""

def test_resource2():
    from app.module1 import resource2
    assert test_resource2 == ""expected value 2""
</code></pre>

<p>This of course assumes the resources to be tested aren't needed anywhere else. </p>

<p>Aside from the difference in required characters to type, is there an advantage to doing one or the other? </p>
",https://stackoverflow.com/questions/43767706/importing-resources-for-unit-testing-using-pytest-module-level-or-test-level,"['python', 'pytest']",388,TRUE,4,4
"Unit testing Azure Function: Cannot create an instance of TraceWriter, how to mock?","<p>I'm trying to unit test a basic Azure Function.  The function's Run method requires a TraceWriter argument; TraceWriter is an abstract class and I'm not finding much in terms of documentation for mocking this dependency.</p>

<p>Here's the signature of the method I'm attempting to test:</p>

<pre><code>public static void Run(string myQueueItem, TraceWriter log)
</code></pre>

<p>Any insights regarding mocking TraceWriter and/or Azure Function unit testing strategies would be much appreciated.</p>
",https://stackoverflow.com/questions/44010514/unit-testing-azure-function-cannot-create-an-instance-of-tracewriter-how-to-mo,"['c#', 'unit-testing', 'azure', 'azure-functions']",3128,TRUE,9,2
Unit testing HttpClientModule in Angular 4.3: undefined return value from HttpTestingController.expectOne(url),"<p>I'm trying to understand how to use the mocking functionality provided as part of the new <code>HttpClientModule</code>. My test code matches what's shown in the existing documentation almost exactly. However, the doc example is not complete - for example, at a minimum the import statement for <code>TestBad</code> and <code>inject</code> is missing. I assume the same is true of <code>HttpClient</code> from @angular/common/http. My test code adds these. </p>

<p>This test fails, as <code>req</code> ends up being undefined after the <code>httpMock.expectOne</code> call. I'd appreciate any insight into why that might be. </p>

<pre><code>import { TestBed, inject } from '@angular/core/testing';
import { HttpClient } from '@angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

describe('HttpClientTestingModule', () =&gt; {
  beforeEach(() =&gt; TestBed.configureTestingModule({
    imports: [ HttpClientTestingModule ],
    providers: [ HttpClient, HttpTestingController]
  }));

  it('expects a GET request', inject([HttpClient, HttpTestingController], (http: HttpClient, httpMock: HttpTestingController) =&gt; {
    http
      .get('/data')
      .subscribe(data =&gt; expect(data['name']).toEqual('Test Data'));

    const req = httpMock.expectOne('/data');
    expect(req).toBeDefined();
    expect(req.request.method).toEqual('GET');
    req.flush({name: 'Test Data'});
    httpMock.verify();
  }));
});
</code></pre>
",https://stackoverflow.com/questions/45446680/unit-testing-httpclientmodule-in-angular-4-3-undefined-return-value-from-httpte,"['angular', 'unit-testing']",4585,TRUE,3,1
Unit testing with database created by Entity Framework with Effort and dbContext,"<p>I am trying to create fake database instance using Effort, but I encountered to a problem. <code>ObjectContextFactory</code> has a <code>CreateTransistent</code> generic method which expects an <code>ObjectContext</code> type to be defined:</p>

<pre><code>public static T CreateTransient&lt;T&gt;( ) where T : ObjectContext;
</code></pre>

<p>So as far as I understand generic types I can define:</p>

<pre><code>class MyObjectContextClass : ObjectContext
{
   //Entity definition here
}
</code></pre>

<p>So I can do following in unit test class:</p>

<pre><code>var effortContext = ObjectContextFactory.CreateTransient&lt;MyObjectContextClass&gt;()
</code></pre>

<p>So far so good, right? But my context class inherits from <code>dbContext</code> class:</p>

<pre><code>class MyRealDbContextClass : DbContext
{
    // Entity definition here
}
</code></pre>

<p>I found that <code>DbContext</code> is a wrapper class and it consist of <code>ObjectContext</code></p>

<p>So my question is: how can I retrieve type of my custom <code>ObjectContext</code> so I can use it in effort static method? I need something like:</p>

<pre><code>var type = MyRealDbContextClass.GetObjectContextType();
</code></pre>

<p>So I can:</p>

<pre><code>var effortContext = ObjectContextFactory.CreateTransient&lt;type&gt;()
</code></pre>
",https://stackoverflow.com/questions/42832065/unit-testing-with-database-created-by-entity-framework-with-effort-and-dbcontext,"['c#', 'entity-framework']",1537,FALSE,2,3
which TDD unit testing framework is best for angular + AEM code base?,"<p>we have a huge E commerce application and the code base is Angular 1.5.8 component based structure on AEM. I am new to TDD but wanted to understand what and how can I proceed to build a TDD framework on application.</p>
",https://stackoverflow.com/questions/41813782/which-tdd-unit-testing-framework-is-best-for-angular-aem-code-base,"['unit-testing', 'tdd', 'aem']",712,TRUE,2,1
Android Unit Testing with Missed Private Method in Jacoco Code Coverage Report,"<p>Hi guys!</p>

<p>I don't have experience in testing but am trying to do it for my current Android practice project.</p>

<p>I have been researching and reading about unit testing on private methods, where people would say we should not be testing them as they are implementations instead of behaviour.</p>

<p>However, by using Jacoco to generate the code coverage report, it would state that certain private method or member variable assignment.</p>

<p>My question is, should I re-write my methods, or should I ignore the report. Or there are other ways to test them.</p>

<p>Thank you.</p>

<p>Screenshot and code:</p>

<p><a href=""https://i.stack.imgur.com/Rtvva.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Rtvva.png"" alt=""enter image description here""></a></p>

<pre><code>public class HNStoriesPresenter&lt;V&gt; implements GetHackerNewsContract.StoriesPresenter {    

private static final String TAG = ""HNStoriesPresenter"";
private GetHackerNewsContract.StoriesView view;
private HackerNewsAPI apiService;
private CompositeDisposable disposables;

private List&lt;HackerNewsStory&gt; hackerNewsStoryList;
private String[] topStoriesID;

// range [0-topStoriesID.length)
private int numStoriesLoaded = 0;

public HNStoriesPresenter(HackerNewsAPI apiService) {
    this.apiService = apiService;
    disposables = new CompositeDisposable();
    hackerNewsStoryList = new ArrayList&lt;&gt;();
}

public void setView(V view){
    this.view = (GetHackerNewsContract.StoriesView) view;
    this.loadTopStories();
}

@Override
public void loadTopStories() {
    // Reset this variable to load stories from start (first page)
    numStoriesLoaded = 0;
    hackerNewsStoryList.clear();

    apiService.getTopStories()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(storiesID -&gt; {
                    topStoriesID = storiesID;
                    pullStories();
                },
                error -&gt; view.onFecthStoriesError());
}

@Override
public void loadMoreStories() {
    pullStories();
}

// Function to load NUMBER_OF_STORIES_TO_DISPLAY individual story item
private void pullStories() {
    // Remove previous stories
    hackerNewsStoryList.clear();
    //((GetHackerNewsContract.StoriesView) view).clearStories();

    // Counter to limit total stories to load
    int currentLoaded = 0;
    int start = numStoriesLoaded;
    List&lt;String&gt; storiesToPullList = new ArrayList&lt;&gt;();

    while (numStoriesLoaded &lt; topStoriesID.length &amp;&amp; currentLoaded &lt; NUMBER_OF_STORIES_TO_DISPLAY) {
        // Get story item from server
        storiesToPullList.add(topStoriesID[numStoriesLoaded]);
        numStoriesLoaded++;
        currentLoaded++;
    }

    // Use flatMap to ensure the order of items received
    // is same as the list (synchronized).

    // This makes the API call visibly slow. There could
    // be better way but stick with this method for now.
    Single&lt;List&lt;HackerNewsStory&gt;&gt; storiesObservable = Observable.fromIterable(storiesToPullList)
            .flatMap(id -&gt; apiService.getStory(id)).toList();

    storiesObservable
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(loadStoriesHandler,
                    error -&gt; view.onFecthStoriesError()
            );

                    //HNStoriesPresenter.this.loadStoriesHandler, HNStoriesPresenter.this.singleErrorHandler);
}

private Consumer&lt;List&lt;HackerNewsStory&gt;&gt; loadStoriesHandler = new Consumer&lt;List&lt;HackerNewsStory&gt;&gt;() {
    @Override
    public void accept(List&lt;HackerNewsStory&gt; hackerNewsStories) throws Exception {
        hackerNewsStoryList.clear();
        hackerNewsStoryList.addAll(hackerNewsStories);

        if (hackerNewsStoryList.size() &gt; 0)
            view.onFetchStoriesSuccess(hackerNewsStoryList);
        else
            view.onFecthStoriesError();

        if (numStoriesLoaded &lt; topStoriesID.length)
            view.showLoadMore();
        else
            view.hideLoadMore();
    }
};
}
</code></pre>
",https://stackoverflow.com/questions/47323042/android-unit-testing-with-missed-private-method-in-jacoco-code-coverage-report,"['android', 'unit-testing', 'mockito', 'code-coverage', 'jacoco']",239,FALSE,2,0
How to get away with NPE for @Inject field while unit testing?,"<p>Im writing unit tests for the below code, Im getting NPE even though Im mocking the fields, How can I resolve that. Those fields are present with @Inject annotation</p>

<pre><code>@Component
interface A {
    void run();
}

class B {
    @Inject
    A a;

    void someMethod() {
        a.run();
    }}

class C{
    @Inject
    B b;

    void anotherMethod() {
        b.someMethod();
    }
}

class CTest {
    @Mock
    B b;
    // remains null when invoked in the actual class though its mocked instance is
    // present here

    @Mock
    A a;
    //// remains null when invoked in the actual class though its mocked instance
    //// is present here

    @InjectMocks
    C c;

    @Before
    public void initialize() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void test() {
        c.anotherMethod();
    }

}
</code></pre>

<p>So how can I get the mocked value in the actual class where the field is injected with @Inject using Mockito?</p>
",https://stackoverflow.com/questions/43504734/how-to-get-away-with-npe-for-inject-field-while-unit-testing,"['java', 'unit-testing', 'junit', 'mockito', 'inject']",375,TRUE,2,1
JVM unit testing with Mockito for testing Retrofit2 and RxJava for network requests,"<pre><code>Android Studio 2.3 RC 1
</code></pre>

<p>I am using the MVP architecture and want to run JVM unit tests.</p>

<p>In my Model I am using Retrofit2 and RxJava to fetch movies from a API. I want to test the function <code>getPopularMovies(...)</code> However, this function will make a call to the webserver. However, in the test I want to mock this somehow and just test the <code>onSuccess()</code> and <code>onFailure()</code> methods are called.</p>

<p>My model class looks like this snippet only to keep it short:</p>

<pre><code>public class MovieListModelImp implements MovieListModelContract {

    @Override
    public void getPopularMovies(PopularMovieResultsListener popularMovieResultsListener) {
        mSubscription = mMovieAPIService.getPopular(Constants.MOVIES_API_KEY)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber&lt;Results&gt;() {
            @Override
            public void onCompleted() {
                Timber.d(""onCompleted"");
            }

            @Override
            public void onError(Throwable e) {
                Timber.e(e, ""onError"");
                popularMovieResultsListener.onFailure(e.getMessage());
            }

            @Override
            public void onNext(Results results) {
                Timber.d(""onNext %d"", results.getResults().size());
                popularMovieResultsListener.onSuccess(results);
            }
        });
    }
}
</code></pre>

<p>And the interface:</p>

<pre><code>public interface MovieListModelContract {
    interface PopularMovieResultsListener {
        void onFailure(String errorMessage);
        void onSuccess(Results popularMovies);
    }
    void getPopularMovies(PopularMovieResultsListener popularMovieResultsListener);
}
</code></pre>

<p>My problem I am trying to solve is how can I use Mockito to test the <code>getPopularMovies</code> without actually calling the network service? I just want to test that:
<code>popularMoviesResultsListener.onFailure(e.getMessage())</code> will be called on failure to get movies
and 
<code>popularMovieResultsListener.onSuccess(results);</code> will be called on success when movies are recieved</p>

<p>I have a test like this but I am not sure if this is correct:</p>

<pre><code>@Test
public void shouldDisplaySuccessWhenNetworkSucceeds() {
    /* Results is the movie results class that is returned */
    Results results = new Results();

    /* Mock the listener */
    MovieListModelContract.PopularMovieResultsListener mockPopularMoviesResultsListener =
            Mockito.mock(MovieListModelContract.PopularMovieResultsListener.class);

    /* Real instance of the model */
    MovieListModelImp movieListModelImp = new MovieListModelImp();

    /* Call getPopularMovies with mock listener - However, this will still make a real network request */
    movieListModelImp.getPopularMovies(mockPopularMoviesResultsListener);

    /* Verify - but I think I have got this all wrong */
    verify(mockPopularMoviesResultsListener, times(1)).onSuccess(results);
}
</code></pre>

<p>So my problem is how can I mock a call to a network request and test the expected onSuccess() and onFailure() is working correctly?</p>
",https://stackoverflow.com/questions/42445665/jvm-unit-testing-with-mockito-for-testing-retrofit2-and-rxjava-for-network-reque,"['android', 'mockito', 'rx-java', 'retrofit2']",2831,TRUE,7,2
C# MVC Model is always valid when Unit Testing a Controller Action,"<p>I am very beginner in this C# world.</p>

<p>There is this model class:</p>

<pre><code>    public class Fund
    {
        [Required]
        public int id { get; set; }
        [Required]
        public string name { get; set; }
        [Required]
        public string nickname { get; set; }
    }
</code></pre>

<p>Although the <code>[Required]</code> annotation is over all properties, an instance like:</p>

<pre><code>Fund f = new Fund();
f.name = ""test name"";
f.nickname = ""test ninckname"";
</code></pre>

<p>always pass in a test like:</p>

<pre><code>if (ModelState.IsValid)
{
    // do stuff
}
</code></pre>

<p>How am I supposed to set the model such that an instance like that won't pass in in the <code>ModelState.IsValid</code> test?</p>

<p>Other instances like:</p>

<pre><code>Fund f1 = new Fund();
f1.id = 3;
f1.nickname = ""test ninckname"";
</code></pre>

<p>and</p>

<pre><code>Fund f2 = new Fund();
f2.id = 3;
f2.name = ""test name"";
</code></pre>

<p>are also passing on the test.</p>

<p><strong>EDIT:</strong></p>

<p>The <code>ModelState.IsValid</code> is inside a controller, I am testing the controller actually.</p>

<p><strong>EDIT 2:</strong></p>

<p>That is the controller's method signature:</p>

<pre><code>[HttpPatch]
public ActionResult EditFund(Fund fund)
</code></pre>

<p><strong>EDIT 3:</strong>
That is my whole test method:</p>

<pre><code>[TestMethod]
public void TestEditInvalidFund()
{
    // Arrange
    FundController controller = new FundController();
    controller.ControllerContext = TestModelHelper.AdminControllerContext();
    var _fund = new Mock&lt;IFund&gt;();
    _fund.SetupGet(f =&gt; f.id).Returns(1);
    //_fund.SetupGet(f =&gt; f.name).Returns(""Fund name"");
    _fund.SetupGet(f =&gt; f.nickname).Returns(""Fund nickname"");
    _fund.Setup(f =&gt; f.Edit()).Callback(() =&gt; {}).Verifiable();

    // Act
    var result = (JsonResult)controller.EditFund(_fund.Object);

    // Assert
    SimpleMessage resultMessage = m_serializer.Deserialize&lt;SimpleMessage&gt;(m_serializer.Serialize(result.Data));
    Assert.IsNotNull(resultMessage.status, ""JSON record does not contain 'status' required property."");
    Assert.IsTrue(resultMessage.status.Equals(""fail""), ""status must be 'fail'"");
}
</code></pre>

<p>And that is the whole controller's method:</p>

<pre><code>[HttpPatch]
public ActionResult EditFund(IFund _fund)
{
    try
    {
        if (ModelState.IsValid)
        {
            //_fund.Edit();
        }
        else
        {
            string error_messages = """";
            foreach (var e in ModelState.Select(x =&gt; x.Value.Errors).Where(y =&gt; y.Count &gt; 0).ToList())
            {
                error_messages += e[0].ErrorMessage + ""\n"";
            }
            throw new Exception(error_messages);
        }
        return MessageHelper(@Resources.Global.success, @Resources.Funds.success_editing_fund, ""success"");
    }
    catch (Exception err)
    {
        return ErrorHelper(@Resources.Global.error, @Resources.Funds.error_editing_fund, err.Message);
    }
}
</code></pre>
",https://stackoverflow.com/questions/41882876/c-mvc-model-is-always-valid-when-unit-testing-a-controller-action,"['c#', 'asp.net-mvc', 'unit-testing', 'nunit']",777,TRUE,1,3
Assembly reference issue while unit testing as part of CI using TFS,"<p>We have setup a unit test project for testing a c# class library. the c# class library has a reference to enterprise libary. The unit test executes fine while building using Visual studio. But when it is executed using TFS as part of CI, it fails due to missing assembly refernce to enterprise library.  But when we register the enterprise libary in build server GAC, it works fine.</p>

<p>How do we make sure that during CI unit testing, the assembly referred is not GAC but is the local copy. Trying to avoid registering all referred assemblies to gac</p>
",https://stackoverflow.com/questions/42075228/assembly-reference-issue-while-unit-testing-as-part-of-ci-using-tfs,"['unit-testing', 'tfs', 'continuous-integration']",115,TRUE,1,1
How to call model&#39;s validate method in Yii2 unit testing using Mockbuilder?,"<p>I am new to codeception and unit testing. I am creating some test cases for my Yii2 basic app using build in codeception module.</p>

<p>I am creating a test case for change password module. I created a mock of change password model. However i am not able to call model's validate method using that mock</p>

<p>Here is my code:</p>

<pre><code> public function testRepeatPassword()
{
    $this-&gt;model = $this-&gt;getMockBuilder('app\models\ChangePasswordForm')
                -&gt;setMethods(['validatePassword'])
                -&gt;getMock();

    $this-&gt;model-&gt;expects($this-&gt;once())
        -&gt;method('validatePassword')
        -&gt;will($this-&gt;returnValue(true));

    $this-&gt;model-&gt;attributes = [
        'old_password' =&gt; 'OldPassword',
        'new_password' =&gt; 'NewPassword',
        'password_repeat' =&gt; 'NewPassword'
    ];


    expect_that($this-&gt;model-&gt;validate());
}
</code></pre>

<p>This is the error i am getting:</p>

<pre><code>PHP Fatal error:  Call to undefined method Mock_ChangePasswordForm_09a6c2a3::validate() in /var/www/html/concept_HIS/tests/unit/models/ChangePasswordTest.php on line 92
</code></pre>

<pre>PHP Fatal Error &#039;yii\base\ErrorException&#039; with message &#039;Call to undefined method Mock_ChangePasswordForm_09a6c2a3::validate()&#039; 

in /var/www/html/concept_HIS/tests/unit/models/ChangePasswordTest.php:92

Stack trace:
#0 [internal function]: yii\base\ErrorHandler-&gt;handleFatalError()
#1 {main}</pre>

<p>Isn't it possible to call model's validate method using mock object?</p>
",https://stackoverflow.com/questions/44753400/how-to-call-models-validate-method-in-yii2-unit-testing-using-mockbuilder,"['php', 'unit-testing', 'yii', 'yii2', 'codeception']",428,FALSE,1,0
Count the number of child components by tag name in angular2 unit testing,"<p>I have a parent component which will dynamically insert the child components based on the length of array. I want to test the number of components created, by using its tag name.</p>

<pre><code>&lt;div *ngFor = ""let item of phoneList; let i = index""&gt;
    &lt;phone-item [item]=""item""&gt; &lt;/phone-item&gt;
&lt;/div&gt;
</code></pre>

<p>I want to verify the number of <code>&lt;phone-item&gt;&lt;/phone-item&gt;</code> created within the html template in angular2 unit testing.</p>

<p>I have very little knowledge on debugElement and nativeElement. This is what I have tried to do. </p>

<pre><code>let el = fixture.debugElement.query(By.css('phone-item'));
</code></pre>

<p>But I want the count of child components created.</p>
",https://stackoverflow.com/questions/43204819/count-the-number-of-child-components-by-tag-name-in-angular2-unit-testing,"['javascript', 'unit-testing', 'angular', 'jasmine']",6298,TRUE,6,1
Unit testing tornado applications: How to improve the display of error messages,"<p>I am using unittest to test a tornado app having several handlers, one of which raises an exception. If I run the following test code with <code>python test.py</code>:</p>

<pre><code># test.py

import unittest
import tornado.web
import tornado.testing

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write('Hello World') # handler works correctly

class HandlerWithError(tornado.web.RequestHandler):
    def get(self):
        raise Exception('Boom') # handler raises an exception
        self.write('Hello World')

def make_app():
    return tornado.web.Application([
        (r'/main/', MainHandler),
        (r'/error/', HandlerWithError),
    ])

class TornadoTestCase(tornado.testing.AsyncHTTPTestCase):

    def get_app(self):
        return make_app()

    def test_main_handler(self):
        response = self.fetch('/main/')
        self.assertEqual(response.code, 200) # test should pass

    def test_handler_with_error(self):
        response = self.fetch('/error/')
        self.assertEqual(response.code, 200) # test should fail with error

if __name__ == '__main__':
    unittest.main()
</code></pre>

<p>the test output looks like:</p>

<pre><code>ERROR:tornado.application:Uncaught exception GET /error/ (127.0.0.1)                                                                                                                   
HTTPServerRequest(protocol='http', host='localhost:36590', method='GET', uri='/error/', version='HTTP/1.1', remote_ip='127.0.0.1', headers={'Connection': 'close', 'Host': 'localhost:3
6590', 'Accept-Encoding': 'gzip'})                                                                                                                                                     
Traceback (most recent call last):                                                                                                                                                     
  File ""/usr/local/lib/python2.7/dist-packages/tornado/web.py"", line 1332, in _execute                                                                                                 
    result = method(*self.path_args, **self.path_kwargs)                                                                                                                               
  File ""test.py"", line 13, in get                                                                                                                                                      
    raise Exception('Boom') # handler raises an exception                                                                                                                              
Exception: Boom                                                                                                                                                                        
ERROR:tornado.access:500 GET /error/ (127.0.0.1) 19.16ms                                                                                                                               
F.                                                                                                                                                                                     
======================================================================                                                                                                                 
FAIL: test_handler_with_error (__main__.TornadoTestCase)                                                                                                                               
----------------------------------------------------------------------                                                                                                                 
Traceback (most recent call last):                                                                                                                                                     
  File ""/usr/local/lib/python2.7/dist-packages/tornado/testing.py"", line 118, in __call__                                                                                              
    result = self.orig_method(*args, **kwargs)                                                                                                                                         
  File ""test.py"", line 33, in test_handler_with_error                                                                                                                                  
    self.assertEqual(response.code, 200) # test should fail with error                                                                                                                 
AssertionError: 500 != 200                                                                                                                                                             

----------------------------------------------------------------------                                                                                                                 
Ran 2 tests in 0.034s                                                                                                                                                                  

FAILED (failures=1)       
</code></pre>

<p>However, I would expect unittest to report an Error for the second test, instead of a failing assertion. Moreover, the fact that the traceback for the 'Boom' exception appears before the unittest test report and does not include a reference to the failing test function makes it difficult to find the source of the exception.</p>

<p>Any suggestions how to handle this situation?</p>

<p>Thanks in advance!</p>

<p><em>EDIT</em></p>

<p>What I find unexpected is the fact that <code>test_handler_with_error</code> actually arrives at making the <code>assertEqual</code> assertion, instead of throwing the error. For example, the following code does not execute the <code>self.assertEqual</code>statement, and consequently reports an <code>ERROR</code> instead of a <code>FAIL</code> in the test output:</p>

<pre><code># simple_test.py
import unittest

def foo():
    raise Exception('Boom')
    return 'bar'

class SimpleTestCase(unittest.TestCase):
    def test_failing_function(self):
        result = foo()
        self.assertEqual(result, 'bar')

if __name__ == '__main__':
    unittest.main()
</code></pre>
",https://stackoverflow.com/questions/42551015/unit-testing-tornado-applications-how-to-improve-the-display-of-error-messages,"['python', 'unit-testing', 'tornado']",1120,TRUE,1,2
"The Following Setups were Not Matched, WPF MVVM Unit Testing with Moq","<p>I am writing a unit test in <strong>WPF</strong> with <strong>Moq</strong> to test whether or not a user clicked the ""Yes"" button on a <code>YesNoCancel</code> MessageBox when they are closing the window.  In my <code>CloseCommand</code> I have in my ViewModel gives the following message when the user is closing the window:</p>

<pre><code>var result = _messageSvc.Show(
    ""Do you want to save changes?"",
    ""Save Changes"", 
    Services.MessageBoxButton.YesNoCancel,
    Services.MessageBoxIcon.Question, 
    Services.MessageBoxResult.Yes);
</code></pre>

<p>My <code>_messageSvc</code> is a private instance inside of a custom Messaging service to display messageboxes.  Here is the code for the service:</p>

<pre><code>public interface IMessageSvc
{
    void Show(string message);
    MessageBoxResult Show(string message, string caption, MessageBoxButton buttons, MessageBoxIcon icon, MessageBoxResult defaultResult = 0);
}

public class MessageSvc : IMessageSvc
{
    public void Show(string message)
    {
        MessageBox.Show(message);
    }

    public MessageBoxResult Show(string message, string caption, MessageBoxButton buttons, MessageBoxIcon icon, MessageBoxResult defaultResult)
    {
        return (MessageBoxResult)MessageBox.Show(message, caption, (System.Windows.MessageBoxButton)buttons, (System.Windows.MessageBoxImage)icon, (System.Windows.MessageBoxResult)defaultResult);
    }
}
</code></pre>

<p>Note: <code>MessageBoxButton</code>, <code>MessageBoxIcon</code>, and <code>MessageBoxResult</code> are enumerations I made in the same file to mimic what .NET provides out of the box.  I am not showing them here for sake of readability</p>

<p>My unit test is:</p>

<pre><code>[TestMethod]
public void ShouldAskToSaveOnCloseRespondYesTest()
{
    // Mock and setup initial user data 
    var u= new User
    {
        UserId = 1,
        UserName = ""FirstName LastName"",
        FavoriteColor = ""Blue""
    };
    mainViewModel.UserInfo= new UserInfoDtoWrapper(u);

    // assert the data has not changed yet
    Assert.IsFalse(mainViewModel.UserInfo.IsChanged);

    // change the user data
    mainViewModel.UserInfo.UserName= ""LastName FirstName"";

    // assert the data has changed
    Assert.IsTrue(mainViewModel.UserInfo.IsChanged);

    // execute window closing
    mainViewModel.CloseCommand.Execute(new object());

    // verify messagebox shows and the 'Yes' button is clicked
    // this will then save the changes made to the user instance
    var messageBox = new Mock&lt;IMessageSvc&gt;();
    messageBox.Setup(x =&gt; x.Show(It.Is&lt;string&gt;(y =&gt; y == ""Do you want to save changes?""),
        It.Is&lt;string&gt;(y =&gt; y == ""Save Changes""),
        It.Is&lt;MessageBoxButton&gt;(y =&gt; y == MessageBoxButton.YesNoCancel),
        It.Is&lt;MessageBoxIcon&gt;(y =&gt; y == MessageBoxIcon.Question),
        It.Is&lt;MessageBoxResult&gt;(y =&gt; y == MessageBoxResult.Yes)))
        .Returns(MessageBoxResult.Yes);

    messageBox.Verify();
}
</code></pre>

<p>The error comes on the <code>messageBox.Verify()</code> line, but from what I can see I am doing it correctly.  I need to get the return value of the messagebox to continue testing what happens after the user clicks the ""Yes"" button, so I did not want to use <code>Verify</code> with a Linq query inside, instead I need to capture the result.</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/45883759/the-following-setups-were-not-matched-wpf-mvvm-unit-testing-with-moq,"['c#', 'wpf', 'unit-testing', 'mvvm', 'moq']",1470,TRUE,1,2
Visual Studio for Mac for Mobile Devices (Xamarin) - C# Automated Unit Testing,"<p>It seems really bizarre that Visual Studio for Mac (the recently-renamed Xamarin Studio) doesn't support automated unit testing for their mobile device (Android/iOS) applications.  Actually, I guess it isn't that bizarre, they REALLY want you to pay for their cloud testing service.</p>

<p>How can I run my own automated unit tests, on my own machine?  Here's what I mean by that - I want to create an application that:</p>

<ol>
<li>Contains C# files containing unit tests that require NO user interface</li>
<li>Can be invoked from my Jenkins or Hudson automated build server</li>
<li>Can run on either a physical iDevice attached to the build server, or the iPad simulator</li>
<li>Runs all unit tests, reports their pass/fail status back to the build server, and then exits, all without any human intervention.</li>
</ol>

<p>It seems like I could do this on the simulator using</p>

<pre><code>xcrun simctl spawn
</code></pre>

<p>and then either</p>

<ol>
<li>Have my test app writes its output to its storage and figure out where on my Mac's hard disk the simulator storage lives, or</li>
<li><p>Have my test app send its output to the simulator's pasteboard and grab it using</p>

<pre><code>xcrun simctl pbpaste
</code></pre></li>
</ol>

<p>But these both require that I find a way to write a C# app that runs on iOS, runs my tests, stores the output where the ""real world"" can find it, and then shuts down.</p>

<p>And I have to figure out how to copy all of the necessary EXEs and DLLs over to the simulated iPad?  Or have Visual Studio package it all into an actual Mac app?</p>
",https://stackoverflow.com/questions/44814067/visual-studio-for-mac-for-mobile-devices-xamarin-c-automated-unit-testing,"['visual-studio', 'unit-testing', 'xamarin', 'jenkins', 'xamarin.ios']",792,TRUE,1,1
How to induce an exception thrown when unit testing a simple method,"<p>I have a service call wrapper that does nothing but forwards the parameter to a service in a call. The reason for the wrapper is so we can have the Wrapper Injected using a DI container and thus mocked for unit testing.</p>

<p>Here is how the wrapper looks like</p>

<pre><code>public class WeatherChannelWrapper : IWeatherServiceWrapper
{
    public GetLocalWeather(string zipcode)
    {
        TWCProxy.GetCurrentCondition(zipcode, DateTime.Now.ToString(""MM/dd/yyyy hh:mm""));
    }
}
</code></pre>

<p>Everything works fine, now I have a requirement to swallow exceptions on TWCProxy's crashes. So now my wrapper looks like this.</p>

<pre><code>public class WeatherChannelWrapper : IWeatherServiceWrapper
{
    private readonly IExceptionLogger exceptionLogger;

    public WeatherChannelWrapper(IExceptionLogger logger)
    {
        this.exceptionLogger = logger;
    }
    public GetLocalWeather(string zipcode)
    {
        try 
        {
            TWCProxy.GetCurrentCondition(zipcode, DateTime.Now.ToString(""MM/dd/yyyy hh:mm""));
        }
        catch (Exception e)
        {
            exceptionLogger.Log(e);
        }
    }
}
</code></pre>

<p>I have to write the following Unit Tests</p>

<ol>
<li>GetLocalWeather() does not crash the application when an internal exception occurs</li>
<li>GetLocalWeather() logs exceptions </li>
</ol>

<p>Now to test both scenarios, I need to somehow induce a crash; how do I do that using NUnit and Automoq/Moq?</p>
",https://stackoverflow.com/questions/45358738/how-to-induce-an-exception-thrown-when-unit-testing-a-simple-method,"['c#', 'unit-testing', 'dependency-injection', 'moq', 'automoq']",2037,TRUE,1,2
How to use Karma and Jest together in unit testing React application?,"<p>I am testing a React application already developed. The application has some unit test cases written in Karma but I am going to use Jest to unit test the application as it is the new framework, developed by facebook for testing React. The problem I am facing is because of file <code>.babelrc</code>. For Jest to run fine the content of .babelrc file should be as follows:</p>

<pre><code>// .babelrc
{
  ""presets"": [""es2015"", ""react""]
}
</code></pre>

<p>But my existing application uses Karma and has the babelrc file content as below:</p>

<pre><code>{
  ""presets"": [
   ""es2015"",
    ""react"",
    ""stage-0""
  ]
, ""plugins"": [
    ""transform-object-rest-spread""
  , ""transform-decorators-legacy""
  , ""transform-es2015-modules-amd""
  ]
}
</code></pre>

<p>The current <code>babelrc</code> file  is not allowing Jest to run properly and causes error. But the thing is I cant modify its content as required by Jest since it will hamper my Karma test cases to stop running. Is there a way I can use the both at same time until i rewrite existing test cases in Jest?</p>
",https://stackoverflow.com/questions/45674936/how-to-use-karma-and-jest-together-in-unit-testing-react-application,"['reactjs', 'karma-runner', 'babeljs', 'enzyme', 'jestjs']",1416,TRUE,1,1
Simple Unit Testing - Parse Invalid Input To Throw Error C# Visual Studio,"<p>I have a very basic method that divides two double values.
For unit testing I want to include a invalid input (string) to throw error message or exception. What is most simple way to parse the value or fail the test (expected)?</p>

<p>CalculatorClass.cs</p>

<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Calculator
{
    public class CalculatorClass
    {
        //METHODS
        public double Divide(double num1, double num2)
        {
            double result = num1 / num2;
            return result;
        }
    }
}
</code></pre>

<p>UnitTest1.cs</p>

<pre><code>using System;
using Calculator; //ADD REFERENCE
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace CalcMethodTest
{
    //AreEqual
    //AreNotEqual
    //AreNotSame
    //AreSame
    //Equals
    //Fail
    //Inconclusive
    //IsFalse
    //IsInstanceOfType
    //IsNotNull
    //IsNull
    //IsTrue
    //ReplaceNullChars

    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void _1_3_Test_Divide_Input_Seven_2_Output_Error()
        {
            //ARRANGE
            CalculatorClass calcObj = new CalculatorClass();
            string expectedOutput = ""Error - Invalid Input"";
            //ACT

            //----HERE WRONG DATA TYPE FOR TESTING----
            double result = calcObj.Divide(""Seven"", 2);
            //ASSERT
            Assert.AreEqual(expectedOutput, result);
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/43795909/simple-unit-testing-parse-invalid-input-to-throw-error-c-visual-studio,"['c#', 'visual-studio', 'unit-testing', 'parsing', 'methods']",1837,TRUE,1,4
TDD Test first Nodejs express Rest Api - unit testing middlewere / controllers / routes,"<p>I'm trying to figure out how to test first my node js rest api app.
so far i've been using <a href=""https://github.com/node-nock/nock"" rel=""nofollow noreferrer"">nock</a> to intercept and mock any http call and by that test my service as a component. (component testing?)
i want to start unit testing my app so my test pyramid is more balanced and tests will be easier to write.</p>

<p>searching the web i got to this approach:
<a href=""http://www.slideshare.net/morrissinger/unit-testing-express-middleware"" rel=""nofollow noreferrer"">http://www.slideshare.net/morrissinger/unit-testing-express-middleware</a></p>

<pre><code>var middleware = require('./middleware');
app.get('example/uri', function (req, res, next) {
  middleware.first(req, res)
    .then(function () { next(); })
    .catch(res.json)
    .done();
}, function (req, res, next) {
  middleware.second(req, res)
    .then(function () { next(); })
    .catch(res.json)
    .done();
});
</code></pre>

<p>(basicly pulling the middleware out and testing it)</p>

<p>since this presentation is from 2014 i was wondering what are the current up to date methods for unit testing express apps?</p>
",https://stackoverflow.com/questions/42329054/tdd-test-first-nodejs-express-rest-api-unit-testing-middlewere-controllers,"['node.js', 'unit-testing', 'express', 'tdd']",550,TRUE,1,1
Why Jest (JavaScript framework for unit testing) does not work with `this`?,"<pre><code>class Test {
  static Test1 () { console.log(this); this.Test2();  }
  static Test2 () { console.log('qwe'); }
}

Test.Test1();

export default Test;
export const Test1 = Test.Test1;
</code></pre>

<p>Compiled with BabelJS with ES2015 preset. With <code>node</code> the compiled code runs fine. But within unit test <code>this</code> is <code>undefined</code>. Why this happens?</p>
",https://stackoverflow.com/questions/47415568/why-jest-javascript-framework-for-unit-testing-does-not-work-with-this,"['ecmascript-6', 'babeljs', 'jestjs']",58,TRUE,-1,1
ASP.NET Web API Unit Testing - Read Json string from controller returning JsonResult,"<p>I have a controller method which returns <strong>JsonResult</strong> (Namespace:   <code>System.Web.Http.Results</code>
)</p>

<pre><code>        public async Task&lt;IHttpActionResult&gt; GetConfig(string section, string group, string name)
        {
            var configurations = await _repository.GetConfig(section, group, name);
            return Json(new { configurations = configurations.ToList() }, SerializerSettings);
        }
</code></pre>

<p>I am trying to Unit Test this method.Here is what I have so far</p>

<pre><code>        [Test]
        public async void Should_Return_List_Of_Configs_Json()
        {
            var section= ""ABC"";
            var group= ""some group"";
            var name= ""XYZ"";
            var response =  await controller.GetConfig(section, group, name);
            Assert.IsNotNull(response);

        }
</code></pre>

<p>I am not able to read <code>Json</code> string from the above method as I can't see a <code>response.Content</code> property.The call to the method is returning mocked response.</p>

<p>Can someone help me out with this?</p>
",https://stackoverflow.com/questions/44561089/asp-net-web-api-unit-testing-read-json-string-from-controller-returning-jsonre,"['c#', 'json', 'unit-testing', 'asp.net-web-api']",616,FALSE,0,2
Unit testing in Apache Storm - timeout with BaseRichBolt but not with BaseBasicBolt,"<p>I'm trying to implement unit tests for Storm bolts (Java). The code below works fine and ends with a success on Storm 1.0.3:</p>

<p><code>Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.887 sec</code></p>

<p>However, when I change <code>BaseBasicParrotBolt</code> on line 46 to <code>BaseRichParrotBolt</code>, the assertions never run and it ends with the following exception:</p>

<p><code>13610 [main] ERROR o.a.s.testing4j - Error in cluster java.lang.AssertionError: Test timed out (10000ms) (not (every? exhausted? (spout-objects spouts)))</code></p>

<p>If you step through it with a debugger you'll see that the bolt does receive and emit tuples, but it seems like <code>Testing.completeTopology</code> never returns. I find this really odd because the bolts are virtually the same. All my bolts extend from <code>BaseRichBolt</code> so I'd really like to make it work for those as well. Any ideas?</p>

<pre><code>import java.util.Map;
import org.apache.storm.Config;
import org.apache.storm.ILocalCluster;
import org.apache.storm.Testing;
import org.apache.storm.generated.StormTopology;
import org.apache.storm.spout.SpoutOutputCollector;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.testing.CompleteTopologyParam;
import org.apache.storm.testing.MkClusterParam;
import org.apache.storm.testing.MockedSources;
import org.apache.storm.testing.TestJob;
import org.apache.storm.topology.BasicOutputCollector;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.TopologyBuilder;
import org.apache.storm.topology.base.BaseBasicBolt;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.topology.base.BaseRichSpout;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;
import java.util.Arrays;
import java.util.List;
import static junit.framework.Assert.*;
import org.junit.Test;

public class StormTestExample {
    private final static String EVENT = ""event"";
    private final static String SPOUT_ID = ""spout"";
    private final static String BOLT_ID = ""parrot"";
    private final static List&lt;String&gt; COMPONENT_IDS = Arrays.asList(SPOUT_ID, BOLT_ID);

    @Test
    public void testBasicTopology() {
        MkClusterParam mkClusterParam = new MkClusterParam();
        mkClusterParam.setSupervisors(4);
        Config daemonConf = new Config();
        daemonConf.put(Config.STORM_LOCAL_MODE_ZMQ, false);
        mkClusterParam.setDaemonConf(daemonConf);

        Testing.withSimulatedTimeLocalCluster(mkClusterParam, new TestJob() {
            @Override
            public void run(ILocalCluster cluster) {
                TopologyBuilder builder = new TopologyBuilder();
                builder.setSpout(SPOUT_ID, new TestSpout());
                builder.setBolt(BOLT_ID, new BaseBasicParrotBolt()).shuffleGrouping(SPOUT_ID);
                StormTopology topology = builder.createTopology();

                MockedSources mockedSources = new MockedSources();
                mockedSources.addMockData(SPOUT_ID, 
                        new Values(""nathan""),
                        new Values(""bob""), 
                        new Values(""joey""), 
                        new Values(""nathan""));

                Config conf = new Config();
                conf.setNumWorkers(2);

                CompleteTopologyParam completeTopologyParam = new CompleteTopologyParam();
                completeTopologyParam.setMockedSources(mockedSources);
                completeTopologyParam.setStormConf(conf);

                final Map result = Testing.completeTopology(cluster, topology, completeTopologyParam);

                final Values expected = new Values(new Values(""nathan""), new Values(""bob""), new Values(""joey""), 
                        new Values(""nathan""));

                for (String component : COMPONENT_IDS) {
                    assertTrue(""Error in "" + component + "" output"", 
                               Testing.multiseteq(expected, Testing.readTuples(result, component)));
                }
            }
        });
    }

    private static class TestSpout extends BaseRichSpout {    
        @Override
        public void declareOutputFields(OutputFieldsDeclarer ofd) {
            ofd.declare(new Fields(EVENT));
        }

        @Override
        public void open(Map map, TopologyContext tc, SpoutOutputCollector soc) {
            throw new UnsupportedOperationException(); // Don't need an implementation to run the test.
        }

        @Override
        public void nextTuple() {
            throw new UnsupportedOperationException(); // Don't need an implementation to run the test.
        }
    }

    private static class BaseBasicParrotBolt extends BaseBasicBolt {    
        @Override
        public void declareOutputFields(OutputFieldsDeclarer ofd) {
            ofd.declare(new Fields(EVENT));
        }

        @Override
        public void execute(Tuple tuple, BasicOutputCollector boc) {
            boc.emit(new Values(tuple.getValue(0)));
        }
    }

     private static class BaseRichParrotBolt extends BaseRichBolt {
        private OutputCollector oc;

        @Override
        public void declareOutputFields(OutputFieldsDeclarer ofd) {
            ofd.declare(new Fields(EVENT));
        }

        @Override
        public void prepare(Map map, TopologyContext tc, OutputCollector oc) {
            this.oc = oc;
        }

        @Override
        public void execute(Tuple tuple) {
            oc.emit(new Values(tuple.getValue(0)));
        }
     }
}
</code></pre>
",https://stackoverflow.com/questions/42491555/unit-testing-in-apache-storm-timeout-with-baserichbolt-but-not-with-basebasicb,"['java', 'apache-storm']",596,TRUE,0,1
Spring JDBC throws an error which impacted my Spring related unit testing,"<p>I am working on Spring Boot Rest Controller and everything is working fine including its unit testing.</p>

<p>When I added the Spring-jdbc(4.3.5.RELEASE) in my maven configuration, all my unit test classes are failing due to a null pointer exception. And if I remove it all my spring related unit testing classes are working fine again.</p>

<p>I have been using Spring so many years but this is the first time I have encountered this issue. </p>

<p>What is the root cause? I am using Spring boot 1.4.2.</p>

<p>Code:</p>

<pre><code>@Test
public void verifyEmail() throws Exception {           
    mockServer.expect(requestTo(""localhost:8080//api/v1/userEmails?email=test@test.com&amp;catalogId=10051""))
        .andExpect(method(HttpMethod.GET))
        .andRespond(withSuccess(""True"", MediaType.APPLICATION_JSON));

    String s = acquisitionService.verifyEmail(""test@test.com"",""10051"");

    mockServer.verify();

    assertEquals(""Assert Status"", s, ""True"");                
}
</code></pre>

<p>Error Stack trace:</p>

<pre class=""lang-none prettyprint-override""><code>java.lang.NullPointerException
    at org.dmc.api.service.AcquisitionServiceImpl.getOrderConfirmData(AcquisitionServiceImpl.java:461)
    at org.dmc.api.service.AcquisitionServiceTest.orderConfirmDataTest(AcquisitionServiceTest.java:547)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
</code></pre>
",https://stackoverflow.com/questions/45043006/spring-jdbc-throws-an-error-which-impacted-my-spring-related-unit-testing,"['java', 'spring', 'spring-mvc', 'jdbc', 'nullpointerexception']",39,FALSE,0,0
"Can we verify, no excpetion occured in a method from unit testing","<blockquote>
  <p>ATest.java -
  Can we verify, when no exception occurred in a testdisplay2() method like we use expected  when some exception occurred in testdisplay1()</p>
</blockquote>

<pre><code>class A{
  public void display(){
    ...
    ...
    ...
    if(a){
     throw new AIsTrueException(""a true"");
    }

    if(b){
     throw new BIsTrueException(""b true"");
    }

  }
}

class BTest{
...
@InjectMock
A subject;
...
@Test(expected=AIsTrueException.class)
public void testdisplay1(){
    subject.display(true,false);
}

@Test
public void testdisplay2(){
    subject.display(false,false);
    // Here how can I verify that no exception has occured in display(),
    // (When exception occured we use expected = ...)
    // Do we have similar when no exception occured
} 
...
...
}
</code></pre>
",https://stackoverflow.com/questions/43757288/can-we-verify-no-excpetion-occured-in-a-method-from-unit-testing,"['java', 'junit']",34,TRUE,0,2
Unit testing with jest in React Native project (&quot;Not a function&quot; error),"<p>I am working on a React Native project (v0.46). I've been able to write component snapshot tests successfully, but I'm having trouble wrapping my head around unit testing JavaScript ES6 functions.</p>

<p>Here are my functions in FakeUtils.js:</p>

<pre><code>export function sum(a, b) {
    return a + b;
}

export function subtract(a, b) {
    return a - b;
}
</code></pre>

<p>And here are my tests for them:</p>

<pre><code>import sum from '../src/utils/FakeUtils.js';
import subtract from '../src/utils/FakeUtils.js';

describe('sum', () =&gt; {   
    it('should sum 2 nums', () =&gt; {
        expect(sum(1,2)).toBe(3);
    });
});

describe('subtract', () =&gt; {   
    it('should subtract 2 nums', () =&gt; {
        expect(subtract(2,1)).toBe(1);
    });
});
</code></pre>

<p>When I run npm test, this is the output I receive:</p>

<pre><code>FAIL  __tests__/FakeUtilsTest.js
  ● sum › should sum 2 nums

    TypeError: (0 , _FakeUtils2.default) is not a function

      at Object.&lt;anonymous&gt; (__tests__/FakeUtilsTest.js:6:31)
      at tryCallTwo (node_modules/promise/lib/core.js:45:5)
      at doResolve (node_modules/promise/lib/core.js:200:13)
      at new Promise (node_modules/promise/lib/core.js:66:3)
      at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)
      at tryCallOne (node_modules/promise/lib/core.js:37:12)
      at node_modules/promise/lib/core.js:123:15

  ● subtract › should subtract 2 nums

    TypeError: (0 , _FakeUtils2.default) is not a function

      at Object.&lt;anonymous&gt; (__tests__/FakeUtilsTest.js:12:31)
      at tryCallTwo (node_modules/promise/lib/core.js:45:5)
      at doResolve (node_modules/promise/lib/core.js:200:13)
      at new Promise (node_modules/promise/lib/core.js:66:3)
      at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)
      at tryCallOne (node_modules/promise/lib/core.js:37:12)
      at node_modules/promise/lib/core.js:123:15
</code></pre>

<p>Any idea what I'm doing wrong here?</p>
",https://stackoverflow.com/questions/46476582/unit-testing-with-jest-in-react-native-project-not-a-function-error,"['javascript', 'unit-testing', 'react-native', 'ecmascript-6']",3039,TRUE,0,3
React | Unit testing how to test methods inside the succesful AJAX call?,"<p>Currently, In my react app, I have an ajax call method that has <code>setState</code> if the ajax call is successful, I already mocked the api response, it seems that the method won't execute anything else other than returning the response</p>

<p>For example,</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>// This is the ajax method
getProductData(productId) {
   // I already successfully mocked the response
   getProductById(productId).then(productResponse =&gt; {
   // I am trying make sure that the state is being updated with response data
   this.setState({
     product: productResponse.data
   })
});
}</code></pre>
</div>
</div>
</p>

<p>This is my test</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>test('Make sure my state is being updated with response data', async () =&gt; {
  const component = shallow(
      &lt;MyComponent /&gt;
  );
  
  component.instance().getProductData(1);
  // This is where my test failed, as it's not updating anything
  expect(component.state().product).to.equal('SOMETHING');
});</code></pre>
</div>
</div>
</p>

<p>Tried using <code>setTimeout</code> to asynchronously test the method, suggested by Jonah Pereira</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>test('Make sure my state is being updated with response data', async () =&gt; {
  const component = shallow(
      &lt;MyComponent /&gt;
  );
  
  component.instance().getProductData(1);
  // Using settimeout still not solving the problem, 
  setTimeout(() =&gt; {
    expect(component.state().product).to.equal('SOMETHING');
    
    // Not even this, that means the test totally ignored the setTimeout
    expect('abc').to.equal('cba');
  }, 0)
});</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/45048256/react-unit-testing-how-to-test-methods-inside-the-succesful-ajax-call,"['unit-testing', 'reactjs']",41,FALSE,0,1
Catch: what symbol can I use to personalize code for unit-testing,"<p>I am using the <a href=""https://github.com/catchorg/Catch2"" rel=""nofollow noreferrer"">Catch</a> C++ test framework. I have a separate test-code file, where I have</p>
<pre><code>#define CATCH_CONFIG_MAIN
#include &quot;catch.hpp&quot;

#include &quot;my_own_headers.h&quot;

TEST_CASE( &quot;test of thisnthat&quot;, &quot;[thisnthat]&quot; )
{
   SomeStuff a(42);
 ...
</code></pre>
<p>Is there some symbol that Catch defines at build time that I can use it to change my code definition?</p>
<p>An example:
Say I have some struct that needs to having some special constructor but only for testing purposes, for some specific test case. I want to be able to use this constructor when I build my test code, but the regular build should not enable this function.</p>
<pre><code>// someheader.h
struct SomeStuff
{
   int someValue;
 #if BUILD_IS_TEST_MODE
   SomeStuff( int a ), someValue(a) {}
 #endif
};
</code></pre>
<p>What symbol can I use ?</p>
<p>I had a look on <a href=""https://github.com/philsquared/Catch/blob/master/docs/configuration.md"" rel=""nofollow noreferrer"">https://github.com/philsquared/Catch/blob/master/docs/configuration.md</a> but couldn't find anything relevant.</p>
",https://stackoverflow.com/questions/45131449/catch-what-symbol-can-i-use-to-personalize-code-for-unit-testing,"['c++', 'unit-testing', 'catch-unit-test']",59,FALSE,0,0
Unit testing a dataflow/apache beam pipline that takes a side input,"<p>Using Dataflow 2.1 sdk</p>

<pre><code>        &lt;dependency&gt;
            &lt;groupId&gt;com.google.cloud.dataflow&lt;/groupId&gt;
            &lt;artifactId&gt;google-cloud-dataflow-java-sdk-all&lt;/artifactId&gt;
            &lt;version&gt;[2.1.0, 2.99)&lt;/version&gt;
        &lt;/dependency&gt;
</code></pre>

<p>As per <a href=""https://beam.apache.org/documentation/pipelines/test-your-pipeline/#side-inputs"" rel=""nofollow noreferrer"">this</a> documentation <code>setSideInputInGlobalWindow</code> should be available. But I only see below two relevant functions:
<a href=""https://i.stack.imgur.com/C4A1z.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/C4A1z.jpg"" alt=""enter image description here""></a></p>

<p>Below is my full code:</p>

<pre><code>DoFnTester&lt;EventItem,EventItem&gt; fnTester = DoFnTester.of(myDoFn);
    TestPipeline pipeline = TestPipeline.create();

TableRow row= new TableRow();
        atr.set(""a"", 7);
        atr.set(""q"", new ArrayList&lt;String&gt;() {{ add(""video_referrer""); add(""from_homepage"");}});

PCollectionView&lt;TableRow&gt; sideInput =  (PCollectionView&lt;TableRow&gt;) pipeline.apply(Create.of(Arrays.asList(atr)));
        Iterable&lt;TableRow&gt; sidVal = Arrays.asList(atr);
        fnTester.setSideInput(sideInput, sidVal); //error on this line

        List&lt;Foo&gt; testOutputs = fnTester.processBundle(Arrays.asList(testInput));
</code></pre>

<p>I see <code>setSideInput(PCollectionView&lt;T&gt; sideInput, BoundedWindow window, T value)</code> function <a href=""https://beam.apache.org/documentation/sdks/javadoc/2.2.0/"" rel=""nofollow noreferrer"">here</a>. But in this case how do I get <code>BoundedWindow</code>
Any ideas what am I missing here, Thanks.</p>
",https://stackoverflow.com/questions/47852891/unit-testing-a-dataflow-apache-beam-pipline-that-takes-a-side-input,"['apache-beam', 'dataflow']",1117,TRUE,0,1
Access Variable Defines in .m file for Unit Testing Objective-C XCTest,"<p>I am using XCTestKit for unit testing in my app using Objective-C.
I need to test the default values of textfields on my screen but the IBOutlets are declared under .m file.</p>

<p>Is there any way to access those variables, or any other approach to test the values in UnitTest classes.</p>
",https://stackoverflow.com/questions/44583326/access-variable-defines-in-m-file-for-unit-testing-objective-c-xctest,"['objective-c', 'xcode', 'unit-testing', 'xctest']",515,TRUE,0,1
Angular 2 Unit testing - &lt;component&gt; is not a known element although declared,"<p>I'm getting an error testing a component intended to show an error message.<br>
The component has a banner which is not recognised by the compiler.</p>

<p>I use a stub instead of the normal banner component since it uses some other things independent for the test. Using the normal banner component yields the same error, though.</p>

<p><strong>error.component.html</strong>  </p>

<pre><code>&lt;banner-component&gt;&lt;/banner-component&gt;
&lt;md-card class=""card""&gt;
    ...
&lt;/md-card&gt;
</code></pre>

<p><strong>error.component.spec.ts</strong></p>

<pre><code>//imports

describe('ErrorComponent', () =&gt; {
    let fixture: ComponentFixture&lt;ErrorComponent&gt;;
    let app;
    let mockRouter = {
        navigate: jasmine.createSpy('navigate')
    }; 
    let activatedRoute = {};
    let location = {

    };

    beforeEach(async(() =&gt; {

            TestBed.configureTestingModule({
                imports: [MdInputModule, MdDialogModule, RouterTestingModule, MdButtonModule, MdCardModule, MdMenuModule, MdToolbarModule, MdIconModule, MdCheckboxModule, MdInputModule, MdListModule, MdAutocompleteModule, MdSelectModule, MdTooltipModule, MdSidenavModule, MdGridListModule, MdSnackBarModule],
                declarations: [BannerStubComponent, ErrorComponent], // declare the test component
                providers: [{provide: ActivatedRoute, useValue: activatedRoute}, {provide: Router, useValue: mockRouter}, {provide: Location, useValue: location}]
            })
                .compileComponents();  // compile template and css

            fixture = TestBed.createComponent(ErrorComponent);
            app = fixture.debugElement.componentInstance;
     }));

     //tests
})
</code></pre>

<p><strong>bannerstub.component.ts</strong></p>

<pre><code>import {Component} from '@angular/core';
@Component({
    selector: 'banner-component',
    template: ``
})
export class BannerStubComponent {

}
</code></pre>

<p><strong>Output</strong></p>

<pre><code>'banner-component' is not a known element:
1. If 'banner-component' is an Angular component, then verify that it is part of this module.
2. If 'banner-component' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. (""[ERROR -&gt;]&lt;banner-component&gt;&lt;/banner-component&gt;
&lt;md-card class=""card""&gt;
</code></pre>

<p>So far, I have tried adding a <code>NO_ERRORS_SCHEMA</code> to the NgModule as suggested by the <a href=""https://angular.io/guide/testing#shallow-component-tests-with-no_errors_schema"" rel=""nofollow noreferrer"">Angular 2 Testing Documentation</a>, without success (yields the same error).</p>

<p>The Stub Component is declared correctly, I am not sure what I'm missing here.</p>
",https://stackoverflow.com/questions/45813660/angular-2-unit-testing-component-is-not-a-known-element-although-declared,"['angular', 'unit-testing']",392,FALSE,0,0
How to test Play Framework APIs and perform Unit Testing over it?,"<p>I need to test some API created in Python Play Framework. While using PHP I used Postman, what is the similar tool to be used to check Play API's?</p>
",https://stackoverflow.com/questions/42968895/how-to-test-play-framework-apis-and-perform-unit-testing-over-it,"['python', 'playframework']",94,TRUE,0,1
Angular 2/4 Jasmine unit testing a service with json object structure,"<p>I have a service that I want to unit test.   It has a current json array object in which when this observable is subscribed to, it works fine.</p>

<p>However,  what am I doing wrong with my unit test?</p>

<p><strong>Service code</strong> </p>

<pre><code>getTrackerData(): (Observable&lt;any&gt;) {
    return Observable.of(tracker)
        .do(data =&gt; console.log('trackerdata', data))
        .catch(this.handleError)
}

private handleError(error: Response) {
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
}
</code></pre>

<p>}</p>

<p><strong>DATA</strong> </p>

<pre><code>const tracker =
[{
    ""tracker"": ""2278474849"", ""task"": 1, ""agent"": 1, ""session"": ""2278474849-1-1""
 }
]
</code></pre>

<p><strong>Unit Test</strong></p>

<pre><code>/// &lt;reference path=""../../../../node_modules/@types/jasmine/index.d.ts"" /&gt;
import { TestBed, fakeAsync, inject, tick, async, ComponentFixture, ComponentFixtureAutoDetect } from '@angular/core/testing';
import { MockBackend } from '@angular/http/testing'
import { Http, BaseRequestOptions, Response, ResponseOptions } from '@angular/http'
import { BrowserModule, By } from ""@angular/platform-browser"";
import { ReactiveFormsModule } from '@angular/forms';
import { Observable } from 'rxjs/Rx'
import { TrackerService } from './tracker.service'


describe('tracker service', () =&gt; {

    let mockResponse, matchingItem, connection

    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            providers: [
                TrackerService,
                MockBackend,
                BaseRequestOptions,
                {
                    provide: Http,
                    useFactory: (backend, defaultOptions) =&gt; new Http(backend, defaultOptions),
                    deps: [MockBackend, BaseRequestOptions]
                },
            ]
        });
        const items =
            [{
                ""tracker"": ""2278474849"", ""task"": 1, ""agent"": 1, ""session"": ""2278474849-1-1""
            }
            ];
        mockResponse = new Response(new ResponseOptions({ body: items, status: 200 }));
    }));


    describe('getTrackerData', () =&gt; {
        //subscribe to connection and storing it later
        it('should return all items', inject([TrackerService, MockBackend], (service: TrackerService, backend: MockBackend) =&gt; {
            backend.connections.subscribe(connection =&gt; {
                connection.mockRespond(mockResponse);
            });
            service.getTrackerData() //{ ""tracker"": ""2278474849"", ""task"": 1, ""agent"": 1, ""session"": ""2278474849-1-1""  }
                .subscribe((items: any =&gt; {
                   expect(this).toBe(2);
            }));

    })

});
</code></pre>

<p>I seem to be getting errors in the <code>describe</code> section   ,  Problem is that I'm not used to writing javascript/angular unit test, along with mixing up a few examples in the project I'm on coupled with online examples.  </p>

<p>Seems like what I want/need to do should be way simple , but yet I imported so many dependencies that this is now just confusing.</p>

<p>Anyone know what I need to do?</p>
",https://stackoverflow.com/questions/45974620/angular-2-4-jasmine-unit-testing-a-service-with-json-object-structure,"['javascript', 'angular', 'unit-testing', 'typescript', 'jasmine']",2078,TRUE,0,1
Php Unit Testing: How do i access find() and get() in testController,"<p>I can access find() and get() in the tableTest.php but can't access it in the ControllerTest.php. How do i gain access in cakephp3?</p>
",https://stackoverflow.com/questions/44774256/php-unit-testing-how-do-i-access-find-and-get-in-testcontroller,"['phpunit', 'cakephp-3.0']",21,FALSE,0,1
"scope method in AngularJS directive is not a function, when unit testing","<p>I have this Mocha test:</p>

<pre><code>'use strict';

///////////////////////////////////

describe('all admin page directives', function () {

  let scope, $compile, element, tmp;
  beforeEach(module('app'));
  beforeEach(module('templates'));

  afterEach(function () {
    scope.$destroy();
  });

  describe('category', function () {

    beforeEach(inject(function ($injector) {
      $compile = $injector.get('$compile');
      var $rootScope = $injector.get('$rootScope');
      scope = $rootScope.$new();
      scope.rightSidebarData = {};
      $compile('&lt;create-category right-sidebar-data=""rightSidebarData""&gt;&lt;/create-category&gt;')(scope);
      return scope.$digest();
    }));

    it('should do something', function () {
       scope.updateModel();           //     &lt;&lt;&lt;&lt;&lt;&lt;  ERROR HERE
    });


  });

});
</code></pre>

<p>here is my directive:</p>

<pre><code>/* globals angular */

angular.module('app').directive('createCategory',

  ['UserService', 'AssignmentService', 'NotificationService', 'USER', 'UserInfoService', 'AlertService', '$window',

    function (UserService, AssignmentService, NotificationService, USER, UserInfoService, AlertService, $window) {

      return {

        scope: {
          rightSidebarData: '=',
        },

        restrict: 'EA',
        templateUrl: ""pages/admin/views/templates/category/create-category.html"",

        link: function ($scope, el, attrs) {

          $scope.rightSidebarData.setOrReset = function () {
            $scope.setOrReset();
          };

        },

        controller: function ($scope, FUNCTIONAL_TEAM_ENUM, CATEGORY_ENUM, CategoryService) {

          const rsd = $scope.rsd = $scope.rightSidebarData;

          $scope.setOrReset = function () {...};

          $scope.updateModel = function () {...};

          $scope.saveModel = function () {...};

        },
      };
    }
  ]);
</code></pre>

<p>I am getting this error:</p>

<blockquote>
  <p>TypeError: scope.updateModel is not a function</p>
</blockquote>

<p>Does anyone know what I need to do in my test to fix this?
Also, how do I know if I need to use <code>$rootScope.$new()</code> or if I should be passing the parent controller's scope?</p>
",https://stackoverflow.com/questions/47877537/scope-method-in-angularjs-directive-is-not-a-function-when-unit-testing,"['javascript', 'angularjs', 'angularjs-directive', 'karma-runner']",449,TRUE,-1,1
Unit testing Javascript - Jasmine test fails although code is working as expected,"<p>I'm trying to get started with unit testing with javascript. I'm using jasmine framework 2.5.2 and Netbeans 8.2 as my IDE.</p>

<p>This is the simple code i want to test:</p>

<pre><code>var ListHandler = {

    ""reverseList"": function (inputList) {
        var list = inputList,
            reversedList = [],
            length = list.length;

        for (var i = 0; i &lt; length; i++) {
            reversedList.push(list[length - i - 1]);
        }

        return reversedList;
    },

    ""sumUp"": function (inputList) {
        var count = 0;
        for (var i = 0; i &lt; inputList.length; i++) {
            count += inputList[i];
        }

        return count;
    },

    ""concatenate"": function (inputList1, inputList2) {
        var result = inputList1.concat(inputList2);
        return result;
    }
}
</code></pre>

<p>This is my test:</p>

<pre><code>describe(""List Handler"", function(){ 

   it(""should return reversed List"",function(){ 
      expect(ListHandler.reverseList([1,2,3])).toEqual([3,2,1]); 
   }); 

   it(""should return sum of list values"",function(){ 
      expect(ListHandler.sumUp([1,2,3])).toEqual(6); 
   }); 

   it(""should return concatenated List"", function(){
       expect(ListHandler.concatenate([1,2],[""a"",""b""]).toEqual([1,2,""a"",""b""]));
   });
});
</code></pre>

<p>So when i run the test, the first two methods pass, but i get an error for the last method ""concenate"": </p>

<blockquote>
  <p>TypeError: ListHandler.concatenate(...).toEqual is not a function</p>
</blockquote>

<p>However, when i just execute it like <code>alert(ListHandler.concatenate([1,2,5], [""a"", ""b"", ""c""]));</code> it works fine. Can someone explain to me why jasmine complains?</p>
",https://stackoverflow.com/questions/42003981/unit-testing-javascript-jasmine-test-fails-although-code-is-working-as-expecte,"['javascript', 'unit-testing', 'jasmine', 'typeerror', 'netbeans-8']",30,TRUE,0,1
"Autofac, unit-testing, C# - Difference between Autofac Moq and FakeItEasy integration package","<p>Can anyone help me differentiate between  Autofac Moq and FakeItEasy integration packages? 
My demo project uses Autofac for its dependencies. I want to change my unit test cases also to use Autofac Moq/FakeItEasy integration project. I am currently using Autofac MOQ</p>

<p>I was referring link: <a href=""http://docs.autofac.org/en/latest/integration/moq.html"" rel=""nofollow noreferrer"">http://docs.autofac.org/en/latest/integration/moq.html</a> helpful but I couldn't run my test successfully.</p>

<p>In the example below IDAL and IDATE are my dependencies and IAGE is a parameter to my unit test function CalculateMatruity(age).</p>

<p>Questions:</p>

<ol>
<li>Unit test is not taking my fake parameters IDAl, IDATE. </li>
<li>Also, can any please advise how to pass parameters to the unit test function.</li>
<li>Am I passing the parameter correctly my instantiating a New person() object? </li>
</ol>

<p>my sample unit test is:</p>

<pre><code>[TestMethod]
public void TestGenericHelper()
{
    //arrange
    using (var mock = AutoMock.GetLoose())
    {

        mock.Mock&lt;IDAL&gt;().Setup(x =&gt; x.GetMaturityConfiguration()).Returns(""0=Child|13=Teen|18=Adult"");
        mock.Mock&lt;IAge&gt;().Setup(x =&gt; x.Birthdate).Returns(DateTime.Parse(""1987-06-16""));
        mock.Mock&lt;IDate&gt;().Setup(x =&gt; x.Date).Returns(Convert.ToDateTime(""2000-01-01""));

        var sut = mock.Create&lt;GenericHelper&gt;(); 

        String expected = ""Teen"";

        Person age = new Person();
           age.Birthdate = DateTime.Parse(""1987-06-16""); 

        //act
         //  mock.Provide&lt;IGenericHelper, GenericHelper&gt;(new NamedParameter(""AgeObj"", DateTime.Parse(""1987-06-16"")));

        String actual = sut.CalculateMatruity(age); 

        //assert
        mock.Mock&lt;IDAL&gt;().Verify(x =&gt; x.GetMaturityConfiguration());
        mock.Mock&lt;IAge&gt;().Verify(x =&gt; x.Birthdate);
        mock.Mock&lt;IDate&gt;().Verify(x =&gt; x.Date);
        Assert.AreEqual(expected, actual);
    }
}
</code></pre>

<p>Previously my test was:</p>

<pre><code>[TestMethod]
public void TestGenericHelper()
{
    Person age = new Person();
    age.Birthdate = DateTime.Parse(""1987-06-16"");     
    String expected = ""Teen""; 

    DateTime FakeDate = Convert.ToDateTime(""2000-01-01"");
    String fake = ""0=Child|13=Teen|18=Adult"";

    FakeDate DateHelperObj = new FakeDate(FakeDate);
    FakeAgeDAL fakeObj = new FakeAgeDAL(fake);

    GenericHelper GenericHelperObj = new GenericHelper(fakeObj, DateHelperObj);
    String actual = GenericHelperObj.CalculateMatruity(age);

    Assert.AreEqual(expected, actual);
}


Function GenericHelper looks like below:

 public class GenericHelper : IGenericHelper
    {
        private IDAL _DAL;
        private IDate _Date;

        public GenericHelper(IDAL DAL, IDate Date)
        {
            _DAL = DAL;
            _Date = Date;
        }

        public GenericHelper()
        { }
        public String CalculateMatruity(IAge AgeObj)
        {

           String Maturity = """", AgeConfiguration;

            //DateTime Now = DateTime.Now;

           IDAL dalObj = _DAL;
           IDate dateObj = _Date; 

            /*start */

                //using (var container = UATContainer.Container.BeginLifetimeScope())
                //{
                    AgeConfiguration = dalObj.GetMaturityConfiguration();
                    Int64 Age = dateObj.Date.Year - AgeObj.Birthdate.Year;

                    //AgeConfiguration = container.Resolve&lt;IDAL&gt;().GetMaturityConfiguration();
                    //var _d = container.Resolve&lt;IDate&gt;().Date.Year;
                    //Int64 Age = _d - AgeObj.Birthdate.Year;      /* Using autofac approach */    

            var config = AgeConfiguration.Split('|').Select(s =&gt; s.Split('=')).ToDictionary(c =&gt; c[1], c =&gt; int.Parse(c[0]));

            if (Age &gt;= config[""Child""] &amp;&amp; Age &lt; config[""Teen""])
                Maturity = ""Child"";
            else if (Age &gt;= config[""Teen""] &amp;&amp; Age &lt; config[""Adult""])
                Maturity = ""Teen"";
            else if (Age &gt;= config[""Adult""])
                Maturity = ""Adult"";
            else              
                Maturity = ""Inapproriate to calculate age,verify the DOB"";

                //}
                /*end */
            return Maturity;
        }

    }
}
</code></pre>

<p>Correct test results:</p>

<pre><code>public void TestGenericHelperAutofacFakeItEasy()
        {  
            using (var fake = new AutoFake())
            {
                A.CallTo(() =&gt; fake.Resolve&lt;IDAL&gt;().GetMaturityConfiguration()).Returns(""0=Child|13=Teen|18=Adult"");
                A.CallTo(() =&gt; fake.Resolve&lt;IDate&gt;().Date).Returns(Convert.ToDateTime(""2000-01-01""));
                var sut = fake.Resolve&lt;GenericHelper&gt;();
                String expected = ""Teen"";
                Person age = new Person();
                age.Birthdate = DateTime.Parse(""1987-06-16"");

                String actual = sut.CalculateMatruity(age);

                A.CallTo(() =&gt; fake.Resolve&lt;IDAL&gt;().GetMaturityConfiguration()).MustHaveHappened();
                A.CallTo(() =&gt; fake.Resolve&lt;IDate&gt;().Date).MustHaveHappened();
                Assert.AreEqual(expected, actual);
            } 
}
</code></pre>
",https://stackoverflow.com/questions/44136873/autofac-unit-testing-c-difference-between-autofac-moq-and-fakeiteasy-integr,"['c#', 'unit-testing', 'testing', 'autofac']",1799,FALSE,0,1
"Unit Testing in Phalcon 3 (upgrading from 2), DI can&#39;t find services","<p>I'm having trouble migrating an old project from Phalcon 2 (2.0.9) to Phalcon 3 (3.1.2). The code itself seems to run ok (first look), but the unit-tests just won't work.
I've been through the documentation (<a href=""https://docs.phalconphp.com/en/3.0.1/reference/unit-testing.html"" rel=""nofollow noreferrer"">https://docs.phalconphp.com/en/3.0.1/reference/unit-testing.html</a>) and even rebuild my TestHelper and UnitTestCase from scratch just to make sure that everything's in place, but especially the DI-container seems to work a lot differently in Phalcon 3 compared to Phalcon 2 in the tests.</p>

<p>For example:</p>

<ul>
<li>""parent::setUp()"" needs to be run at the beginnig of ""setUp()"" in UnitTestCase.</li>
<li>""parent::setUp()"" at the end of UnitTestCase needs to be changed to ""$this->setDi($di)""</li>
<li>The config is unknown in all tests unless you explicitely use ""$this->setConfig($config)"" in UnitTestCase (took me hours just to figure that out).</li>
<li>It seems I need to register ""request"" and ""response"" (as shared) in my DI to run any unit-test that needs the request- or response-object. This was not necessary before. Still the tests won't work, but at least the warning that the services ""request/response"" are unknown went away.</li>
<li>The ""modelsManager"" is now unknown to the DI, also I need to register ""modelsMetadata"" in the DI to get the unit-tests to work. This also was not necessary with Phalcon 2.</li>
</ul>

<p>And it still won't work (although I fixed hundreds of warnings with the above fixes), right now I'm getting the message ""<em>Phalcon\Di\Exception: Service 'filter' wasn't found in the dependency injection container</em>"" when running a unit-test which tries to validate a form using ""$form->isValid($post)"" which was working fine this way with Phalcon 2.</p>

<p>I've been struggling with this for a couple of days now and starting to plan <strong>not</strong> to upgrade to Phalcon 3 at all but to keep an old server with Phalcon 2 running for legacy projects, even though this feels like failure ... is anyone experiencing the same problems and is this really the - hard to believe - way to go to upgrade to Phalcon 3?</p>

<p>Here's some of my code, TestHelper:</p>

<pre><code>include __DIR__ . '/../../../vendor/autoload.php';
$loader = new \Phalcon\Loader();
$loader-&gt;registerDirs([ROOT_PATH]));
$loader-&gt;registerNamespaces( ... );
$loader-&gt;register();
$di = new FactoryDefault();
Di::reset();
Di::setDefault($di);
</code></pre>

<p>UnitTestCase (for each module):</p>

<pre><code>abstract class UnitTestCase extends PhalconTestCase
{
    public function setUp()
    {
        parent::setUp();
        $di = Di::getDefault();
        (... setting my services as well as Request/Response here...)
       $this-&gt;setDi($di);
    }
}
</code></pre>
",https://stackoverflow.com/questions/44544878/unit-testing-in-phalcon-3-upgrading-from-2-di-cant-find-services,"['unit-testing', 'phalcon']",145,FALSE,0,0
"Mockito unit testing: on all method invocations of a class, return &quot;true&quot;","<p>I have a class in kotlin <code>SmsHandler</code>, with a method <code>determineFiltersPass</code> that invokes methods of another class, <code>SmsSendingFilters</code>:</p>

<pre><code>class SmsHandler(val filterPredicates: SmsSendingFilters) {
    fun determineFiltersPass(sms: SmsDto): Boolean = with(sms.filters) {
        var pass = true
        for (filter in FiltersDto::class.memberProperties)
            pass = when (FilterType.valueOf(filter.name.toUpperCase())) {
                UNIQUE -&gt; if (filter.get(sms.filters) != null) {
                    val unique = filter.get(sms.filters) as Boolean
                    pass &amp;&amp; if (unique) filterPredicates.isUnique().test(sms) else true
                } else pass &amp;&amp; true
                RECENT -&gt; if (filter.get(sms.filters) != null) {
                    pass &amp;&amp; filterPredicates.shouldSendByTimePeriodFromLastMessage().test(sms)
                } else pass &amp;&amp; true
                else -&gt; pass &amp;&amp; true
            }
        pass
    }
}


class SmsSendingFilters {

    fun isUnique(): Predicate&lt;SmsDto&gt; = Predicate {
        with(it) {
        repo.findAllByMessageIdAndMobileNumAndAppIdAndParamMap(messageId!!, mobileNum!!, appId!!, paramMap!!.toString()).isEmpty()
        }
    }

    fun shouldSendByTimePeriodFromLastMessage(): Predicate&lt;SmsDto&gt; = Predicate {
        val calendar = Calendar.getInstance()
        calendar.time = Date()
        with(it.filters.recent ?: """" to """") {
            val size = this.second.toInt()
            when (IntervalType.valueOf(this.first.toUpperCase())) {
                SECOND -&gt; calendar.add(Calendar.SECOND, -1 * size)
                MINUTE -&gt; calendar.add(Calendar.MINUTE, -1 * size)
                HOUR -&gt; calendar.add(Calendar.HOUR, -1 * size)
                MONTH -&gt; calendar.add(Calendar.MONTH, -1 * size)
                YEAR -&gt; calendar.add(Calendar.YEAR, -1 * size)
                else -&gt; Unit
            }
            with(it) {
                repo.findAllByMessageIdAndMobileNumAndAppId(messageId!!, mobileNum!!, appId!!)
                    .none { it.dateSent?.toInstant()?.isAfter(calendar.toInstant()) ?: true }
            }
        }
    }
}
</code></pre>

<p>Now, I'm testing the class <code>SmsHandler</code> and because I predict that more filters will be added to the second class, I want to create a generic mock that on invocation of any method from class <code>SmsSendingFilters</code>, will return <code>true</code> or <code>false</code> as I please. Is there a way of doing so without describing the invocation of each method name explicitly (through reflection I guess)?</p>

<p>I'm not looking for a solution of sort:</p>

<pre><code>when(filterPredicates.shouldSendByTimePeriodFromLastMessage().test(any()).thenReturn(true)
</code></pre>

<p>But, something that complies with this logic:</p>

<pre><code>when(filterPredicates.&lt;anyMethodInvoked&gt;().test(any())).thenReturn(true)
</code></pre>
",https://stackoverflow.com/questions/47519631/mockito-unit-testing-on-all-method-invocations-of-a-class-return-true,"['java', 'kotlin', 'mockito']",477,TRUE,0,1
Unit testing encrypt/decrypt with some salt located in different code bases,"<p>First of all I shall mention that I have seen <a href=""https://stackoverflow.com/questions/24371069/unit-testing-of-encrypt-decrypt"" title=""Unit testing of encrypt/decrypt"">Unit testing of encrypt/decrypt</a>, and <a href=""https://stackoverflow.com/questions/41375108/unit-testing-encryption-and-decryption-in-java"" title=""Unit testing encryption and decryption in Java"">Unit testing encryption and decryption in Java</a>.</p>

<p>I want to protect a library by validating its license. The license contains information such as maximum users and expiration time and so on.</p>

<p>The problems I encounter are:</p>

<ul>
<li>The encryptor and decryptor are in two different code bases. The decryptor is packaged with the library, but encryptor is not, so it is hard to have them both in the same test suite!</li>
<li>A random salt is used within encryptor, so even with same input the encryptor produces a different output each time, again I can not do assertion on the result.</li>
<li>For the sake of its purpose the decryptor (to make it harder to inject another class for it) is a final class, and all of its methods are private, except a few package accessible entry points.</li>
</ul>

<p>I don't want to test JCE, but I want to test my code which does:</p>

<ul>
<li>Extracting the salt from the encrypted license,</li>
<li>Deciphers the encrypted license,</li>
<li>Deserializes the output to some data structure containing license data,</li>
</ul>

<p>Shall I create a clone of the the code, with some softer access constraints and test that? Then the problem is I am not testing the real code which is run on client systems.</p>

<p>Are there any better solutions to do this?</p>
",https://stackoverflow.com/questions/46207908/unit-testing-encrypt-decrypt-with-some-salt-located-in-different-code-bases,"['java', 'unit-testing', 'encryption', 'jce']",749,FALSE,0,1
Wierd behavior when loading AutoMapper profiles for Unit Testing using xUnit 2,"<p>xUnit2 runs all tests in parallel, so for this reason I want to ensure that all my automapper profiles are loaded first, in order to get a successful mapping while running the tests. This is what I have done</p>

<pre><code>    public static class AutoMapperRestConfiguration
{
    private static readonly object Sync = new object();
    private static bool isInitialized = false;

    public static void Configure()
    {
        lock (Sync)
        {
            if (!isInitialized)
            {
                isInitialized = true;
                Trace.Listeners.Add(new ConsoleTraceListener());
                Trace.WriteLine(""Automapper initialized"");
                GetConfiguration(Mapper.Configuration);
            }
        }
    }
     private static void GetConfiguration(IConfiguration configuration)
    {
        if (true)
        {
            // var assemblies = AppDomain.CurrentDomain.GetAssemblies();
            var assemblies = new List&lt;Assembly&gt;();
            var baseProfileAssemblies = new List&lt;Assembly&gt;();

            assemblies.Add(typeof(Profile1).Assembly);
            assemblies.Add(typeof(Profile2).Assembly);

         Mapper.Initialize(cfg =&gt;
            {
                foreach (var assembly in assemblies)
                {
                    var profiles = assembly.GetTypes().Where(x =&gt; typeof(Profile).IsAssignableFrom(x));
                    foreach (var profile in profiles)
                    {
                        cfg.AddProfile((Profile) Activator.CreateInstance(profile));
                        Trace.WriteLine(profile.ToString());
                    }
                    // var baseProfileSpecs = assembly.GetTypes().Where(x =&gt; typeof(BaseProfileSpecs&lt;T&gt;().Where(T=&gt; )).IsAssignableFrom(x));

                }
            });
            Mapper.Configuration.Seal();
        }
    }
}
</code></pre>

<p>}</p>

<p>Things work like this, but when I set the Boolean value below the GetConfiguration method call, everything starts failing. The profiles are not loaded and AutoMapper throws MappingExceptions. Isnt the lock(Sync) construct supposed to block and wait for one execution cycle to complete before the other method executes. I am not being able to wrap my head around this. </p>
",https://stackoverflow.com/questions/45835284/wierd-behavior-when-loading-automapper-profiles-for-unit-testing-using-xunit-2,"['c#', '.net', 'automapper', 'xunit2']",421,FALSE,0,0
How to handle view throwing manual exception in django in unit-testing?,"<p>I have made a django application and am writing tests for it.
In one of my views I'm manually throwing an exception:</p>

<p><code>raise Http404('Not authorised')</code></p>

<p>While writing test for that using django's built-in test framework(based on unittest).</p>

<p>TL;DR: Is there way to write test such that it makes sure that the view is indeed returning <code>Http404</code>. ( <code>assertEqual(response.status_code, 404</code> doesn't work)</p>
",https://stackoverflow.com/questions/42325440/how-to-handle-view-throwing-manual-exception-in-django-in-unit-testing,"['python', 'django', 'unit-testing', 'django-unittest']",975,TRUE,0,2
Angular2 Unit testing Uncaught Error: Invalid argument &#39;[object Object]&#39; for pipe &#39;AsyncPipe&#39;,"<p>Having problems runnign my unit test code, getting this error message when trying to run the test: </p>

<ul>
<li>Uncaught Error: Error in package:454:50:17 caused by: Invalid argument '[object 
Object]' for pipe 'AsyncPipe'
at ViewWrappedError.ZoneAwareError</li>
</ul>

<p><strong>dashboard.component.spec.ts</strong></p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { Router, ActivatedRoute } from ""@angular/router"";
import { MockAF } from ""../../providers/mockAf"";
import { AF } from ""../../providers/af"";
import { DashboardComponent } from './dashboard.component';
import { SortOnLikePipe } from '../sort-on-like.pipe'
import { EditMessageModalComponent } from '../edit-message-modal/edit-
message-modal.component';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/observable/of';
import { MockModal } from '../edit-course-modal/mockEdit-course-
modal.component';

describe('DashboardComponent', () =&gt; {
  let component: DashboardComponent;
  let fixture: ComponentFixture&lt;DashboardComponent&gt;;
  let routerStub;

beforeEach(async(() =&gt; {
  routerStub = {
    navigate: jasmine.createSpy('navigate')
  };
  TestBed.configureTestingModule({
    declarations: [
      DashboardComponent,
      SortOnLikePipe,
      EditMessageModalComponent,
     ],
    imports: [
      FormsModule,
    ],
    providers: [
      { provide: AF, useClass: MockAF },
      { provide: Router, useValue: routerStub },
      { provide: EditMessageModalComponent, useClass: MockModal },
      { provide: ActivatedRoute, useValue: { queryParams: Observable.from([{ 
      course: ""TDT4001"" }]) }},
    ],
  })
  .compileComponents();
}));

beforeEach(() =&gt; {
  fixture = TestBed.createComponent(DashboardComponent);
  component = fixture.componentInstance;
  fixture.detectChanges();
});

it('should create', () =&gt; {
  expect(component).toBeTruthy();
});
</code></pre>

<p>This is where i use pipes in my code
<strong>dashboard.component.html</strong></p>

<pre><code>&lt;div *ngFor=""let message of afService.messages | async | 
sortOnLike:'votes':false""&gt;
.....
&lt;/div&gt;
</code></pre>

<p><strong>dashboard.component.ts</strong></p>

<pre><code>import { Component, OnInit, AfterViewChecked, ElementRef, ViewChild } from 
'@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { AF } from '../../providers/af';
import { FirebaseListObservable, AngularFire } from 'angularfire2';
import { Bubble } from './bubble';
import { EditMessageModalComponent } from '../edit-message-modal/edit-
message-modal.component';

@Component({
  moduleId: module.id.toString(),
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})

export class DashboardComponent implements OnInit, AfterViewChecked {

  constructor(public afService: AF, private router: Router, private route: 
  ActivatedRoute) {
  }

  ngOnInit(): void {
    var sub = this.route
      .queryParams
      .subscribe(params =&gt; {
      // Defaults to error if no query param provided.
      this.afService.setCourse(params['course'] || ""error"");
     });
  }
</code></pre>

<p>I have no clue on how to fix this problem, the funny thing is that it all worked. But when i got home to continue testing i got this error. All help is appreciated :)</p>
",https://stackoverflow.com/questions/43630574/angular2-unit-testing-uncaught-error-invalid-argument-object-object-for-pip,"['unit-testing', 'angular', 'karma-jasmine']",903,FALSE,0,0
Cannot call beforeEach &#39;inject&#39; on angularJS (FUSE Admin) unit testing using karma,"<p>I used FUSE Admin app on my project - <a href=""http://fuse-angular-material.withinpixels.com/apps/dashboards/project"" rel=""nofollow noreferrer"">http://fuse-angular-material.withinpixels.com/apps/dashboards/project</a>.</p>

<p>I already checked other samples and even run this code on a different project and works just fine. IT's just that I cannot inject the service, controller etc. on 'beforeEach inject', thus I cannot cont. my test.</p>

<p>I don't know what's wrong or did I miss something (dependencies? not sure) while running this on FUSE. Do you have any idea?</p>

<p>Here's my code.</p>

<p><strong>SERVICE</strong> <em>(the service returns a list of array)</em></p>

<pre><code>(function () {
    'use strict';

    angular
        .module('app.admin.users', [])
        .config(config)
        .service('adminUserService', service);

    function service(msApi) {
        return {
            adminUserList: function () {
                return msApi.resolve('admin.users.list@query');
            }
        };
    }

    function config(msApiProvider) {
       // calling the API (used dummy data)
        msApiProvider.register('admin.users.list',['app/data/admin/users/users.json']);
    }

})();
</code></pre>

<p><strong>UNIT TEST</strong></p>

<pre><code>var oDataService;
var adminUserService;

describe('unit test ----------------------------', function () {
    beforeEach(module('app.admin.users'));

    beforeEach(function () {
        inject(function ($injector) {
            adminUserService = $injector.get('adminUserService');
            oDataService = adminUserService.adminUserList();
        });
    });

    it(""is registered with the module."", function () {
        expect(oDataService).not.toBe(null);
    });
});
</code></pre>
",https://stackoverflow.com/questions/46460399/cannot-call-beforeeach-inject-on-angularjs-fuse-admin-unit-testing-using-kar,"['angular', 'karma-runner', 'angular-mock', 'gulp-karma']",209,FALSE,0,1
How to fix Unit Testing - error: &quot;Cannot read property &#39;parseUrl&#39; of undefined&quot;?,"<p>For a component which uses a Service I'am writing a unit testing - spec file.</p>

<p><strong>function in the component:</strong></p>

<pre><code>registerUser(email: string, pass: string) {
    if (!this.EMAIL_REGEXP.test(email)) {
        return false;
    } else if (!this.PASS_REGEXP.test(pass)) {
        return false;
    } else {
        this._backUpApiService.storeUserData(email, pass)
        .subscribe(
            (res) =&gt; {
                console.log(JSON.stringfy(res));
                ...
            },
            (err) =&gt; {
                console.log(JSON.stringfy(err));
                ...
            }
        );
    }
}
</code></pre>

<p><strong>method in the service:</strong></p>

<pre><code>storeUserData(email:String, pass:String) {
    this.form = this._fbuilder.group({
        input: {
            user:{
                umail:email,
                upassword:pass
            }
        }
    });
    let formObj = this.form.getRawValue();
    let serializedObj = JSON.stringify(formObj);

    return this._http.post(url, serializedObj, this.options)
    .map(res =&gt; {
        res.json();
    })
    .catch((error: any) =&gt; Observable.throw(error.json().error || 'Server error'));
}
</code></pre>

<p><strong>The spec file:</strong></p>

<pre><code>it(`should call storeUserData on BackendApiService when registerUser is called with correct Credentials`, async(() =&gt; {

    let myService: BackendApiService = new BackendApiService();
    spyOn(myService, 'storeUserData').and.returnValue(Observable.of(myService));

    const emailOk = [
      'test@test.com',
      'test@test.co.uk',
    ];
    const passwordOk = '!cdRef2';

    let result = component.registerUser(this.emailOk, this.passwordOk);

    expect(myService.storeUserData).toHaveBeenCalled();

  }));
</code></pre>

<p>The issue is that the test failed and I keep getting the following: <strong><code>Cannot read property 'parseUrl' of undefined</code></strong></p>

<p>Can it be that the function in spec file is expecting the <strong><code>URL</code></strong> for the Ajax Call in the Service function? I actually just want to test if the <strong><code>storeUserData</code></strong> function in the service is being called when the <strong><code>registerUser</code></strong> function in the component is called/invoked.</p>

<p>What am I doing wrong?</p>
",https://stackoverflow.com/questions/47573011/how-to-fix-unit-testing-error-cannot-read-property-parseurl-of-undefined,"['angular', 'unit-testing', 'jasmine']",755,TRUE,0,1
Angular2 unit testing does not update input&#39;s ngModel when used inside a form,"<p>I have fairly extensive testing in our Angular 2.4 based application.  One area we have not been able to test though is forms with inputs.  I finally tracked this down to a small test case.  I have a plnkr that shows the issue: <a href=""https://plnkr.co/edit/NyeAoh2Uo5rJT9if6j64"" rel=""noreferrer"">https://plnkr.co/edit/NyeAoh2Uo5rJT9if6j64</a>  (see form_bug.spec.ts)</p>

<p>Note: I based this example off the way the code in the testing guide works.</p>

<p>The problem is that when we hook an input up with ngModel, and then in the test suite we update the input the data will flow into the component only if the input is not inside a form.  If we add it to a form, then the data will not flow correctly.</p>

<p>The core pieces of the code are:</p>

<pre><code>@Component({
   selector: 'with-form-test',
   template: `
   &lt;div&gt;
      &lt;div class=""show_val""&gt;{{testVal}}&lt;/div&gt;
      &lt;form&gt;
         &lt;input name=""test_val"" id=""val_id"" [(ngModel)]=""testVal"" /&gt;
      &lt;/form&gt;
   &lt;/div&gt;
   `,
})
class WithFormTestComp {
   testVal: string = 'start';
}
</code></pre>

<p>and the test.  The two expect() checks in this one fail.</p>

<pre><code>describe('WithFormTest', () =&gt; {
   let fixture: ComponentFixture&lt;WithFormTestComp&gt;;
   let comp:    WithFormTestComp;
   let comp_de: DebugElement;

   function getInput(): DebugElement {
      return comp_de.query(By.css('input'));
   }
   function getShowVal(): DebugElement {
      return comp_de.query(By.css('.show_val'));
   }

   beforeEach(() =&gt; {
      TestBed.configureTestingModule({
         imports: [
            FormsModule,
         ],
         declarations: [
            WithFormTestComp,
         ],
      });

      fixture = TestBed.createComponent(WithFormTestComp);
      comp    = fixture.componentInstance;
      comp_de = fixture.debugElement;
   });

   it('should update testVal', () =&gt; {
      fixture.detectChanges();
      const input_elt: HTMLInputElement = getInput().nativeElement;

      input_elt.value = 'set_val';
      input_elt.dispatchEvent(newEvent('input'));
      fixture.detectChanges();

      const show_val_elt = getShowVal().nativeElement;

      expect(comp.testVal).toEqual('set_val');
      expect(show_val_elt.textContent).toBe('set_val');
   });

});
</code></pre>

<p>Does anyone see how to fix this up so that it will work correctly?  I have looked around and can't find any bug reports that explain why this would work without the form but fail with it.</p>
",https://stackoverflow.com/questions/43287454/angular2-unit-testing-does-not-update-inputs-ngmodel-when-used-inside-a-form,"['angular', 'angular2-testing']",2011,FALSE,5,0
"Unit Testing : cellForItem(at: IndexPath.init(item: 0, section: 0)) returns nil for UICollectionView","<p>I am running into a very weird problem where my code for unit testing a UiCollectionViewCell returns nil.</p>

<pre><code>var indexPath = IndexPath.init(item: 0, section: 0)

let cell = libraryGridViewController?.libraryCollectionView.cellForItem(at: indexPath)
</code></pre>

<p>This collection view is attached to the datasource by RxSwift binding.</p>

<p>Though while debugging I observed that numberOfItems(inSection: 0) returns the desired number of items in data-array.</p>

<pre><code>(lldb) po libraryGridViewController!.libraryCollectionView.numberOfItems(inSection: 0)
</code></pre>

<p>4</p>

<p>Please let me know what could have possibly gone wrong here. I just want a valid cell to be returned from the method - cellForItem.  Thanks!</p>
",https://stackoverflow.com/questions/43020828/unit-testing-cellforitemat-indexpath-inititem-0-section-0-returns-nil,"['ios', 'swift3', 'uicollectionview', 'xctestcase']",967,FALSE,5,0
Unit Testing: Karma-Jasmine not resolving Promise without implicitly calling $rootScope.$digest();,"<p>I have an <code>Angular</code> service that makes a call to the server and fetch the user list. The service returns a <code>Promise</code>.</p>

<p><strong>Problem</strong></p>

<p>Promise is not being resolved until and unless I call <code>$rootScope.$digest();</code> either in the service or in the test itself. </p>

<pre><code>    setTimeout(function () {
        rootScope.$digest();
    }, 5000);
</code></pre>

<p>Apparently, Calling <code>$rootScope.$digest();</code> is a workaround and I cannot call it in the angular service so I am calling it in the <code>unit test</code> with an interval of 5 seconds which I think is a bad practice.</p>

<p><strong>Request</strong></p>

<p>Please suggest an actual solution for this.</p>

<p>Given below is the test that I have written.</p>

<pre><code>   // Before each test set our injected Users factory (_Users_) to our local Users variable
    beforeEach(inject(function (_Users_, $rootScope) {
        Users = _Users_;
        rootScope = $rootScope;
    }));

    /// test getUserAsync function
    describe('getting user list async', function () {

        // A simple test to verify the method getUserAsync exists
        it('should exist', function () {
            expect(Users.getUserAsync).toBeDefined();
        });


        // A test to verify that calling getUserAsync() returns the array of users we hard-coded above
        it('should return a list of users async', function (done) {
            Users.getUserAsync().then(function (data) {
                expect(data).toEqual(userList);
                done();
            }, function (error) {
                expect(error).toEqual(null);
                console.log(error.statusText);
                done();
            });

            ///WORK AROUND
            setTimeout(function () {
                rootScope.$digest();
            }, 5000);
        });
    })
</code></pre>

<p><strong>service</strong></p>

<pre><code>  Users.getUserAsync = function () {
    var defered = $q.defer();

    $http({
      method: 'GET',
      url: baseUrl + '/users'
    }).then(function (response) {
      defered.resolve(response);
    }, function (response) {
      defered.reject(response);
    });

    return defered.promise;
  }
</code></pre>
",https://stackoverflow.com/questions/42647488/unit-testing-karma-jasmine-not-resolving-promise-without-implicitly-calling-ro,"['javascript', 'angularjs', 'unit-testing', 'jasmine', 'karma-jasmine']",163,FALSE,0,1
Creating (mocked) Repository for Unit Testing - what to use instead of DbContext,"<p>I have to create Unit testing infrastructure in the project. However, I am a bit stuck on <strong>how to mock Repository</strong> and which structure to use instead of <code>DbContext</code>.</p>

<p>Here is our <strong>Repository</strong>:</p>

<pre><code> public class Repository : IRepository
    {
        protected readonly IProjContext _context;    
        public Repository(IProjContext context)
        {
            this._context = context;
        }    

    public T GetById&lt;T&gt;(object id) where T : class
        {
            return _context.Set&lt;T&gt;().Find(id);       
        }
   ...}
</code></pre>

<p><strong>Interface for IRepository</strong></p>

<pre><code> public interface IRepository {
        T GetById&lt;T&gt;(object id) where T : class;
        ... }
</code></pre>

<p><strong>DB Context</strong></p>

<pre><code>public class ProjContext : DbContext, IProjContext { ... }
</code></pre>

<p><strong>DB Context Interface</strong></p>

<pre><code>public interface IProjContext : IDbContext { ... }
</code></pre>

<p>There are a lot of similar methods in this class (that also implements interface <code>IRepository</code>) - <code>Count</code>, <code>Delete</code>, etc. and also <code>SaveChanges</code>.</p>

<p>As you see, we use single Repository without UnitOfWork. Now I have to mock it. </p>

<p>I decided not to use any Mocking framework and just created our own <code>MockedRepository</code>. It should be something like this:</p>

<pre><code>public class MockedRepository: IRepository
{
    public T GetById&lt;T&gt;(object id) where T : class {
            /// ??????   Get data from where?
   }    
}
</code></pre>

<p>The question is - as <code>MockedRepository</code> is used for Unit Testing, I do not need DbContext there. However, I cannot understand which structure to use instead of DbContext to be able to add data (generic data that means data of different types <code>T</code>) to repository and to implement simple method slike <code>GetById&lt;T&gt;</code> and others.</p>
",https://stackoverflow.com/questions/45484638/creating-mocked-repository-for-unit-testing-what-to-use-instead-of-dbcontext,"['c#', 'entity-framework', 'unit-testing']",60,FALSE,0,0
Google unit testing in C++: how to write a persistent data file?,"<p><strong>Questions:</strong> </p>

<p>1) Where do files go that are created by a C++ Google unit test?</p>

<p>2) Is there a way to write a persistent data file in a C++ Google unit test, such that the file is accessible after the test runs?</p>

<p><strong>Code and desired behavior</strong></p>

<p>I'm running the unit test on Ubuntu 14.04 with catkin_make. I would like the code to write a file somewhere that I can find it after the test runs. The following code writes a file, but I don't know where it goes, or if it persists after the unit tests complete.</p>

<pre><code>TEST(GUnitTestFileIo, Test_One)
{
  std::ofstream csvFile;
  csvFile.open(""helloWorldTestFile.csv"");
  if (csvFile.is_open()) {
    csvFile &lt;&lt; ""Hello, World, !"" &lt;&lt; std::endl;
    csvFile.close();
  } else {
    std::cout &lt;&lt; ""Failed to open the file!"" &lt;&lt; std::endl;
  }
}

int main(int argc, char **argv){
  testing::InitGoogleTest(&amp;argc, argv);
  return RUN_ALL_TESTS();
}
</code></pre>
",https://stackoverflow.com/questions/47554446/google-unit-testing-in-c-how-to-write-a-persistent-data-file,"['c++', 'unit-testing', 'persistence', 'googletest', 'file-writing']",1553,TRUE,0,1
"Unit Testing Delete, record returned even though it is deleted in the DB","<p>I am using Nunit to test a method in my controller which deletes a record from the DB.  Everything works correctly and the record is deleted when I check but somehow</p>

<pre><code>db.AssesorMaxProjectLoad.Find(previousLoad.ID) 
</code></pre>

<p>still returns the deleted value and makes my test fail.</p>

<p>Test:</p>

<pre><code>[Test]
public void AssesorMaxProjectLoadsDeleteLoad()
{
   var previousLoad = db.AssesorMaxProjectLoad.Where(t =&gt; t.AssesorID == testAssesor3ID).FirstOrDefault(t =&gt; t.TaskGroupID == taskGroupID);
   var result = controller.DeleteConfirmed(previousLoad.ID) as ViewResultBase;
   var newProjectLoad = db.AssesorMaxProjectLoad.Find(previousLoad.ID).MaxAssignedProjectLoad;
   Assert.AreEqual(null, newProjectLoad);
}
</code></pre>

<p>Controller Method its Testing:</p>

<pre><code>[HttpPost, ActionName(""Delete"")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
   AssesorMaxProjectLoad assesorMaxProjectLoad = db.AssesorMaxProjectLoad.Find(id);
   db.AssesorMaxProjectLoad.Remove(assesorMaxProjectLoad);
   db.SaveChanges();
   return RedirectToAction(""Index"", ""AssesorMaxProjectLoads"", new { id = assesorMaxProjectLoad.TaskGroupID });
}
</code></pre>

<p>Whats going on or what am I missing? I don't understand how it can be returned when it is no longer in the database?</p>
",https://stackoverflow.com/questions/42637191/unit-testing-delete-record-returned-even-though-it-is-deleted-in-the-db,"['c#', 'asp.net-mvc', 'unit-testing', 'nunit']",2026,TRUE,4,1
what does 1x 3x etc mean in karma code coverage report in Angular Unit testing?,"<p>I am new to Unit Testing in Angular. I got the <code>karma</code> setup with code coverage along with <code>angular-cli</code> . I have run the command ng-test and opened code coverage report. I saw <code>1x</code> ,<code>3x</code> etc along with my code line numbers in that coverage report. Please find the my coverage report image.</p>

<p><a href=""https://i.stack.imgur.com/LPsTZ.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/LPsTZ.png"" alt=""enter image description here""></a></p>

<p>Here is my test case code <code>app.component.spec.ts</code> </p>

<pre><code>/* tslint:disable:no-unused-variable */

import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';

describe('AppComponent', () =&gt; {
  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
    });
  });

  it('should create the app', async(() =&gt; {
    let fixture = TestBed.createComponent(AppComponent);
    let app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));

  it(`should have as title 'app works!'`, async(() =&gt; {
    let fixture = TestBed.createComponent(AppComponent);
    let app = fixture.debugElement.componentInstance;
    expect(app.title).toEqual('app works!');
  }));

  it('should render title in a h1 tag', async(() =&gt; {
    let fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    let compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('h1').textContent).toContain('app works!');
  }));
});
</code></pre>

<p>I didn't understand what is the importance of that <code>1x,2x,3x</code> etc in my code report. Please help me in knowing the importance of that.</p>
",https://stackoverflow.com/questions/41757821/what-does-1x-3x-etc-mean-in-karma-code-coverage-report-in-angular-unit-testing,"['javascript', 'unit-testing', 'angular', 'istanbul', 'karma-coverage']",4008,TRUE,15,1
Framework/visual studio project type to use for unit testing .net standard libray?,"<p>Given that the implementation of the <code>.net standard library</code> is provided by the underlined implementation (<code>.Net framework</code>, <code>.Net Core</code> (windows/Linux etc) ). And it is possible that the APIs have little different behaviour. <code>TimeZoneInfo.Id</code> provides different results based on the OS (last time I checked).</p>

<p>So, how to unit test? In visual studio we can either create a <code>.Net Core</code> <code>xUnit</code> project or <code>.Net Framework</code> <code>xUnit</code> project. How to run the same <code>xUnit</code> tests in two different environment?</p>
",https://stackoverflow.com/questions/45658528/framework-visual-studio-project-type-to-use-for-unit-testing-net-standard-libra,"['c#', '.net', 'unit-testing', '.net-core', '.net-standard']",659,TRUE,4,2
Unit testing a parent class that uses Injector with Router (and other services),"<p>Suppose I have class <code>Foo</code> which provides dependency injected services to all its derived classes, as such:</p>

<pre><code>export class Foo {
    protected fb : FormBuilder;
    protected router : Router;
    protected otherService : OtherService;
    protected anotherService : AnotherService;

    constructor(injector : Injector) {
        this.fb = injector.get(FormBuilder);
        this.router = injector.get(Router);
        this.otherService = injector.get(OtherService);
        this.anotherService = injector.get(AnotherService);
}
</code></pre>

<p>which has classes derived from it as such:</p>

<pre><code>export class Bar extends Foo {

    constructor(injector : Injector){
         super(injector);
    }
}
</code></pre>

<p>How can I unit test the parent class correctly, without running into:</p>

<p><code>Error: Can't resolve all parameters for Foo: (?)</code></p>

<p>At the minute I have (having tried many, <em>many</em> different things to get it to work, but failing :( )</p>

<pre><code>export function main() {

    describe('Class: Foo', () =&gt; {
        beforeEach(async(() =&gt; {

            TestBed.configureTestingModule({
                providers: [
                    Foo,
                    Injector,
                    OtherService,
                    AnotherService
                ]
            });
        }));


        it('should compile', inject([Foo, Injector], ( foo: Foo, injector : Injector ) =&gt; {
            console.log(""INJECTOR"", injector);
            expect(foo).toBeTruthy();
        }));

    });
}
</code></pre>

<p>I've also tried using <code>ReflectiveInjector.resolveAndCreate</code> as such:</p>

<pre><code>{
    provide : Injector,
    useValue: ReflectiveInjector.resolveAndCreate([FormBuilder, Router, OtherService, AnotherService])
}
</code></pre>

<p>But still no dice :( Any ideas?</p>
",https://stackoverflow.com/questions/42907338/unit-testing-a-parent-class-that-uses-injector-with-router-and-other-services,"['angular', 'angular2-di']",5051,TRUE,4,1
Angular 4 unit testing with jasmine /karma with http post mocking - how to fix,"<p>I have a service I want to unit test in angular 4  typescript  jasmine.</p>

<p>Now, the <code>http</code> is doing a <code>post</code> , and it returns an identity, however.. it is not sending anything. </p>

<p>I want to just have good code coverage but i don't understand how to quite complete this mocking statement.</p>

<p><strong>here is the method for http post in my service file</strong></p>

<pre><code>addSession() {
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        return this.http.post(this.url, JSON.stringify({}), options)
            .map((response: Response) =&gt; response.json());

}
</code></pre>

<p><strong>Then the SPEC FILE</strong> , which i don't get what to really test,  i suppose faking that i received a number back from the service http post,  the response should be something like  <code>000000014</code>    </p>

<p><strong>Spec</strong></p>

<pre><code>import { TrackerFormService } from './tracker-form.service'
import { Observable } from 'rxjs/Observable'

describe('TrackerFormService', () =&gt; {

    let trackerFormService: TrackerFormService,
        mockHttp;

    beforeEach(() =&gt; {
        mockHttp = jasmine.createSpyObj('mockHttp', ['get', 'post', 'put']
        )
        trackerFormService = new TrackerFormService(mockHttp);
    });

    describe('addSession', () =&gt; {

        it('add session ', () =&gt; {
              // how to test,  what to test?    
              // response , is a number?  how to mock/fake this?

        })

    })

})
</code></pre>
",https://stackoverflow.com/questions/46420640/angular-4-unit-testing-with-jasmine-karma-with-http-post-mocking-how-to-fix,"['angular', 'unit-testing', 'typescript', 'jasmine', 'karma-jasmine']",17299,TRUE,9,4
Spring MVC Controller Unit Testing : How do I set private instance boolean field?,"<p>I have a Spring MVC REST controller class that has a private instance boolean field injected via @Value , </p>

<pre><code>@Value(""${...property_name..}"")
private boolean isFileIndex;
</code></pre>

<p>Now to unit test this controller class, I need to inject this boolean. </p>

<p>How do I do that with <code>MockMvc</code>?</p>

<p>I can use reflection but <code>MockMvc</code> instance doesn't give me underlying controller instance to pass to <code>Field.setBoolean()</code> method. </p>

<p>Test class runs without mocking or injecting this dependency with value always being <code>false</code>. I need to set it to <code>true</code> to cover all paths. </p>

<p>Set up looks like below. </p>

<pre><code>@RunWith(SpringRunner.class)
@WebMvcTest(value=Controller.class,secure=false)
public class IndexControllerTest {

    @Autowired
    private MockMvc mockMvc;
 ....
}
</code></pre>
",https://stackoverflow.com/questions/44517648/spring-mvc-controller-unit-testing-how-do-i-set-private-instance-boolean-field,"['java', 'unit-testing', 'spring-mvc', 'spring-restcontroller']",3062,TRUE,3,2
TypeError: Cannot read property &#39;snapshot&#39; of undefined failure while performing unit testing in angular2,"<p>I am doing unit testing using angular 2   when i do unit testing it show me error cannot read property 'snapshot' undefined.</p>

<pre><code>ReadMailComponent should create
TypeError: Cannot read property 'snapshot' of undefined
TypeError: Cannot read property 'snapshot' of undefined
    at ReadMailComponent.getCommentId (webpack:///D:/Zool-Projects/mindspark/src/app/modules/my-mindspark/components/read-mail/read-mail.component.ts?:48:27)
    at ReadMailT1Component.ReadMailT2Component.ngOnInit (webpack:///D:/Zool-Projects/mindspark/src/app/shared/components/my-mindspark/read-mail/read-mail-t2/read-mail-t2.component.ts?:34:49)
    at checkAndUpdateDirectiveInline (webpack:///D:/Zool-Projects/mindspark/node_modules/@angular/core/@angular/core.es5.js?:11043:19)
    at checkAndUpdateNodeInline (webpack:///D:/Zool-Projects/mindspark/node_modules/@angular/core/@angular/core.es5.js?:12541:20)
    at checkAndUpdateNode (webpack:///D:/Zool-Projects/mindspark/node_modules/@angular/core/@angular/core.es5.js?:12484:16)
    at debugCheckAndUpdateNode (webpack:///D:/Zool-Projects/mindspark/node_modules/@angular/core/@angular/core.es5.js?:13341:59)
    at debugCheckDirectivesFn (webpack:///D:/Zool-Projects/mindspark/node_modules/@angular/core/@angular/core.es5.js?:13282:13)
    at Object.eval [as updateDirectives] (ng:///DynamicTestModule/ReadMailComponent.ngfactory.js:16:5)
    at Object.debugUpdateDirectives [as updateDirectives] (webpack:///D:/Zool-Projects/mindspark/node_modules/@angular/core/@angular/core.es5.js?:13267:21)
    at checkAndUpdateView (webpack:///D:/Zool-Projects/mindspark/node_modules/@angular/core/@angular/core.es5.js?:12451:14)
</code></pre>

<blockquote>
  <p>Here is readmail.component.spec.ts</p>
</blockquote>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { ReadMailComponent } from './read-mail.component';
import { ReadMailT1Component } from '../../../../shared/components/my-
mindspark/read-mail/read-mail-t1/read-mail-t1.component';
import { ReadMailT2Component } from '../../../../shared/components/my-mindspark/read-mail/read-mail-t2/read-mail-t2.component';
import { ShortenPipe } from 'ngx-pipes/src/app/pipes/string/shorten';
import { NgbModule, NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { MomentModule } from 'angular2-moment/moment.module';
import { SanitizeCodePipe } from '../../../../shared/pipes/sanitize/sanitizeCode.pipe';
import { GetFileNamePipe } from '../../../../shared/pipes/getFileName/getFileName.pipe';
import { ReactiveFormsModule } from '@angular/forms';
import { TranslateService, TranslateModule } from 'ng2-translate';
import { RouterTestingModule } from '@angular/router/testing';
import { CommentModalService } from '../../../../shared/components/comments/comment-modal/comment-modal.service';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { SharedService } from '../../../../shared/shared.service';
import { MailboxService } from '../mailbox/mailbox.service';
import { ContentService } from '../../../../shared/services/content/content.service';
import { ActivatedRoute, ActivatedRouteSnapshot } from '@angular/router';

describe('ReadMailComponent', () =&gt; {
  let component: ReadMailComponent;
  let fixture: ComponentFixture&lt;ReadMailComponent&gt;;
  let activatedRoute: ActivatedRouteSnapshot;
  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ReadMailComponent, ReadMailT1Component, ReadMailT2Component, ShortenPipe, SanitizeCodePipe, GetFileNamePipe],
      imports: [TranslateModule.forRoot(), NgbModule.forRoot(), MomentModule, ReactiveFormsModule, RouterTestingModule, HttpClientModule],
      providers: [TranslateService, CommentModalService, SharedService, MailboxService, ContentService, { provide: ActivatedRoute, useValue: activatedRoute }]
    })
      .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(ReadMailComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p>Here is my <strong>readmail.component.ts</strong> file</p>

<pre><code>import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { CommentModalService } from '../../../../shared/components/comments/comment-modal/comment-modal.service';
import { SharedService } from '../../../../shared/shared.service';
import { ContentService } from '../../../../shared/services/content/content.service';
import { MailboxService } from '../mailbox/mailbox.service';
import { AppSettings } from '../../../../settings/app.settings';
import * as _ from 'lodash';

@Component({
  selector: 'ms-read-mail',
  templateUrl: './read-mail.component.html',
  styleUrls: ['./read-mail.component.scss']
})
export class ReadMailComponent implements OnInit {
  template: string;
  readmail: any;
  errorInfo: any;

  constructor(private route: ActivatedRoute, private commentModalService: CommentModalService, private mailBoxService: MailboxService,
    private sharedService: SharedService, private contentService: ContentService) {
    this.sharedService.setSiteTitle('ReadMail');
    this.contentService.getTemplate().subscribe(
      result =&gt; {
        this.template = this.contentService.getTemplateId(result);
      },
      responseError =&gt; this.errorInfo = responseError
    );
  }

  ngOnInit() { }

  getMessageTrailData(messageID) {
    /* check if messaege id not empty, else show error in an alert and return to mailbox */
    this.sharedService.showLoader();
    this.mailBoxService.getMessageTrailData(messageID).subscribe(
      result =&gt; {
        const status = this.contentService.validateResponse(result, messageID);
        if (status === 'success') {
          this.readmail = result;
          this.contentService.setTemplate(result);
          this.contentService.setBasicData(result);
        }
        this.sharedService.hideLoader();
      },
      responseError =&gt; this.errorInfo = this.sharedService.handleResponseError(responseError)
    );
  }

  getCommentId() {
    return this.route.snapshot.url[1].path;
  }

  showQuestion(showQue) {
    return (showQue === 'SHOW') ? 'HIDE' : 'SHOW';
  }

  updateSelectedFiles(attachFile) {
    const files = [];
    if (attachFile) {
      const file = attachFile.nativeElement;
      if (file.files &amp;&amp; file.files[0]) {
        const uploadFile = file.files;
        for (let i = 0; i &lt; uploadFile.length; i++) {
          const thisFile = uploadFile[i];
          files.push({ filename: thisFile.name });
        }
      }
    }
    return files;
  }

  removeFile(attachFile) {
    if (attachFile) {
      attachFile.nativeElement.value = '';
    }
    return [];
  }

  saveCommentRating(rating, commentId) {
    this.sharedService.showLoader();
    const data = {
      'rating': rating,
      'commentID': commentId
    };
    this.mailBoxService.saveRating(data).subscribe(
      result =&gt; {
        const status = this.contentService.validateResponse(result, data);
        if (status === 'success') {
          console.log('Rating updated.');
        }
        this.sharedService.hideLoader();
      },
      responseError =&gt; this.errorInfo = this.sharedService.handleResponseError(responseError)
    );
  }

  replyToMessage(replyMessage, messageID, attachFile) {
    this.sharedService.showLoader();
    let uploadFileError = '';
    let uploadFileState = '';
    const maxFileUpload = AppSettings.MAX_IMAGE_SIZE;
    const formData = new FormData();
    if (attachFile) {
      const file = attachFile.nativeElement;
      if (file.files &amp;&amp; file.files[0]) {
        const uploadFile = file.files;
        for (let i = 0; i &lt; uploadFile.length; i++) {
          const thisFile = uploadFile[i];
          if (thisFile.type.indexOf('image') !== 0) {
            uploadFileState = 'invalidType';
          } else {
            const fileSize = thisFile.size / 1024;
            if (fileSize &gt; maxFileUpload * 1024) {
              uploadFileState = 'fileSize';
            }
          }
        }
        if (uploadFileState === '') {
          for (let i = 0; i &lt; uploadFile.length; i++) {
            formData.append('attachments[]', uploadFile[i]);
          }
        } else if (uploadFileState === 'invalidType') {
          const acceptedTypes = AppSettings.IMAGE_FORMAT.join(' or ');
          uploadFileError = 'Upload only files of type ' + acceptedTypes + '.';
        } else if (uploadFileState === 'fileSize') {
          uploadFileError = 'File size should not be greater than ' + maxFileUpload + 'MB.';
        }
        if (uploadFileError !== '') {
          setTimeout(() =&gt; uploadFileError = '', 3000);
        }
      } else {
        console.log('No file selected.');
      }
    }
    if (uploadFileState === '') {
      formData.append('replyBody', replyMessage.value.replyBody);
      formData.append('messageID', messageID);

      this.commentModalService.replyToMessage(formData).subscribe(
        result =&gt; {
          const status = this.contentService.validateResponse(result, {});
          if (status === 'success') {
            this.getMessageTrailData(messageID);
          }
          this.sharedService.hideLoader();
        },
        responseError =&gt; this.errorInfo = this.sharedService.handleResponseError(responseError)
      );
      return { result: 'success', message: '' };
    } else {
      this.sharedService.hideLoader();
      return { result: 'error', message: uploadFileError };
    }
  }

  open(imageBoxModal, fileName) {
    this.sharedService.open(imageBoxModal);
    return fileName;
  }

  disableSend(replyMessage) {
    return replyMessage.invalid;
  }

}
</code></pre>

<p>Here is my <strong>readmail.component.html</strong> file</p>

<pre><code>&lt;ng-container [ngSwitch]=""template""&gt;
  &lt;ng-container *ngSwitchCase=""'1'""&gt;
    &lt;ms-read-mail-t1 [readMail]=""readmail""&gt;&lt;/ms-read-mail-t1&gt;
  &lt;/ng-container&gt;
  &lt;ng-container *ngSwitchCase=""'2'""&gt;
    &lt;ms-read-mail-t2 [readMail]=""readmail""&gt;&lt;/ms-read-mail-t2&gt;
  &lt;/ng-container&gt;
  &lt;ng-container *ngSwitchDefault&gt;
    &lt;ms-read-mail-t1 [readMail]=""readmail""&gt;&lt;/ms-read-mail-t1&gt;
  &lt;/ng-container&gt;
&lt;/ng-container&gt;
</code></pre>

<p>I think the error is coming from the url[1].path as it shows that path is undefined means that url is causing error. </p>

<p>I have tried all sorts of example but did not work for me please help me out. 
Thanks in advance</p>
",https://stackoverflow.com/questions/47430280/typeerror-cannot-read-property-snapshot-of-undefined-failure-while-performing,"['angular', 'unit-testing', 'karma-jasmine']",11432,TRUE,8,1
Testing user if he has a specific authority using AuthorizeAsync() in Xunit-Unit Testing,"<p><strong>The question has been Updated for better explanation to the issue I have,</strong> </p>

<p>Simply I have this controller, </p>

<pre><code>    [Authorize]
    public class IdeaManagementController : Controller
    {
        private IIdeaManagementService _ideaManagementService;

        private ITenantService _tenantService;

        private ITagService _tagService;

        private IEmployeeIdeaCategoryService _ideaManagementCategoryService;

        private static PbdModule _modul = PbdModule.IdeaManagement;

        IAuthorizationService _authorizationService;

        public IdeaManagementController(
            IIdeaManagementService ideaManagementService,
            ITenantService tenantService,
            ITagService tagService,
            IAuthorizationService authorizationService,
            IEmployeeIdeaCategoryService ideaManagementCategoryService)
        {
            _ideaManagementService = ideaManagementService;
            _tenantService = tenantService;
            _tagService = tagService;
            _authorizationService = authorizationService;
            _ideaManagementCategoryService = ideaManagementCategoryService;
        }

    public async Task&lt;IActionResult&gt; IdeaCoordinator()
    {
        if (!await _authorizationService.AuthorizeAsync(User, ""IdeaManagement_Coordinator""))
        {
            return new ChallengeResult();
        }
        var ideas = _ideaManagementService.GetByIdeaCoordinator(_tenantService.GetCurrentTenantId());
        return View(ideas);
    }
}
</code></pre>

<p>and simply I need to test the retrned viewResult of the action method IdeaCoordinator but I couldn't simply because if the _authorizationService.AuthorizeAsync validation Method, <strong>I tried to mock the method but simply I couldn't because it is an Extension Built In Method</strong> , then I tried to make a work around solution by creating a new Interface that implements IAuthorizationService and Mock that customized Interface like that </p>

<pre><code>public interface ICustomAuthorizationService : IAuthorizationService
{
    Task&lt;bool&gt; AuthorizeAsync(ClaimsPrincipal user, string policyName);
}


public IAuthorizationService CustomAuthorizationServiceFactory()
{
   Mock&lt;ICustomAuthorizationService&gt; _custom = new Mock&lt;ICustomAuthorizationService&gt;();
    _custom.Setup(c =&gt; c.AuthorizeAsync(It.IsAny&lt;ClaimsPrincipal&gt;(), ""IdeaManagement_Coordinator"")).ReturnsAsync(true);
    return _custom.Object;
}
</code></pre>

<p>and Inject it to while I am calling the controller constructor and then I found myself like that : </p>

<pre><code>[Theory]
[InlineData(1)]
public async void IdeaManager_Should_Return_ViewResult(int _currentTenanatID)
{
    // Arrange ..
    _IdeaManagementControllerObject = new IdeaManagementController
                                      (IdeaManagementServiceMockFactory(_currentTenanatID),
                                      TenantServiceMockFactory(_currentTenanatID),
                                       TagServiceMockFactory(),
                                       AuthorizationServiceMockFactory(),
                                       EmployeeIdeaCategoryServiceMockFactory());
    // Act 
    var _view = await _IdeaManagementControllerObject.IdeaCoordinator() as ViewResult;

    // Assert 
    Assert.IsType(new ViewResult().GetType(), _view);
}
</code></pre>

<p>I expected different results because I marked the return result to be true just to ignore this line of code and continue to the Viewresult but while I debugged my Test Method again the compiler got into the validation message as it didn't feel the changes I did on the AuthorizeAsync Method result ..
<a href=""https://i.stack.imgur.com/orpOu.jpg"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/orpOu.jpg"" alt=""enter image description here""></a></p>

<p>Thank you so much in advance.</p>

<p><strong>==Solution==</strong></p>

<p><strong>Intro :</strong></p>

<p>“We can not solve our problems with the same level of thinking that created them” - Albert Einstein. and with this adorable saying I would like to inform that I spent about 1 week for solving this problem until I felt it will never solved at this moment, I spent hours of investigation, but after reading an article and after changing the way of thinking , the solution came in 30 mins.</p>

<p><strong>Problem at a glance :</strong></p>

<p>Simply, I was trying to unit test the written above action method, and I have a serious problem related with that I couldn't mock the method ""AuthorizeAsync"" and simply because it is a built in extension method and because of extension method nature as static method it can never be mocked with the traditional way of mocking classes.</p>

<p><strong>Solution in Details :</strong></p>

<p>To be able to mock this action method I created a static class that contains static delegates and with those delegates I will mock or as it can be said ""Wrap"" my extension method by a replacement of my static delegates in my unit test class as following.</p>

<pre><code>public static class DelegateFactory
{
    public static Func&lt;ClaimsPrincipal, object, string, Task&lt;bool&gt;&gt; AuthorizeAsync =
        (c, o, s) =&gt;
        {
            return AuthorizationServiceExtensions.AuthorizeAsync(null, null, """");
        };
}

public Mock&lt;IAuthorizationService&gt; AuthorizationServiceMockExtensionFactory()
{
    var mockRepository = new Moq.MockRepository(Moq.MockBehavior.Strict);
    var mockFactory = mockRepository.Create&lt;IAuthorizationService&gt;();
    var ClaimsPrincipal = mockRepository.Create&lt;ClaimsPrincipal&gt;();
    mockFactory.Setup(x =&gt; x.AuthorizeAsync(It.IsAny&lt;ClaimsPrincipal&gt;(), It.IsAny&lt;object&gt;(), It.IsAny&lt;string&gt;())).ReturnsAsync(true);
    return mockFactory;
}
</code></pre>

<p>and at my test method I just called the mocked object in the controller constructor instantiation.</p>

<pre><code>    [Fact]
    public async void IdeaCoordinator_When_AuthroizedUser_IsNotNull_But_IdeaManagement_Manager_Authorized_Return_View()
    {
       // Arrange
        int approvedByID = data.GetTenantByID(1).TenantId;
        _IdeaManagementControllerObject = new IdeaManagementController
                                          (IdeaManagementServiceMockFactory().Object,
                                          TenantServiceMockFactory().Object,
                                           TagServiceMockFactory().Object,
                                           AuthorizationServiceMockExtensionFactory().Object,
                                           EmployeeIdeaCategoryServiceMockFactory().Object);
        //Act
        IdeaManagementServiceMockFactory().Setup(m =&gt; m.GetByIdeaCoordinator(approvedByID)).Returns(data.GetCordinatedEmpIdeas(approvedByID));
        ViewResult _view = await _IdeaManagementControllerObject.IdeaCoordinator() as ViewResult;
        var model = _view.Model as List&lt;EmployeeIdea&gt;;
        // Assert
        Assert.Equal(3, model.Count);
        Assert.IsType(new ViewResult().GetType(), _view);
    }
</code></pre>

<p>and as it said, The single greatest cause of happiness is gratitude.I would like to thank Stephen Fuqua for his brilliant solution and article , <a href=""http://www.safnet.com/writing/tech/2014/04/making-mockery-of-extension-methods.html"" rel=""noreferrer"">http://www.safnet.com/writing/tech/2014/04/making-mockery-of-extension-methods.html</a></p>

<p>Thank you everyone :) !</p>
",https://stackoverflow.com/questions/42965727/testing-user-if-he-has-a-specific-authority-using-authorizeasync-in-xunit-unit,"['c#', 'unit-testing', 'asp.net-core-mvc', 'xunit.net', 'asp.net-core-identity']",4235,TRUE,8,3
Why is the python logger in unit testing not working after setLevel called,"<p>I have the following code in my <code>unittest</code> TestCase:</p>
<pre><code>class StatsdLogHandler(logging.Handler):
    def emit(self, record):
        log_entry = self.format(record)
        statsd_client.incr(log_entry)

def setup_statsd_logging(logger, level=logging.WARNING):
    # set up statsd counts for logging
    statsd_format = &quot;pegasus.logger.%(levelname)s.%(name)s&quot;
    formatter = logging.Formatter(statsd_format)
    statsd_handler = StatsdLogHandler()
    statsd_handler.setFormatter(formatter)
    statsd_handler.setLevel(level)
    logger.addHandler(statsd_handler)

class TestLogging(unittest.TestCase):
    @mock.patch('.statsd_client')
    def test_logging_to_statsd(self, statsd_mock):
        &quot;&quot;&quot;Make sure log calls go to statsd&quot;&quot;&quot;
        root_logger = logging.getLogger()
        setup_statsd_logging(root_logger)
        root_logger.setLevel(logging.DEBUG)
        root_logger.warning('warning')
        statsd_mock.incr.assert_called_with('pegasus.logger.WARNING.root')
</code></pre>
<p>However, when I run the TestLogging test case, I get</p>
<blockquote>
<p>AssertionError: Expected call: incr(u'pegasus.logger.WARNING.root')</p>
<p>Not called</p>
</blockquote>
<p>I would expect this call to be successful. Why is this happening?</p>
",https://stackoverflow.com/questions/47543830/why-is-the-python-logger-in-unit-testing-not-working-after-setlevel-called,"['python', 'logging', 'python-unittest']",980,TRUE,2,1
py.test unit testing over a fixed range of parameter values with failure records,"<p>I've written the following type of unit tests for a tool:</p>

<pre class=""lang-python prettyprint-override""><code>param_one = np.random.randint(100, 1000)
param_two = np.random.randint(20, 200)

data1 = generate_random_data(param_one, param_two)
data2 = generate_random_data(param_one, param_two)

def test_one(data1, data2):
    assert something
def test_two(data1, data2):
    assert something
</code></pre>

<p>I know the tests can fail for a certain combination of these parameters. so I would like to repeat the <code>py.test</code> for a specified ranges of the two parameters, and record which combinations of these parameters are failing.</p>

<p>Even better would be </p>

<ol>
<li>if I could save the random data under test when a certain test fails and </li>
<li>repeat each test (for each combination of these parameters 10 times) and record the frequency of success/failure.</li>
</ol>

<p>How can I achieve this under py.test or unittest? Thanks a lot.</p>

<p>I looked up documentation on py.test website and some previous answers here, but the terms are all confusing and it is not easy to follow them.</p>

<p>Obviously, I could do this outside the testing framework, I need this in the unit testing mechanism so I can setup continuous integration better. </p>
",https://stackoverflow.com/questions/45396169/py-test-unit-testing-over-a-fixed-range-of-parameter-values-with-failure-records,"['python', 'unit-testing', 'debugging', 'pytest']",487,FALSE,2,0
Jest unit testing a function that calls a function that returns a promise,"<p>If I have code something like this:</p>

<pre><code>import externalThing from 'externalThing'
import anotherThing from 'anotherThing'

function functionIWantToTest()
{    
    externalThing.doSomething()
    .then(data=&gt;{
        anotherThing.do(data.Id)
    })
}
</code></pre>

<p>What is the best practice way to unit test this?</p>

<p>Ideally the test would be something like this:</p>

<pre><code>import externalThing from 'externalThing'
import anotherThing from 'anotherThing'

jest.mock('externalThing',()=&gt;jest.fn())
jest.mock('anotherThing',()=&gt;jest.fn())

describe('when calling functionIWantToTest',()=&gt;{

    beforeEach(()=&gt;{     
       anotherThing.do=jest.fn()
       //mock external thing somehow so that it still the 'then' code

       functionIWantToTest()
    })

    it('anotherThing should be called',()=&gt;{
        expect(anotherThing.do).toHaveBeenCalledWith(1)
    });
});
</code></pre>

<p>But when I try I just end up building a chain of mocked functions with jest.fn() and no code actually gets executed.</p>
",https://stackoverflow.com/questions/45663803/jest-unit-testing-a-function-that-calls-a-function-that-returns-a-promise,"['javascript', 'unit-testing', 'promise', 'jestjs']",1492,TRUE,2,1
Karma+jasmine+Angular2 unit testing http service error (No provider for [object Object]),"<p>I have set up a simple service and tried to run the test. </p>

<h2>Service</h2>

<pre><code>//CustomerServiceTest.ts:
import { Injectable, Pipe } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';

@Injectable()
export class CustomerServiceTest{

  constructor(public http: Http) {}

  query(URL: string, params?: Array&lt;string&gt;): Observable&lt;any[]&gt; {

    let be_endpoint: string = 'http:\/\/localhost:44444\/';
    let queryURL: string = `${be_endpoint}${URL}`;


    if (params) {
      queryURL = `${queryURL}?${params.join('&amp;')}`;
    }

    return this.http.request(queryURL).map((res: any) =&gt; res.json());
  }


  searchBackEnd(query: string, type: string): Observable&lt;any[]&gt; {

   return this.query(`/${type}`, [
      `id=${query}`
   ]);
 }

}
</code></pre>

<h2>Test for the service</h2>

<pre><code>//CustomerServiceTest.spec.ts:

import {
  TestBed,
  getTestBed,
  async,
  inject
} from '@angular/core/testing';
import {
  Headers, BaseRequestOptions,
  Response, HttpModule, Http, XHRBackend, RequestMethod
} from '@angular/http';

import {ResponseOptions} from '@angular/http';
import {MockBackend, MockConnection} from '@angular/http/testing';
import { CustomerServiceTest } from '../../ts/components/CustomerServiceTest';



describe('CustomerServiceTest test suite', () =&gt; {

let mockBackend: MockBackend;

beforeEach(async(() =&gt; {
TestBed.configureTestingModule({
  providers: [
    CustomerServiceTest,
    MockBackend,
    BaseRequestOptions,
    {
      provide: Http,
      deps: [MockBackend, BaseRequestOptions],
      useFactory:
        (backend: XHRBackend, defaultOptions: BaseRequestOptions) =&gt; {
          return new Http(backend, defaultOptions);
        }
   }
  ],
  imports: [
    HttpModule
  ]
}).compileComponents();

mockBackend = getTestBed().get(MockBackend);

  }));



it('should get data', async(inject([CustomerServiceTest], (CustomerServiceTest) =&gt; {

    let crmSvc:CustomerServiceTest;
    let ContactResponceBody:Object = {
    body: [
        {
            id: '12345678',
            cellPhNum: '+9273839222',
            lastName: 'TestUser',
            firstName: 'TestUser'
        }
        ]
    };
    let contactResponceOptions:ResponseOptions = new ResponseOptions(ContactResponceBody);
    let contactResponse:Response = new Response(contactResponceOptions);


    mockBackend.connections.subscribe(
    (connection: MockConnection) =&gt; {
      connection.mockRespond(contactResponse);
    });

    crmSvc = getTestBed().get(CustomerServiceTest);
    expect(crmSvc).toBeDefined();

})));

});
</code></pre>

<p>Executing npm run test results in error:</p>

<pre><code>Chrome 49.0.2623 (Windows 7 0.0.0) CustomerServiceTest test suite should get data FAILED
    Failed: No provider for [object Object]!
    Error: DI Error
        at NoProviderError.Error (native)
        at NoProviderError.ZoneAwareError (karma.entry.js:43703:33)
        at NoProviderError.BaseError [as constructor] (karma.entry.js:6062:34)
        at NoProviderError.AbstractProviderError [as constructor] (karma.entry.js:32848:16)
        at new NoProviderError (karma.entry.js:32879:16)
        at ReflectiveInjector_._throwOrNull (karma.entry.js:53504:19)
        at ReflectiveInjector_._getByKeyDefault (karma.entry.js:53532:25)
        at ReflectiveInjector_._getByKey (karma.entry.js:53495:25)
        at ReflectiveInjector_.get (karma.entry.js:53304:21)
        at TestBed.get (karma.entry.js:9842:67)
</code></pre>

<p>Apparently, some dependency is missing, but I can't understand what it is. Could anyone explain where to look? At first glance - all providers are at place...</p>
",https://stackoverflow.com/questions/41678692/karmajasmineangular2-unit-testing-http-service-error-no-provider-for-object,"['unit-testing', 'angular', 'karma-jasmine']",1211,TRUE,2,1
ASP.NET MVC - unit testing creation of action method URL&#39;s in a business assembly,"<p>I'm trying to write some unit tests for my ASP.NET MVC code, but I'm hitting a road block.</p>

<p>I have entity partial classes (in a business class library assembly) that need to determine a URL to call for an action method and controller. In order to do that, I found this snippet of code which works nicely - but alas, this uses the <code>HttpContext.Current</code> and thus prevents me from writing any unit tests:</p>

<pre><code>public string NavigateUrl 
{
    get 
    {
            HttpContextWrapper httpContextWrapper = new HttpContextWrapper(HttpContext.Current);
            UrlHelper urlHelper = new UrlHelper(new RequestContext(httpContextWrapper, RouteTable.Routes.GetRouteData(httpContextWrapper)));

            string url = urlHelper.Action(""SomeAction"", ""MyController"");
    }
}
</code></pre>

<p>I am reading about the <code>HttpContextBase</code> - but how does this come into play here?? Or is there another way to determine an action URL inside an entity class (that is in a business assembly - <strong>NOT</strong> the MVC project and not inside a controller or other MVC infrastructure class)?</p>

<p><strong>Update:</strong> I need to return this URL from an entity class as a string, since I need to use it in a grid as the navigation URL of a hyperlink. And in reality, there are numerous conditions being checked and the URL string returned can be one of several possibilities - so I cannot just replace it by a single controller call...</p>
",https://stackoverflow.com/questions/47328987/asp-net-mvc-unit-testing-creation-of-action-method-urls-in-a-business-assembl,"['c#', 'unit-testing', 'asp.net-mvc-5', 'httpcontext']",482,TRUE,2,1
Unit testing Angular 2 JS code without using browser and Karma test runner,"<p>I am trying to execute the unit test cases from <a href=""https://github.com/angular/quickstart/archive/master.zip"" rel=""nofollow noreferrer"">QuickStart</a> Seed from Angular official site.</p>
<p>I want to start using only Jasmine for unit testing so I have removed karma references from the project. The 'app.component.spec.ts' containing unit test cases is compiled fine to JS (using Gulp task), however, when I try to execute them I am getting below error:</p>
<pre><code> var /** @type {?} */ meta = Reflect.getOwnMetadata('propMetadata', target.constructor) || {};
                                                    ^

TypeError: Reflect.getOwnMetadata is not a function
    at PropDecorator (node_modules\@angular\core\bundles\core.umd.js:463:53)
    at __decorate (app.component.js:5:110)
    at Object.&lt;anonymous&gt; (app.component.js:23:1)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
</code></pre>
<p>Though haven't tried, it would work fine with Karma set up as provided in QuickStart seed.
<br/>However, it would helpful to know why doesn't work with only Jasmine? Also, is there any other JS library need to be imported for making it work.</p>
<p>Current app.component.spec.ts: (again same as seed)</p>
<pre><code>import { AppComponent } from '../app/app.component';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
 
describe('AppComponent', function () {
    let de: DebugElement;
    let comp: AppComponent;
    let fixture: ComponentFixture&lt;AppComponent&gt;;

    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            declarations: [AppComponent]
        }).compileComponents();
    }));

    beforeEach(() =&gt; {
        fixture = TestBed.createComponent(AppComponent);
        comp = fixture.componentInstance;
        de = fixture.debugElement.query(By.css('h1'));
    });

    it('should create component', () =&gt; expect(comp).toBeDefined());

    it('should have expected &lt;h1&gt; text', () =&gt; {
        fixture.detectChanges();
        const h1 = de.nativeElement;
        expect(h1.innerText).toMatch(/angular/i,
            '&lt;h1&gt; should say something about &quot;Angular&quot;');
    });
});
</code></pre>
<p><strong>Update:</strong>
The method causing errors is defined in ES7/reflect. I have added the required imports (Thanks @peeskillet for help). The updated test spec looks like below:</p>
<pre><code>import '../node_modules/core-js/client/shim.min';
import 'core-js/es6';
import 'core-js/es7/reflect';
import '../node_modules/zone.js/dist/zone-node';
import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/proxy';
import 'zone.js/dist/jasmine-patch';    

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { AppComponent, secondCmp } from '../app/app.component';

import {
    BrowserDynamicTestingModule,
    platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';

TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());

describe('1st tests', () =&gt; {
    it('true is true', () =&gt; expect(true).toBe(true));
});

describe('AppComponent1', function () {
    let de: DebugElement;
    let comp: AppComponent;
    let fixture: ComponentFixture&lt;AppComponent&gt;;

    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            declarations: [AppComponent, secondCmp]
        }).compileComponents();
    }));

    beforeEach(() =&gt; {
        console.log(AppComponent.toString());
        fixture = TestBed.createComponent(AppComponent);
        comp = fixture.componentInstance;
        de = fixture.debugElement.query(By.css('#welcome'));
    });

    it('should create component', () =&gt; expect(comp).toBeDefined());

    it('should have setup success text', () =&gt; {
        fixture.detectChanges();
        const h1 = de.nativeElement;
        expect(h1.innerText).toContain('setup is successful');
    });
});
</code></pre>
<br/>
<p>Now, I'm getting below error at TestBed.createComponent:</p>
<pre><code> ReferenceError: document is not defined
 Stack:
    ReferenceError: document is not defined
        at BrowserDomAdapter.defaultDoc (node_modules\@angular\platform-browser\bundles\platform-browser.umd.js:2015:71)
</code></pre>
<p>However, the above tests works fine with Karma test runner.</p>
<p>It looks like, the angular unit cases require document object which would be available in user agent like browser.
<br/></p>
<p>
So, my question is browser is always required for executing Angular unit test cases?
</p>
",https://stackoverflow.com/questions/42348209/unit-testing-angular-2-js-code-without-using-browser-and-karma-test-runner,"['javascript', 'unit-testing', 'angular', 'typescript', 'jasmine']",1036,FALSE,2,0
Not able to get url parameter while unit testing Django&#39;s rest api using APIRequestFactory,"<p>I have created a rest api using Django's <code>rest_framework</code>. It's created using class based view.</p>

<p><strong>views.py</strong></p>

<pre><code>import logging
from rest_framework.views import APIView
from rest_framework.authentication import BasicAuthentication, SessionAuthentication, TokenAuthentication
from rest_framework.response import Response

from handlers.product import get_data

log = logging.getLogger(__name__)

class ProductView(APIView):
    authentication_classes = (TokenAuthentication, BasicAuthentication, SessionAuthentication)

    def get(self, request, **kwargs):
        try:
            product_id = kwargs['product_id']
            response = get_data(product_id)
            return Response(response)
        except KeyError as key:
            log.exception(key)
            return Response({'error_msg': '{} is required'.format(key)}, status=400)
</code></pre>

<p><strong>urls.py</strong></p>

<pre><code>url(r'^product/(?P&lt;product_id&gt;[0-9]+)/data/$', ProductView.as_view(), name='product'),
</code></pre>

<p>And this is what I have tried,</p>

<pre><code>import pytest
from django.contrib.auth.models import User
from mixer.backend.django import mixer
from rest_framework.authtoken.models import Token
from rest_framework.test import APIRequestFactory

from views import *

pytestmark = pytest.mark.django_db


@pytest.fixture()
def token():
    user = mixer.blend(User)
    return Token.objects.create(user=user)


class TestProductView:

    def test_get_data(self, token):
        factory = APIRequestFactory()
        request = factory.get('/product/100230/data/', HTTP_AUTHORIZATION='Token {}'.format(token))
        response = ProductView.as_view()(request)
        assert response.status_code == 200
</code></pre>

<p>My test fails because I get an exception,</p>

<pre><code>KeyError: 'product_id'
</code></pre>

<p>But when I run my app and request the api from browser it takes the product_id from the url.</p>

<p>Please note that I really have to use <code>kwargs</code> in <code>get</code> api method because later I want to make get_data generic and pass all the url params and query params to it.</p>

<hr>

<h2>Update (29/01/2018)</h2>

<p>Django test client (<code>django.test.Client</code>) came to the rescue! </p>

<p>I have started using it instead of <code>RequestFactory</code> whenever I have url params. I am not sure if I should put that as answer on this post.</p>
",https://stackoverflow.com/questions/47564960/not-able-to-get-url-parameter-while-unit-testing-djangos-rest-api-using-apirequ,"['python', 'django', 'rest']",851,FALSE,7,1
How to Unit testing Angular4 HttpClient Service for both success and error condition,"<p>New to angular I need help to unit test this code to get full coverage. I'm trying to verifying mock response return by promise but getting <code>undefined</code> every time.        </p>

<pre><code>getData(): Promise&lt;{}&gt; {
    const apiUrl = 'resources/data.json';
    return this.http
      .get(apiUrl)
      .toPromise()
      .then(this.extractData)
      .catch(this.handleError);
  }

  private extractData(res: any) {
    return res;
  }

  private handleError(error: any) {
    return Promise.reject(error);
  }
}
</code></pre>
",https://stackoverflow.com/questions/45596302/how-to-unit-testing-angular4-httpclient-service-for-both-success-and-error-condi,['angular'],307,FALSE,1,0
C# Unit Testing (Xunit and Moq) - Test an interface and its implementations separately,"<p>I want to separate the unit tests for testing the interface behavior itself and the additional business behavior of the implementations.</p>

<pre><code>public interface IIncrementor
{
    void Increment();

    int Count { get; }
}

public class AIncrementor : IIncrementor { /* Implementation */ }
public class BIncrementor : IIncrementor { /* Implementation */ }
</code></pre>

<p>To ensure the correctness of the business behavior of an interface I need to check all according implementations against my defined unit tests. Of course every implementation has its own additional behavior to test, but I don't want to repeat myself over and over again.</p>

<p>My current solution was to create an abstract test-class with an abstract property for the subclasses to implement.</p>

<pre><code>public abstract class IIncrementorTest
{
    protected abstract IIncrementor Incrementor { get; }

    [Fact]
    public void WhenIncremented_ThenCounterHasCorrectValue()
    {
        var oldCount = Incrementor.Count;

        Incrementor.Increment();

        Assert.Equal(oldCount + 1, Incrementor.Count);
    }
}

public class AIncremetorTest : IIncrementorTest
{
    protected override IIncrementor Incrementor =&gt; new AIncrementor();

    [Fact]
    public void WhenSomeAdditional_ThenCheckSomething() { /* More test */ }
}

public class BIncremetorTest : IIncrementorTest
{
    protected override IIncrementor Incrementor =&gt; new BIncrementor();

    [Fact]
    public void WhenSomeAdditional_ThenCheckSomething() { /* More test */ }
}
</code></pre>

<p>But that leads to some problems, e.g. when a test case needs to build an instance differently which is very likely to happen. Would you suggest to create abstract properties for these cases?</p>

<pre><code>protected abstract IIncrementor IncrementorForCheckingSomething { get; }
</code></pre>

<p>Or is there a best practice approach which solves this interface-test problem comprehensively?</p>
",https://stackoverflow.com/questions/44048210/c-unit-testing-xunit-and-moq-test-an-interface-and-its-implementations-sepa,"['c#', 'unit-testing', 'mocking', 'moq', 'xunit']",1400,FALSE,1,1
Python - How to import a class from a different directory for unit testing,"<p>This question has been asked a hundred times, but every solution I've seen does not work for me, and I'm getting extremely frustrated so here's 101.</p>

<p>Given the project directory:</p>

<pre><code>project/
  src/
    __init__.py
    student.py
  test/
    __init__.py
    student_test.py
</code></pre>

<p>My student.py file:</p>

<pre><code>class Student:
  def __init__(self, name, age):
   self.full_name = name
   self.age = age
</code></pre>

<p>My student_test.py file:</p>

<pre><code>from nose.tools import *
import src
from src import Student

def test_basic():
  print ""I RAN!""

def test_student():
  s = Student(""Steve"", 42)
  assert s.age == 42
</code></pre>

<p>I get the following errors:</p>

<pre><code>======================================================================
ERROR: Failure: ImportError (cannot import name Student)
----------------------------------------------------------------------
    from src import Student
ImportError: cannot import name Student
</code></pre>

<p>I've tried variations of the import yada yada and adding the <code>src</code>directory to path, but nothing seems to work here. WTF am I doing wrong?</p>
",https://stackoverflow.com/questions/43579874/python-how-to-import-a-class-from-a-different-directory-for-unit-testing,['python-2.7'],74,TRUE,1,1
Error while using child component in parent component - Angular 2 Unit Testing (KarmaJasmine),"<p><code>template parse error</code> when using child component in parent.</p>

<p>I have two components. </p>

<pre><code>  1. CardComponent
  2. InfoComponent
</code></pre>

<p>My CardComponent's HTML</p>

<pre><code>     &lt;div class=""footer""&gt;
       &lt;full-info&gt;&lt;/full-info&gt;
     &lt;/div&gt;
</code></pre>

<p>CardComponent's Spec File: </p>

<pre><code> beforeEach(async(() =&gt; {
TestBed.configureTestingModule({
  declarations: [InfoComponent, CardComponent ],
  imports: [
      FormsModule,
      MaterialModule.forRoot()
  ],
  schemas: [ NO_ERRORS_SCHEMA ], //Used CUSTOM_ERRORS_SCHEMA also
})
.compileComponents();
  }));
</code></pre>

<p>My InfoComponent ts code:</p>

<pre><code>   import { Component, Input } from '@angular/core';


   @Component({
            selector: 'full-info',
            templateUrl: './full-info.component.html',
            styleUrls: ['./full-info.component.css']
            })

   export class InfoComponent {
     public fullInfo;
    }
</code></pre>

<p>InfoComponent spec declaration:</p>

<pre><code>     beforeEach(async(() =&gt; {
TestBed.configureTestingModule({
  declarations: [ InfoComponent ],
  imports: [
      FormsModule,
      MaterialModule.forRoot()
  ],
  schemas: [ NO_ERRORS_SCHEMA ]
})
.compileComponents();
   }));
</code></pre>

<p>When I run test case for these two components <strong>individually</strong> then it is working fine.</p>

<p>When I am running these test cases at a time then I am getting error:</p>

<pre><code>    'full-info' is not a known element:
1. If 'full-info' is an Angular component, then verify that it is part of this module.
2. If 'full-info' is a Web Component then add ""CUSTOM_ELEMENTS_SCHEMA"" to the '@NgModule.schemas' of this component to suppress this message. (""
  &lt;/div&gt;
  &lt;div class=""footer""&gt;
    [ERROR -&gt;]&lt;full-info&gt;&lt;/full-info&gt;
  &lt;/div&gt;
</code></pre>

<p>I have imported <code>InfoComponent</code> in <code>CardComponent</code> even then I am getting this error. I am not able to find the issue. I any one knows then it would be great for me.</p>
",https://stackoverflow.com/questions/44304474/error-while-using-child-component-in-parent-component-angular-2-unit-testing,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",494,FALSE,1,1
Ionic 2 Unit Testing: &quot;Uncaught TypeError: Cannot read property &#39;_getPortal&#39; of undefined throw&quot;,"<p>I am a beginner to ionic 2 unit testing.I am stuck in an error and couldn't able to resolve:
""Uncaught TypeError: Cannot read property '_getPortal' of undefined throw""</p>

<p>Here is my ts file:</p>

<pre><code>//Angular Module Import
import { Component, OnInit } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { ConfigService } from '../../../providers/config.service';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import { ViewController } from 'ionic-angular';

//App Services Imports
import { Globals } from '../../../providers/globals';
import { GetPaymentusService } from '../../../providers/getPaymentusUrl.service';

//App Component Imports
import { PolicyDocumentPage } from '../document/policydocument';

@Component({
    selector: 'page-watercraft-policy',
    templateUrl: 'watercraftpolicy.html'
})
export class WaterCraftPolicyPage implements OnInit {

    watercraftPolicyData: any;
    index: number;
    customerName: any;

    constructor(public navCtrl: NavController, 
                public navParams: NavParams, 
                public global: Globals, 
                public http: Http,
                public _config: ConfigService, 
                public paymentusService: GetPaymentusService,
                public viewCtrl: ViewController) {
    }

    ionViewDidLoad() {
        this.viewCtrl.setBackButtonText('My Policy');
    }

    ngOnInit() {
        this.watercraftPolicyData = this.navParams.get('param1');
        this.index = this.navParams.get('param2');
        this.customerName = this.navParams.get('param3');
        this.watercraftPolicyData.csppolicyNickName = ""WATERCRAFT"";
    }

    policyDocumentPage() {
        this.navCtrl.push(PolicyDocumentPage, {
            param1: this.watercraftPolicyData,
            param2: this.index,
            param3: this.customerName
        });
    }

    myBillsPage() {
        let text: string;
        this.paymentusService.getPolicy(this.watercraftPolicyData)
            .map((policyRequest) =&gt; {
                 if (policyRequest.header.error.errorCode === '0001'){
                    this._config.showError();
                } else if(policyRequest.header.status === 'UNAUTHORIZED'){
                             this._config.showUnathorisedError();
                        }else if(policyRequest.header.error.errorCode === '1001'){
                             this._config.showUnexpectedError();
                         }else if(policyRequest.status === '403' ||
                                 policyRequest.header.status === 'FORBIDDEN'){
                             this._config.showSessionTimeOutError();
                      }else{
                this.global.payBill(policyRequest.customerPayment.paymentusURL);
            }
            }).subscribe(response =&gt; { },
                    error =&gt; {
                        this._config.showError();
                    });



    }

}
</code></pre>

<p>Unit test File:</p>

<pre><code>  import { TestBed, ComponentFixture, async } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { IonicModule } from 'ionic-angular';
import { NavController,NavParams} from 'ionic-angular';
import { ViewController } from 'ionic-angular';
import { AlertController } from 'ionic-angular';
import { File } from '@ionic-native/file';
import { FileOpener } from '@ionic-native/file-opener';
import { PdfViewerPage } from '../viewer/pdfviewer';

import { HanoverApp } from '../../../app/app';
import { WaterCraftPolicyPage } from './watercraftpolicy';

import { ViewControllerMock } from '../../../mocks';
import { MockNavParams } from '../../../mocks';
import { NavMock } from '../../../mocks';
import { MockAlertController } from '../../../mocks';

import { Globals } from '../../../providers/globals';
import { GetPaymentusService } from '../../../providers/getPaymentusUrl.service';
import { GetIdCardService } from '../../../providers/getIdCard.service';
import { ConfigService } from '../../../providers/config.service';
import { Http, Response, RequestOptions, Headers } from '@angular/http';


let comp: WaterCraftPolicyPage;
let fixture: ComponentFixture&lt;WaterCraftPolicyPage&gt;;
let de: DebugElement;
let el: HTMLElement;



describe('Page: WaterCraftPolicyPage', () =&gt; {

    beforeEach(async(() =&gt; {

        TestBed.configureTestingModule({

            declarations: [HanoverApp, WaterCraftPolicyPage],

            providers: [NavController,{provide: NavParams, useClass: MockNavParams},
            {provide: ViewController, useClass: ViewControllerMock},
            Globals,GetPaymentusService,GetIdCardService,ConfigService],

            imports: [
                IonicModule.forRoot(HanoverApp)
            ]

        }).compileComponents();

    }));

    beforeEach(() =&gt; {

        fixture = TestBed.createComponent(WaterCraftPolicyPage);
        comp    = fixture.componentInstance;

    });

    afterEach(() =&gt; {
        fixture.destroy();
        comp = null;
        de = null;
        el = null;
    });

    it('is created', () =&gt; {
        expect(fixture).toBeTruthy();
        expect(comp).toBeTruthy();
    });

});
</code></pre>

<p>mocks.ts:</p>

<pre><code>export class NavMock {

  public pop(): any {
    return new Promise(function(resolve: Function): void {
      resolve();
    });
  }

  public push(): any {
    return new Promise(function(resolve: Function): void {
      resolve();
    });
  }

  public getActive(): any {
    return {
      'instance': {
        'model': 'something',
      },
    };
  }

  public setRoot(): any {
    return true;
  }
}

export class ViewControllerMock {

    public readReady: any = {
        emit(): void {

        },
        subscribe(): any {

        }
    };

    public writeReady: any = {
        emit(): void {

        },
        subscribe(): any {

        }
    };

    public contentRef(): any {
        return new Promise(function (resolve: Function): void {
            resolve();
        });
    }

    public didEnter(): any {
        return new Promise(function (resolve: Function): void {
            resolve();
        });
    }

    public didLeave(): any {
        return new Promise(function (resolve: Function): void {
            resolve();
        });
    }

    public onDidDismiss(): any {
        return new Promise(function (resolve: Function): void {
            resolve();
        });
    }

    public onWillDismiss(): any {
        return new Promise(function (resolve: Function): void {
            resolve();
        });
    }

    public willEnter(): any {
        return new Promise(function (resolve: Function): void {
            resolve();
        });
    }

    public willLeave(): any {
        return new Promise(function (resolve: Function): void {
            resolve();
        });
    }

    public willUnload(): any {
        return new Promise(function (resolve: Function): void {
            resolve();
        });
    }

    public dismiss(): any {
        return true;
    }

    public enableBack(): any {
        return true;
    }

    public getContent(): any {
        return true;
    }

    public hasNavbar(): any {
        return true;
    }

    public index(): any {
        return true;
    }

    public isFirst(): any {
        return true;
    }

    public isLast(): any {
        return true;
    }

    public pageRef(): any {
        return true;
    }

    public setBackButtonText(): any {
        return true;
    }

    public showBackButton(): any {
        return true;
    }

    public _setHeader(): any {
        return true;
    }

    public _setIONContent(): any {
        return true;
    }

    public _setIONContentRef(): any {
        return true;
    }

    public _setNavbar(): any {
        return true;
    }

    public _setContent(): any {
        return true;
    }

    public _setContentRef(): any {
        return true;
    }

    public _setFooter(): any {
        return true;
    }

}


export class MockNavParams{

   public get(param): any{
    return {'csppolicyNickName':'data'};
  }
}



export class MockAlertController{
 create(): any{
   return true;
 };

}
</code></pre>
",https://stackoverflow.com/questions/44149489/ionic-2-unit-testing-uncaught-typeerror-cannot-read-property-getportal-of,"['angular', 'ionic2', 'karma-jasmine']",1168,FALSE,1,0
"Unit testing a Delegate of a request parameter of a repository C#,Moq","<p>In the below code,I need to check whether in the request ""System"" is added with the value ""Portal"".</p>

<pre><code>var rq = new RestBaseRequest{AmendHeaders = x =&gt; x.Add(""Systerm"", ""Portal"")};

var repositoryResponse = await this.restRepository.GetAsync(rq,cancellationToken, loggingContext);
</code></pre>

<p>The RestBaseRequest class looks like  below</p>

<pre><code>  public class RestBaseRequest
        {
            public RestBaseRequest();

            public Action&lt;HttpRequestHeaders&gt; AmendHeaders { get; set; }
        }
</code></pre>

<p>I tried the way as below</p>

<pre><code>[Test]
        public async Task TestRequestHeaderConatainsRequestingSystem()
        {
            // Arrange
            var restRepository = new Mock&lt;IRestRepository&lt;LifeBondResponse&gt;&gt;();
            RestBaseRequest requestBase = null;
            CancellationToken token = new CancellationToken();
            LoggingContext context = null;


 restRepository.Setup(x =&gt; x.GetAsync(
                    It.IsAny&lt;RestBaseRequest&gt;(),
                    It.IsAny&lt;CancellationToken&gt;(),
                    It.IsAny&lt;LoggingContext&gt;())).Callback((RestBaseRequest baseRequest, CancellationToken cancellationToken, LoggingContext loggingContext) =&gt;
                    {
                        requestBase = baseRequest;
                        token = cancellationToken;
                        context = loggingContext;
                    })
                .ReturnsAsync(new Service&lt;LifeBondResponse&gt;
                {
                    Status = GeneralResponseType.Success,
                });

 var request = new CustomerRequest&lt;InvestmentBondPolicy&gt;
            {
                TypeOfRequest = CustomerRetrieveType.Number,
                Id = ""12345"",
                Data = new Policy()
                {
                    PolicyNumber = ""123456"",
                }
            };

            var repository = new BondRepository(this.authoriseService.Object, restRepository.Object);
            var rs = await repository.GetPolicyAsync(request, new CancellationToken());

}
</code></pre>

<p>since there is no public properties in RestBaseRequest,I couldn't able to do check further.Is there any way to test this or suggestions?</p>
",https://stackoverflow.com/questions/45932387/unit-testing-a-delegate-of-a-request-parameter-of-a-repository-c-moq,"['c#', 'unit-testing', 'tdd', 'moq']",250,TRUE,1,2
unit testing - How can I pass string with comma to a testcase in DUnitX,"<p>If I have a unit test with <strong>string</strong> parameter, and I want to check if the input string has a <strong>comma</strong> (<code>,</code>) somewhere, I should create an input string with a comma in it. </p>

<p>But how to pass it to the TestCase?</p>

<pre><code>[Test]    
[TestCase('TestA', '12,34')]  //AValue1 gets only '12' instead of '12,34'
[TestCase('TestB', '12,,34')] //AValue1 gets only '12' instead of '12,34'
[TestCase('TestC', '12/,34')] //AValue1 gets only '12/' instead of '12,34'
[TestCase('TestD', '12\,34')] //AValue1 gets only '12\' instead of '12,34'
procedure ValueShouldHaveComma(const AValue1: string); 
</code></pre>
",https://stackoverflow.com/questions/44538544/unit-testing-how-can-i-pass-string-with-comma-to-a-testcase-in-dunitx,"['unit-testing', 'delphi', 'dunitx']",657,TRUE,6,1
Android Unit testing run all class tests fail but every single method run successfully,"<p>please help me this when i run all the class test methods together the test fails in a method although this method when i run it alone it succeed</p>

<pre><code>public class RealEstatesListPresenterTest {
RealEstatesListPresenter mRealEstatesListPresenter;
@Mock
private RealEstateListBusiness mRealEstateListBusiness;
@Mock
private RealEstatesListContract.View mRealEstatesView;

@BeforeClass
public static void setUpClass() {
    RxAndroidPlugins.setInitMainThreadSchedulerHandler(__ -&gt; Schedulers.trampoline());
}

@Before
public void setupTasksPresenter() {
    MockitoAnnotations.initMocks(this);
    mRealEstatesListPresenter = new RealEstatesListPresenter(mRealEstatesView);
    mRealEstatesListPresenter.setmRealEstateListBusiness(mRealEstateListBusiness);
}

@Test
public void testWhenGetAllRealEstates_ProgressISDisplayed() {
    when(mRealEstateListBusiness.getAllRealEstates()).thenReturn(Observable.create(sub -&gt; {
        sub.onNext(new ArrayList&lt;&gt;());
        sub.onComplete();
    }));
    mRealEstatesListPresenter.getAllRealEstates();
    verify(mRealEstatesView, times(1)).showLoading();
}

@Test
public void testWhenGetAllRealEstatesSuccess_ProgressISHidden() {
    when(mRealEstateListBusiness.getAllRealEstates()).thenReturn(Observable.create(sub -&gt; {
        sub.onNext(new ArrayList&lt;&gt;());
        sub.onComplete();
    }));
    mRealEstatesListPresenter.getAllRealEstates();
    verify(mRealEstatesView, times(1)).hideLoading();
}

@Test
public void testWhenGetAllRealEstatesError_ProgressISHidden() {
    when(mRealEstateListBusiness.getAllRealEstates()).thenReturn(Observable.create(sub -&gt; {
        sub.onError(new Throwable());
    }));
    mRealEstatesListPresenter.getAllRealEstates();
    verify(mRealEstatesView, times(1)).hideLoading();
}

@AfterClass
public static void tearDownClass() {
    RxAndroidPlugins.reset();
}}
</code></pre>

<p>when i run all the tests together the first two methods pass but the last one fail (testWhenGetAllRealEstatesError_ProgressISHidden) but when i run it alone it pass.</p>

<p>and this is the presenter code</p>

<pre><code>public class RealEstatesListPresenter implements RealEstatesListContract.Presenter {

private RealEstatesListContract.View mView;
private RealEstateListBusiness mRealEstateListBusiness;
private CompositeDisposable mSubscriptions;

@Inject
public RealEstatesListPresenter(RealEstatesListContract.View view) {
    this.mView = view;
    mSubscriptions = new CompositeDisposable();
}

@Inject
public void setmRealEstateListBusiness(RealEstateListBusiness mRealEstateListBusiness) {
    this.mRealEstateListBusiness = mRealEstateListBusiness;
}

@Inject
public void setupListeners() {
    mView.setPresenter(this);
}

@Override
public void unSubscribe() {
    mSubscriptions.clear();
}

@Override
public void getAllRealEstates() {
    mView.showLoading();
    mSubscriptions.add(mRealEstateListBusiness.getAllRealEstates().observeOn(AndroidSchedulers.
            mainThread()).subscribeOn(Schedulers.io()).subscribe((realEstatesItems) -&gt; {
        mView.hideLoading();
        mView.showAllRealEstates(realEstatesItems);
    }, throwable -&gt; {
        mView.hideLoading();
        mView.showErrorMessage(throwable.getMessage());
    }));
}
</code></pre>

<p>}</p>
",https://stackoverflow.com/questions/44169967/android-unit-testing-run-all-class-tests-fail-but-every-single-method-run-succes,"['android', 'unit-testing', 'mockito', 'android-testing', 'rx-android']",2332,TRUE,6,3
Bringing unit testing to angular2 app with karma and systemjs (templateUrl path issue),"<p>I have a small trivial angular2 <a href=""https://github.com/ibqn/ng2-quick-start"" rel=""nofollow noreferrer"">application</a> which is relying on <code>systemjs</code> with JiT and AoT compilation.</p>

<p>The key difference here, compared to other setups is that I explicitly do not want to set the <code>moduleId: module.id</code> into the definition of the component, as there is absolutely no use for it during the AoT compilation (which stands for the desired end-result for production). To get things going in the JiT mode I prefer to host testing server from multiple folders (cp. this <a href=""https://stackoverflow.com/questions/37178192/angular2-what-is-the-meanings-of-module-id-in-component/41170237#41170237"">reference</a>)</p>

<pre><code>import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  // moduleId: module.id,
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css']
})
export class AppComponent {
  ...
}
</code></pre>

<p>The only bottleneck here is that I cannot get karma based unit tests working as I was not able to find a way to proxy the template file to the correct location...</p>

<p>When I run karma I am struggling to proxy the path to the template file:</p>

<pre><code>[1] 08 02 2017 13:03:20.768:INFO [karma]: Karma v1.4.1 server started
... 
[1] 08 02 2017 13:03:22.579:WARN [web-server]: 404: /app.component.html
    Chrome 56.0.2924 (Linux 0.0.0) AppComponent should create component FAILED
[1]     Error: This test module uses the component AppComponent which is using a ""templateUrl"" or ""styleUrls"", but they were never compiled. Please call ""TestBed.compileComponents"" before your test.
[1]     Expected undefined to be defined.
</code></pre>
",https://stackoverflow.com/questions/42113416/bringing-unit-testing-to-angular2-app-with-karma-and-systemjs-templateurl-path,"['angular', 'typescript', 'karma-runner', 'systemjs', 'angular2-aot']",413,FALSE,1,0
Injecting data before creating mock component with TestBed - unit testing in angular 4,"<p>I would like to inject data to <code>DeviceMarkerComponent</code> before running this:</p>

<pre><code>let component: DeviceMarkerComponent;
let fixture: ComponentFixture&lt;DeviceMarkerComponent&gt;;
...

fixture = TestBed.createComponent(DeviceMarkerComponent);
component = fixture.componentInstance;
</code></pre>

<p><code>DeviceMarkerComponent</code> uses variables in <code>ngOnInit</code> and I can't create the component without initializing the variables. <code>NgOnInit</code> is firing when <code>TestBed.CreateComponent</code> is called and it causes error, so I have to set these variables or modify a code which I'm testing :(</p>

<p><a href=""https://i.stack.imgur.com/TNv7I.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/TNv7I.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/46448046/injecting-data-before-creating-mock-component-with-testbed-unit-testing-in-ang,"['angular', 'jasmine', 'karma-runner']",1429,FALSE,1,2
TypeScript Unit-Testing on VSTS with Continuous Integration in a C# Web Application,"<p>I have a web application with continuous integration via visual studio team services and I want to add unit tests for my typescript code.</p>

<hr>

<p><strong>First try</strong></p>

<p>At first I tried to create a Blank Node.js Console Application in my solution. I wrote some tests (with 'mocha',etc...) which worked fine locally. But as I commited the solution I noticed the build server not being able to...well...build: </p>

<pre><code>Error : web.config not found in project, to create a project to deploy to Microsoft Azure you must create an Azure Node.js project.
</code></pre>

<p>This message suggested that msbuild wanted to create a deployable package of my NodeJS Project even though I only used it for testing purposes. The first thing that came to mind was to add a minimal web.config even though I did not want to publish the NodeJS project:</p>

<pre><code>Error MSB4062: The ""TypeScript.Tasks.FormatLocalizedString"" task could not be loaded from the assembly C:\xxx\Microsoft.TypeScript.MSBuild.2.3.3\build\\..\tools\net45\TypeScript.Tasks.dll.  Confirm that the &lt;UsingTask&gt; declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask.
</code></pre>

<p>I don't really see any way out of this...</p>

<hr>

<p><strong>Second try</strong></p>

<p>Then I tried to use a UnitTest Project instead of the NodeJS Project. Surely this will work, or so I thought. With this approach I ran into the problem that VS Test did not recognize my Unit Tests (which worked fine on my NodeJS project) as there was no option to mark my files with the appropriate ""Test Framework"" attribute which was present on the file properties in the NodeJS Project. Instead there were the default file options for ""Custom Tool"", etc:</p>

<p><a href=""https://i.stack.imgur.com/IbZk3.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/IbZk3.png"" alt=""enter image description here""></a></p>

<p>No Problem! I'll just adjust the .csproj file directly!</p>

<pre><code> &lt;TypeScriptCompile Include=""main.test.ts""&gt;
  &lt;SubType&gt;Code&lt;/SubType&gt;
  &lt;TestFramework&gt;Mocha&lt;/TestFramework&gt;
  &lt;Publish&gt;False&lt;/Publish&gt;
&lt;/TypeScriptCompile&gt;
</code></pre>

<p>But, alas, no dice...The Tests still could not be found by VS Test</p>

<hr>

<p><strong>Question</strong></p>

<p>What is the best practices approach here? Is there something I'm not thinking of? Was the 'First try' correct and I just did not find the correct option to disable the publishing of my NodeJS App?</p>

<hr>

<p><strong>PS</strong></p>

<p>I now think my first approach was the correct one. Just to be clear: A lot of things already worked:</p>

<ul>
<li>Installed Node Tools for Visual Studio on the Build Server</li>
<li>Compiling typescript via VSTS</li>
<li>Running Tests in VS Test locally</li>
<li>List item</li>
<li>Running <code>npm install</code> on build (in VSTS)</li>
</ul>

<p>Now all I need is for the build to go through :/
I now notice that I did not write the full error message for the last error in the first approach:</p>

<pre><code>##[error]C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\TypeScript\Microsoft.TypeScript.targets(60,5): Error MSB4062: The ""TypeScript.Tasks.FormatLocalizedString"" task could not be loaded from the assembly C:\Agent-PaketBuildIntern1\_work\54\s\packages\Microsoft.TypeScript.MSBuild.2.3.3\build\\..\tools\net45\TypeScript.Tasks.dll.  Confirm that the &lt;UsingTask&gt; declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask.
</code></pre>

<p>So we see here that it uses the .targets file under C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\TypeScript\ and not the one under ......\packages\Microsoft.TypeScript.MSBuild.2.3.3\tools</p>

<p>Could this be the problem? How do I go about correcting that?</p>

<hr>

<p>.njsproj file:</p>

<pre><code> &lt;Project DefaultTargets=""Build"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" ToolsVersion=""4.0""&gt;
  &lt;PropertyGroup&gt;
    &lt;VisualStudioVersion&gt;14.0&lt;/VisualStudioVersion&gt;
    &lt;VSToolsPath Condition=""'$(VSToolsPath)' == ''""&gt;$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)&lt;/VSToolsPath&gt;
    &lt;Name&gt;MyProjectName&lt;/Name&gt;
    &lt;RootNamespace&gt;MyProjectName&lt;/RootNamespace&gt;
    &lt;SccProjectName&gt;SAK&lt;/SccProjectName&gt;
    &lt;SccProvider&gt;SAK&lt;/SccProvider&gt;
    &lt;SccAuxPath&gt;SAK&lt;/SccAuxPath&gt;
    &lt;SccLocalPath&gt;SAK&lt;/SccLocalPath&gt;
  &lt;/PropertyGroup&gt;
  &lt;Import Project=""$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props"" Condition=""Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"" /&gt;
  &lt;PropertyGroup&gt;
    &lt;Configuration Condition="" '$(Configuration)' == '' ""&gt;Debug&lt;/Configuration&gt;
    &lt;SchemaVersion&gt;2.0&lt;/SchemaVersion&gt;
    &lt;ProjectGuid&gt;5697a590-d15f-401b-b8d8-138bbd5d3330&lt;/ProjectGuid&gt;
    &lt;ProjectHome&gt;.&lt;/ProjectHome&gt;
    &lt;StartupFile&gt;
    &lt;/StartupFile&gt;
    &lt;StartWebBrowser&gt;False&lt;/StartWebBrowser&gt;
    &lt;SearchPath&gt;
    &lt;/SearchPath&gt;
    &lt;WorkingDirectory&gt;.&lt;/WorkingDirectory&gt;
    &lt;OutputPath&gt;.&lt;/OutputPath&gt;
    &lt;TargetFrameworkVersion&gt;v4.0&lt;/TargetFrameworkVersion&gt;
    &lt;ProjectTypeGuids&gt;{3AF33F2E-1136-4D97-BBB7-1795711AC8B8};{9092AA53-FB77-4645-B42D-1CCCA6BD08BD}&lt;/ProjectTypeGuids&gt;
    &lt;TypeScriptSourceMap&gt;true&lt;/TypeScriptSourceMap&gt;
    &lt;TypeScriptModuleKind&gt;CommonJS&lt;/TypeScriptModuleKind&gt;
    &lt;EnableTypeScript&gt;true&lt;/EnableTypeScript&gt;
    &lt;StartWebBrowser&gt;false&lt;/StartWebBrowser&gt;
  &lt;/PropertyGroup&gt;
  &lt;PropertyGroup Condition="" '$(Configuration)' == 'Debug' ""&gt;
    &lt;DebugSymbols&gt;true&lt;/DebugSymbols&gt;
  &lt;/PropertyGroup&gt;
  &lt;PropertyGroup Condition="" '$(Configuration)' == 'Release' ""&gt;
    &lt;DebugSymbols&gt;true&lt;/DebugSymbols&gt;
  &lt;/PropertyGroup&gt;
  &lt;ItemGroup&gt;
    &lt;Content Include=""tsconfig.json""&gt;
      &lt;SubType&gt;Code&lt;/SubType&gt;
    &lt;/Content&gt;
    &lt;Content Include=""package.json"" /&gt;
    &lt;Content Include=""README.md"" /&gt;
    &lt;Content Include=""Web.config"" /&gt;
    &lt;TypeScriptCompile Include=""Scripts\typings\node\node.d.ts"" /&gt;
    &lt;TypeScriptCompile Include=""bootstrap.test.ts""&gt;
      &lt;SubType&gt;Code&lt;/SubType&gt;
      &lt;TestFramework&gt;Mocha&lt;/TestFramework&gt;
      &lt;Publish&gt;False&lt;/Publish&gt;
    &lt;/TypeScriptCompile&gt;
    &lt;TypeScriptCompile Include=""util\templates.ts""&gt;
      &lt;SubType&gt;Code&lt;/SubType&gt;
    &lt;/TypeScriptCompile&gt;
  &lt;/ItemGroup&gt;
  &lt;ItemGroup&gt;
    &lt;Folder Include=""util\"" /&gt;
    &lt;Folder Include=""Scripts\"" /&gt;
    &lt;Folder Include=""Scripts\typings\"" /&gt;
    &lt;Folder Include=""Scripts\typings\node\"" /&gt;
  &lt;/ItemGroup&gt;
  &lt;PropertyGroup&gt;
    &lt;PreBuildEvent&gt;cd $(ProjectDir)
call npm install
    &lt;/PreBuildEvent&gt;
  &lt;/PropertyGroup&gt;
  &lt;Import Project=""..\..\..\packages\Microsoft.TypeScript.MSBuild.2.3.3\build\Microsoft.TypeScript.MSBuild.targets"" Condition=""Exists('..\..\..\packages\Microsoft.TypeScript.MSBuild.2.3.3\build\Microsoft.TypeScript.MSBuild.targets')"" /&gt;
  &lt;Import Project=""$(VSToolsPath)\Node.js Tools\Microsoft.NodejsTools.targets"" /&gt;
&lt;/Project&gt;
</code></pre>
",https://stackoverflow.com/questions/45060116/typescript-unit-testing-on-vsts-with-continuous-integration-in-a-c-web-applicat,"['node.js', 'msbuild', 'mocha.js', 'azure-pipelines']",718,TRUE,0,2
Why runtime.caller(0) is giving different path with &#39;--cover&#39; argument in unit testing,"<p>When trying to execute a unit test function without any argument it  give following output path</p>

<pre><code>C:/Program Files (x86)/Go1.8\bin\go.exe"" test -v gclassec/skyline/loggers -run ^TestCreateLogFilesPath$

filePath:=== C:/GerritNew/goclassec/src/gclassec/skyline/loggers/logs.go
</code></pre>

<p>But when I try to run it with any argument such as <code>--cover</code> the file path value changes as below:</p>

<pre><code>""C:/Program Files (x86)/Go1.8\bin\go.exe"" test -v --cover gclassec/skyline/loggers -run ^TestCreateLogFilesPath$

filePath:=== gclassec/skyline/loggers/_test/_obj_test/logs.go
</code></pre>

<p>I am using <code>runtime.caller(0)</code> to get file path. </p>
",https://stackoverflow.com/questions/44878486/why-runtime-caller0-is-giving-different-path-with-cover-argument-in-unit-t,['go'],224,TRUE,-1,1
how to do unit testing of component with multiple parent routes of ActivatedRoute,"<p>Lets say I have a component that access parent route like this:</p>

<pre><code>ngOnInit() {
    //TODO - FFBZAP-25: far from an ideal solution
    this.sub = this.route.parent.parent.parent.params.subscribe(params =&gt; {
        this.siteId = params[""siteId""];
        this.loadContents();
        this.loadTypes(this.siteId);
    });
}
</code></pre>

<p>My issue is that when I run the test I get</p>

<blockquote>
  <p>Failed: Cannot read property 'undefined' of undefined</p>
</blockquote>

<p>I am not testing the route right now, but I think error should be Because of this line:</p>

<ul>
<li>useValue: { parent: { parent: { parent: { 'params': Observable.from([{ 'siteId': '156' }]) } } } },</li>
</ul>

<p>Here is my Unit-test code:</p>

<pre><code>beforeEach(async(() =&gt; {

    TestBed.configureTestingModule({
        imports: [
            HttpModule,
            RouterTestingModule,
            SharedModule,
            BootstrapModalModule
        ],
        declarations: [
            ContentListComponent,
        ],
        providers: [
            SiteService,
            UserService,
            Modal,
            Overlay,
            {
                provide: ActivatedRoute,
                useValue: { parent: { parent: { parent: { 'params': Observable.from([{ 'siteId': '156' }]) } } } },
            },
            OverlayRenderer,
            AuthHttp,
            MessageService,
        ],
        schemas: [NO_ERRORS_SCHEMA]

    }).compileComponents()
        .then(() =&gt; {
            fixture = TestBed.createComponent(ContentListComponent);
            component = fixture.componentInstance;
            siteService = TestBed.get(SiteService);
            userService = TestBed.get(UserService);
            activatedRoute = TestBed.get(ActivatedRoute);

        });
}));
console.log(""HEUUUYFYYHSIDDHARTHs"", { parent: { parent: { parent: { 'params': Observable.from([{ 'siteId': '11' }]) } } } })
it('should have a defined component', () =&gt; {
    expect(component).toBeDefined();
});
it('Sholud get content-list', async(() =&gt; {

    spyOn(userService, 'getUser')
        .and.returnValue(Observable.of(UpdatedBy));

    spyOn(siteService, 'getSiteContents')
        .and.returnValue(Observable.of(contentList));
    fixture.detectChanges();
    component = new ContentListComponent(activatedRoute, mockModal, mockRouter, siteService, userService);
    component.ngOnInit();


    fixture.whenStable()
        .then(() =&gt; {
            fixture.detectChanges();
            return fixture.whenStable();
        })
        .then(() =&gt; {
            const totalRows = de.queryAll(By.css('tr'));
            expect(totalRows.length).toEqual(3);
        });
}));
});
</code></pre>

<p>I have tried to take reference of following links. But I could now get satisfactory result
<a href=""https://stackoverflow.com/questions/40789637/how-to-mock-an-activatedroute-parent-route-in-angular2-for-testing-purposes"">How to mock an activatedRoute parent Route</a> </p>

<p><a href=""https://stackoverflow.com/questions/40950552/testing-angular-2-parent-route"">Testing Angular 2 parent route</a></p>
",https://stackoverflow.com/questions/45758626/how-to-do-unit-testing-of-component-with-multiple-parent-routes-of-activatedrout,"['angular', 'unit-testing', 'typescript', 'karma-jasmine']",418,FALSE,0,0
"Unit testing, how to make spring management services do not pollute the database","<p>I'm trying to use the <strong>spring and junit</strong> test DAO method, I see some of the practice on the Internet is the use of spring statement-style transaction management (@Transactional) for business operations, said that after the test is completed, the spring will let the test method back Roll, so as to achieve the purpose of testing.</p>

<p>Then I follow this approach to add the operation of the method of dao tested and found that the transaction submitted, <strong>the rollback is not successful</strong>, the database I came out of the test data. At first I thought it was spring did not roll back, but behind the observation console print information found to have rollback information, but why would fail, do not know. I found some related programs, but I found that did not solve my problem. Very troubled, hope to get your help!</p>

<p><em>The following is my code and file configuration</em></p>

<ul>
<li><p>DAOImpl's addUser () method</p>

<pre><code>@Override
public void addUser(User u) {
    Session session = sessionFactory.openSession();
    Transaction tc = session.getTransaction();
    try {
        tc.begin();
        session.save(u);
        tc.commit();
    }catch(Exception e){
        tc.rollback();
        e.printStackTrace();
    }
    return ;
}
</code></pre></li>
<li><p>Daos.xml file configuration</p>

<pre><code>&lt;bean id=""txManager""

    class=""org.springframework.orm.hibernate5.HibernateTransactionManager""&gt;
    &lt;property name=""sessionFactory"" ref=""mySessionFactory"" /&gt;
&lt;/bean&gt;
&lt;tx:annotation-driven transaction-manager=""txManager"" /&gt;
</code></pre></li>
</ul>

<p>Test class</p>

<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={""/services.xml""})
@Transactional(transactionManager = ""txManager"")
@Rollback(true)
 public class UserServiceImplTest {
    @Autowired
    UserDAO userDAO; 

    @Test
    public void testAddUse(){
        User u = new User();
        u.setLevel(3);
        u.setName(""ab11"");
        u.setPassword(""hh"");
        userDAO.addUser(u);
        Assert.assertEquals(u.getName(), userDAO.getUserList().get(userDAO.getUserList().size()-1).getName());
    }
</code></pre>

<p>Some of the console prints information</p>

<pre><code>INFO: Using DataSource [org.apache.commons.dbcp2.BasicDataSource@498d318c] of Hibernate SessionFactory for HibernateTransactionManager
    JUNE 02, 2017 4:46:19 afternoon org.springframework.test.context.transaction.TransactionContext startTransaction
INFO: Began transaction (1) for test context [DefaultTestContext@52d6cd34 testClass = UserServiceImplTest, testInstance = com.dxzh.mall.serviceImpl.test.UserServiceImplTest@715d6168, testMethod = testAddUse@UserServiceImplTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@75798d03 testClass = UserServiceImplTest, locations = '{classpath:/services.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]; transaction manager [org.springframework.orm.hibernate5.HibernateTransactionManager@c6634d]; rollback [true]
    Fri Jun 02 16:46:19 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
    Hibernate: insert into user (name, password, level) values (?, ?, ?)
    JUNE 02, 2017 4:46:19 afternoon org.springframework.test.context.transaction.TransactionContext endTransaction
INFO: Rolled back transaction for test context [DefaultTestContext@52d6cd34 testClass = UserServiceImplTest, testInstance = com.dxzh.mall.serviceImpl.test.UserServiceImplTest@715d6168, testMethod = testAddUse@UserServiceImplTest, testException = java.lang.RuntimeException, mergedContextConfiguration = [MergedContextConfiguration@75798d03 testClass = UserServiceImplTest, locations = '{classpath:/services.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]].
    JUNE 02, 2017 4:46:19 afternoon org.springframework.context.support.GenericApplicationContext doClose
INFO: Closing org.springframework.context.support.GenericApplicationContext@3ffc5af1: startup date [Fri Jun 02 16:46:13 CST 2017]; root of context hierarchy
</code></pre>
",https://stackoverflow.com/questions/44326359/unit-testing-how-to-make-spring-management-services-do-not-pollute-the-database,"['java', 'spring', 'junit', 'spring-transactions']",579,TRUE,0,1
Generate test-jar of unit testing project and use in other maven projects,"<p>I created a unit-test maven project as a base project which other project can extend and use <a href=""http://maven.apache.org/plugins/maven-jar-plugin/examples/create-test-jar.html"" rel=""nofollow noreferrer"">Described here</a>. Here is the pom.xml -</p>

<pre><code>&lt;dependencies&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.powermock&lt;/groupId&gt;
            &lt;artifactId&gt;powermock-mockito-release-full&lt;/artifactId&gt;
            &lt;version&gt;1.6.4&lt;/version&gt;
            &lt;type&gt;pom&lt;/type&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;
    &lt;build&gt;
        &lt;plugins&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
                &lt;artifactId&gt;maven-jar-plugin&lt;/artifactId&gt;
                &lt;version&gt;2.6&lt;/version&gt;
                &lt;executions&gt;
                    &lt;execution&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;test-jar&lt;/goal&gt;
                        &lt;/goals&gt;
                    &lt;/execution&gt;
                &lt;/executions&gt;
            &lt;/plugin&gt;
        &lt;/plugins&gt;
    &lt;/build&gt;
</code></pre>

<p>This generates two jars in target -</p>

<ul>
<li>unit-test-0.0.1-SNAPSHOT.jar </li>
<li>unit-test-0.0.1-SNAPSHOT-tests.jar</li>
</ul>

<p>Now, I have some spring boot microservice projects say <strong>service-a</strong> and <strong>service-b</strong> which are using another maven project say <strong>super-service</strong> as dependency. <strong>service-a</strong> and <strong>service-b</strong> are using <strong>super-service</strong> as following declaration in respective services pom.xml -</p>

<pre><code>&lt;dependency&gt;
    &lt;groupId&gt;com.super.service&lt;/groupId&gt;
    &lt;artifactId&gt;super-service&lt;/artifactId&gt;
    &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>

<p>I have written unit test for classes in <strong>super-service</strong> by using above unit-test maven project which is working fine. The pom.xml of <strong>super-service</strong> is -</p>

<pre><code>&lt;dependency&gt;
    &lt;groupId&gt;com.unit-test&lt;/groupId&gt;
    &lt;artifactId&gt;unit-test&lt;/artifactId&gt;
    &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
    &lt;type&gt;test-jar&lt;/type&gt;
    &lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
</code></pre>

<p>But <strong>service-a</strong> and <strong>service-b</strong> is not working in same manner. I thought above dependency should get resolved through the base i.e. <strong>super-service</strong> but it's not and test gets fail. Then I have tried to repeat the same dependency declaration in each services pom.xml but still maven test gets fail.</p>

<p>I tried the other way described in that URL which tells to move source files from src/test/java to src/main/java but that also worked only for <strong>super-service</strong> project and not for <strong>service-a</strong> and <strong>service-b</strong>.</p>
",https://stackoverflow.com/questions/43137401/generate-test-jar-of-unit-testing-project-and-use-in-other-maven-projects,"['java', 'maven', 'unit-testing', 'spring-boot']",705,FALSE,0,1
Unit Testing a method that calls a stored procedure and returns the results,"<p>I have a question about unit testing.  I have a method that takes in 2 date time parameters : start time, and end time.  The method calls a database and returns a set of records between the the 2 date times.  I have been told to unit test this logic, but I am not sure how.  My first try was to directly call the database and qry the table in question.  Then call the method.  Lastly I would compare the 2 results and see if they are the same.<br>
It does not make sense to me to test this method because all of the logic is in the database.  I could moq a few basic objects, but then all I would be testing would be if my fake data is returned.  i.e. pass in x, get back y, results not null would pass.  I might be on the wrong track here so I could use some advice please.</p>
",https://stackoverflow.com/questions/47267181/unit-testing-a-method-that-calls-a-stored-procedure-and-returns-the-results,"['c#', 'unit-testing']",1897,TRUE,0,1
How do I share settings between web.config and class library during unit testing?,"<p>I want to do unit tests in class library, where I need the same config settings as in my main asp.net project's web.config. Therefore I need to duplicate a number of web.config settings to my class library. </p>

<p>I have added settings through the class library's project properties Settings tab.</p>

<p>Then a app.config file is automatically added to the project:</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""utf-8"" ?&gt;
&lt;configuration&gt;
    &lt;configSections&gt;
        &lt;sectionGroup name=""applicationSettings"" type=""System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" &gt;
            &lt;section name=""ExternalServices.CPR.Properties.Settings"" type=""System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" requirePermission=""false"" /&gt;
        &lt;/sectionGroup&gt;
    &lt;/configSections&gt;
    &lt;applicationSettings&gt;
        &lt;ExternalServices.CPR.Properties.Settings&gt;
            &lt;setting name=""CprProdHostName"" serializeAs=""String""&gt;
                &lt;value&gt;direkte.cpr.dk&lt;/value&gt;
            &lt;/setting&gt;
</code></pre>

<p>Question 1. What is the ""best practice"" way to share/duplicate some settings from the main web.config to a class library that needs to run unit tests separately but with the same config?</p>

<p>Question 2. I want to read the settings by name. 
I try to read with ConfigurationManager.AppSettings[""CprProdHostName""]; (using System.Configuration;) but it doesn't work, just returns null?</p>

<p>Question 3. What is the purpose of the app.config-file? Because there is no Build action set and the file is not copied to output, it is never visible anywhere by default. This implies I can not change these settings in run time. That's quite strange, right? </p>
",https://stackoverflow.com/questions/45749329/how-do-i-share-settings-between-web-config-and-class-library-during-unit-testing,"['asp.net', 'asp.net-mvc', 'unit-testing', 'configuration', 'web-config']",61,FALSE,0,1
Error in Karma Jasmine Unit testing : &quot;Expected spy VehicleId to have been called&quot;,"<p>Could you please help me to resolve the below issue. I am fairly new to Angular and Unit Testing. Service is not returning a promise.</p>

<blockquote>
  <p>Error: Expected spy fetchVehicleId to have been called.</p>
</blockquote>

<p>Component Code Snippet:</p>

<pre><code>async getVehicleId() {
  debugger; 
  try {          
    if(this.selectedId) {
        let data: any = await this.VehicleComposer.fetchVehicleId(this.selectedID); 
        this.vehicleQuantity = data.vehicleCaseQuantity;
        this.vehicleId = data.vehicleId; 
        console.log(""return service data"",data);
      } 
   }
   catch (err) {
     console.log(err)
   }
}
</code></pre>

<p>Service Composer Code Snippet:</p>

<pre><code>fetchVehicleId(selectedID) {       
    let center = this.user.getCenterId();    
    let vehicleURL = this.config.getReceiveVehicleURL(selectedID.Id,selectedID.Number,center);
    return new Promise((resolve, reject) =&gt; {
        this.api.put(vehicleIdURL)
          .subscribe(
            data =&gt; {  
                this.receivingUnit = data.receivingUnitId;
                resolve(data);                   
            }, error =&gt; {
                reject({
                    error: true,
                    errorObj: error
                });
            });                             
        });        
    }
</code></pre>

<p>Testing Spec code snippet:</p>

<pre><code>Class MockVehicleComposerService { 
  debugger;
  fetchVehicleId(){  
    console.log(""---------""); 
    return Observable.of({}); 
  }
}

describe('VehicleComponent', () =&gt; {

  let comp: VehicleComponent;  
  let fixture: ComponentFixture&lt;VehicleComponent&gt;; 
  let mockService: MockVehicleComposerService;

  beforeEach(async(() =&gt; {

  mockService = new MockVehicleComposerService();

  TestBed.configureTestingModule({
    declarations: [VehicleComponent],
    imports: [IonicModule.forRoot(VehicleComponent)],
    providers: [{ 
        provide: ReceiveVehicleComposer, 
        useValue: MockVehicleComposerService
    }]
  })      
  .overrideComponent(VehicleComponent, {
    set: {
      template: '&lt;div&gt;&lt;/div&gt;',
      providers: [{
          provide: ReceiveVehicleComposer,
          useValue: MockVehicleComposerService
      }]
    }
  })
  .compileComponents();
}));


it('getVehicleId', async(() =&gt; {
  debugger;
  this.selectedID = { ""Number"":""123"" }
  const app = fixture.componentInstance; 
  let messageSpy = spyOn(mockService, 'fetchVehicleId');
  if(this.selectedID){
    app.getVehicleId();
  }

  expect(messageSpy).toHaveBeenCalled();
}));
</code></pre>
",https://stackoverflow.com/questions/47988033/error-in-karma-jasmine-unit-testing-expected-spy-vehicleid-to-have-been-calle,"['angular', 'karma-runner', 'ionic3', 'angular-promise', 'karma-coverage']",1167,TRUE,0,1
Advice on unit testing a method with a disposable concrete third party dependency,"<p>I'm creating a service that will serve as a facade for a third party toolkit we use.  The toolkit does not make much use of interfaces, and often requires using transient disposable classes.  Specifically, here is an example of a method that wraps an image loader:</p>

<pre><code>    public RasterImage LoadImage(string fileName)
    {
        using (var codecs = new RasterCodecs())
        {
            return codecs.Load(fileName);
        }
    }
</code></pre>

<p>I'm not really sure how to make this testable. I thought about a factory to create the RasterCodecs, but since it doesn't have an interface, the factory method would have to just return the concrete class and I'm not sure how I could mock that.</p>
",https://stackoverflow.com/questions/42166253/advice-on-unit-testing-a-method-with-a-disposable-concrete-third-party-dependenc,"['c#', 'unit-testing']",77,FALSE,0,0
Python unit testing: multiple test functions to test single function with different inputs?,"<p>When testing a single function with different inputs (some that are default), is it better practice to do:</p>

<pre><code>def test_init(self):
    page = HTMLGen(""test"", ""path\\goes\\here"")
    self.assertEqual(page.path, ""path\\goes\\here\\index.html"")

    page_2 = HTMLGen(""test"", ""path\\goes\\here"", ""cool_page"")
    self.assertEqual(page_2.path, ""path\\goes\\here\\cool_page.html"")
</code></pre>

<p>or </p>

<pre><code>def test_init(self):
    page = HTMLGen(""test"", ""path\\goes\\here"")
    self.assertEqual(page.path, ""path\\goes\\here\\index.html"")

def test_init_with_filename(self):
    page = HTMLGen(""test"", ""path\\goes\\here"", ""cool_page"")
    self.assertEqual(page.path, ""path\\goes\\here\\cool_page.html"")
</code></pre>
",https://stackoverflow.com/questions/46054973/python-unit-testing-multiple-test-functions-to-test-single-function-with-differ,"['python', 'unit-testing']",314,TRUE,0,1
java.lang.NoClassDefFoundError: com/google/gwt/core/client/GWTBridge exception while unit testing presenter class,"<p>I am trying to test one of my presenter class in GWT application.
Following is my constructor of presenter class which is to be tested.</p>

<pre><code>@Inject
public MyPresenter(MyView view, MyService myService) {
    super(view, myService);
    view.setDelegate(this);
}
</code></pre>

<p>Following is my setup() method of test class.</p>

<pre><code>@Before
public void setUp() throws Exception {

mockMyView = Mockito.mock(MyWidget.class);
mockMyService = Mockito.mock(myService.class);

sut = new MyPresenter(mockMyView, mockMyService);
</code></pre>

<p>I got following exception while executing above setup() method.</p>

<pre><code>java.lang.NoClassDefFoundError: com/google/gwt/core/client/GWTBridge
    at com.google.gwt.user.client.ui.UIObject.&lt;clinit&gt;(UIObject.java:194)
    at sun.reflect.GeneratedSerializationConstructorAccessor1.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.newInstance(SunReflectionFactoryInstantiator.java:40)
    at org.objenesis.ObjenesisBase.newInstance(ObjenesisBase.java:59)
    at org.mockito.internal.creation.jmock.ClassImposterizer.createProxy(ClassImposterizer.java:128)
    at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:63)
    at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:56)
    at org.mockito.internal.creation.CglibMockMaker.createMock(CglibMockMaker.java:23)
    at org.powermock.api.mockito.internal.mockmaker.PowerMockMaker.createMock(PowerMockMaker.java:43)
    at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:26)
    at org.mockito.internal.MockitoCore.mock(MockitoCore.java:51)
    at org.mockito.Mockito.mock(Mockito.java:1243)
    at org.mockito.Mockito.mock(Mockito.java:1120)
    at com...MyPresenterTest.setUp(MyPresenterTest.java:35)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.ClassNotFoundException: com.google.gwt.core.client.GWTBridge
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 38 more
</code></pre>

<p>Does it mean we can't mock GWT widget class as other class?
Am I missing something here?</p>
",https://stackoverflow.com/questions/44024911/java-lang-noclassdeffounderror-com-google-gwt-core-client-gwtbridge-exception-w,"['java', 'gwt', 'junit']",425,FALSE,0,1
ASP Boilerplate problems using Effort in unit testing with EFProf (Entity Framework Profiler),"<p>Having issues using EFProf (<a href=""http://www.hibernatingrhinos.com/products/EFProf"" rel=""nofollow noreferrer"">http://www.hibernatingrhinos.com/products/EFProf</a>) with ASP Boilerplate (<a href=""http://www.aspnetboilerplate.com/"" rel=""nofollow noreferrer"">http://www.aspnetboilerplate.com/</a>).  </p>

<p>For unit testing, ASP Boilerplate uses Effort (<a href=""https://github.com/tamasflamich/effort"" rel=""nofollow noreferrer"">https://github.com/tamasflamich/effort</a>) for mocking the database in-memory.</p>

<p>If I run the unit tests without adding the reference to EFProf, the tests run correctly (green).  </p>

<p>If I add the initialization line: </p>

<pre><code>HibernatingRhinos.Profiler.Appender.EntityFramework.EntityFrameworkProfiler.Initialize();
</code></pre>

<p>in either my test base ctor or my application project's Initialize(), I get the following error:</p>

<pre><code>Castle.MicroKernel.ComponentActivator.ComponentActivatorException
</code></pre>

<p>ComponentActivator: could not instantiate MyApp.EntityFramework.MyAppDataContext</p>

<p></p>

<p>The inner exception has the relevant information:</p>

<p><code>Error: Unable to cast object of type 'Effort.Provider.EffortConnection' to type 'HibernatingRhinos.Profiler.Appender.ProfiledDataAccess.ProfiledConnection'.</code></p>

<p>Is Effort just not compatible with EFProf?  Or am I doing something blindingly obvious wrong in my initialization?</p>
",https://stackoverflow.com/questions/41929305/asp-boilerplate-problems-using-effort-in-unit-testing-with-efprof-entity-framew,"['entity-framework', 'unit-testing', 'entity-framework-6', 'effort', 'asp.net-boilerplate']",445,TRUE,0,1
How to unit testing spring boot rest controller and exception handler using power mock,"<p>I am having a simple Spring boot application which contains Employee controller which returns the Employee names if the year passed  is greater than 2014 and if the it is not less than 2014 then I am throwing a custom exception and handling it in Exception Handler.<br> I want to unit test the exception flow using powermock but I am not sure how to do it. I have gone through some links but unable to understand.
<br/>
Currently I am getting java.lang.IllegalArgumentException: WebApplicationContext is required.</p>

<p>EmployeeController.java</p>

<pre><code>@RestController
public class EmployeeController{

    @GetMapping(value = ""/employee/{joiningYear}"",produces = MediaType.APPLICATION_JSON_VALUE)
    public List&lt;String&gt; getEmployeeById(@PathVariable int joiningYear) throws YearViolationException {

        if(joiningYear &lt; 2014){
            throw new YearViolationException(""year should not be less than 2014"");
        }else{

            // send all employee's names joined in that year 
        }
        return null;
    }
}   
</code></pre>

<p>ExceptionHandler</p>

<pre><code>@RestControllerAdvice
public class GlobalControllerExceptionHandler {


    @ExceptionHandler(value = { YearViolationException.class })
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiErrorResponse yearConstraintViolationExceptio(YearViolationException ex) {

        return new ApiErrorResponse(400, 5001, ex.getMessage());
    }
}
</code></pre>

<p>CustomException</p>

<pre><code>public class YearViolationException extends Exception {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public YearViolationException(String message) {

        super(message);
    }

}
</code></pre>

<p>Junit to unit test exception handler</p>

<pre><code>@RunWith(PowerMockRunner.class)
@WebAppConfiguration
@SpringBootTest
public class ExceptionControllerTest {

    @Autowired
    private WebApplicationContext applicationContext;

    private MockMvc mockMVC;

    @Before
    public void setUp() {

        mockMVC = MockMvcBuilders.webAppContextSetup(applicationContext).build();
    }

    @Test
    public void testhandleBanNotNumericException() throws Exception {

        mockMVC.perform(get(""/employee/2010"").accept(MediaType.APPLICATION_JSON)).andDo(print())
                .andExpect(status().isBadRequest())
        .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON));

    }
}
</code></pre>
",https://stackoverflow.com/questions/43911326/how-to-unit-testing-spring-boot-rest-controller-and-exception-handler-using-powe,"['spring', 'spring-boot', 'junit', 'powermock', 'powermockito']",15656,TRUE,4,2
Spring Boot Unit Testing - Test fails complaining about not having an &quot;entityManagerFactory&quot; bean defined,"<p>I'm trying to write a unit test for a Controller in a Spring Boot application. The application runs smoothly, my problem is with running its <strong>tests</strong>.</p>

<p>Here is the test code:</p>

<pre><code>@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class)
@AutoConfigureTestEntityManager
public class MyControllerTest {

@Autowired
private MockMvc mockMvc;

@Mock
private MyRepository myRepository;

@Mock
ZendeskNotifier zendeskNotifier;

@Mock
ActivityLogger activityLogger;

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

@Test
public void cannotSendFooWithoutMessageBody() throws Exception {
    this.mockMvc.perform(post(""/api/v1/foo/1/send""))
            .andDo(print())
            .andExpect(status().is4xxClientError())
            .andExpect(content().string(containsString(""The message body cannot be empty."")));
}
}
</code></pre>

<p>When I try running it I get:</p>

<pre><code>***************************
APPLICATION FAILED TO START
***************************

Description:

Field jobEventRepository in foo.bar.util.memsource.svc.MemsourceEventProcessor required a bean named 'entityManagerFactory' that could not be found.


Action:

Consider defining a bean named 'entityManagerFactory' in your configuration.
</code></pre>

<p>And that feels weird to me, since I'm providing the <code>AutoConfigureTestEntityManager</code> annotation and would expect all the <code>EntityManager</code>-related stuff to be in place.</p>
",https://stackoverflow.com/questions/44809204/spring-boot-unit-testing-test-fails-complaining-about-not-having-an-entityman,"['java', 'unit-testing', 'spring-mvc', 'spring-boot', 'mockito']",7134,TRUE,4,6
Wrapping open() for unit testing will make gcov not able to open gcda file,"<p>I am in the process of implementing using testing for some C program. For this purpose I am using GCC's <code>-Wl,--wrap=open</code> in order to mock stdlib's <code>open()</code> function and to check that it has been called with the correct options.</p>

<p>When doing so however gcov is having some issues in writing its <code>.gcda</code> file. I guess the mock I define is not only used by my tests but also by gcov. Here is a small example of how to reproduce this:</p>

<pre><code>#include &lt;stdio.h&gt;

int __wrap_open(const char *path, int flags, int mode)
{
    printf(""hello from __wrap_open\n"");
    return -1;
}


int main(void)
{
    return 0;
}
</code></pre>

<p>And compile it with <code>gcc main.c -Wl,--wrap=open -fprofile-arcs -ftest-coverage -lgcov</code>. In order to keep the example simple I have removed the unit testing part using CMocka in order to show the bug I am encountering.</p>

<p>When running the executable <code>a.out</code> I have the following output with GCC and gcov 6.3.0:</p>

<pre><code>$ ./a.out
hello from __wrap_open
hello from __wrap_open
profiling:/home/romain/wrap-bug/main.gcda:Cannot open
</code></pre>

<p>Is there a way to mock the <code>open()</code> function for my unit testing purposes <em>and</em> to be able to use gcov in order to generate code coverage data? Maybe there is a way to tell gcov to use <code>__real_open()</code>?</p>
",https://stackoverflow.com/questions/47201349/wrapping-open-for-unit-testing-will-make-gcov-not-able-to-open-gcda-file,"['c', 'unit-testing', 'gcc', 'gcov']",1209,TRUE,4,1
How to stub out the controllers called by express routes when unit testing routes,"<p>I am trying to unit test express routes such as the following:</p>

<pre><code>var app = express();
app.get('/',indexController.Index);
</code></pre>

<p>In my unit tests I am using code such as the following:</p>

<pre><code>const indexController = {};
indexController.Index = sinon.stub();
const server = proxyquire('../server.js', { './controllers/indexController': indexController }); 
describe('GET /', () =&gt; {
  it('index controller should be called', (done) =&gt; {
    request(server)
      .get('/')
      .expect(200)
      .end((err, res) =&gt; {
        if (err) {
          return done(err);
        }
        sinon.assert.called(indexController.Index);
        return done();
      });
  });
});
</code></pre>

<p>As you can see what I want to do is to stub the controller out. But this does not seem to be working (original controller seems to be called instead of the stub). And I can not figure out why. (The same approach worked when doing unit tests on the controllers and the models.)</p>

<p>Can some explain why this is not working. And any alternative way to testing these routers.</p>
",https://stackoverflow.com/questions/43062414/how-to-stub-out-the-controllers-called-by-express-routes-when-unit-testing-route,"['node.js', 'unit-testing', 'express', 'sinon', 'proxyquire']",432,FALSE,3,0
"Unit testing with `testthat` on functions that write/read files, or a Fortran error","<p>What is the best way to make unit testing with <code>testthat</code> on functions that read and write files?</p>

<p>Apologies for asking a complicated question, but I am not sure what is wrong here.</p>

<p>I have implemented a number of functions in Fortran, that reads and writes files. They are compiled in an R package cf. Writing R Extension manual. My unit testing with <code>testthat</code> generates random content that is written to temporary files with tempfile(). Running R CMD check on the R package works on my local Windows machine.</p>

<p>Running with R-devel fails however because it cannot detect Rtools for R-3.5.0 (devel). So I submitted to win-builder.</p>

<p><a href=""http://win-builder.r-project.org/"" rel=""nofollow noreferrer"">http://win-builder.r-project.org/</a> however fails with the following error:</p>

<pre><code>  At line 9 of file auxil.f95
Fortran runtime error: Actual string length is shorter than the declared one for dummy argument 'fn' (96/255)
</code></pre>

<p>with corresponding Fortran source:</p>

<pre><code>subroutine get_nlines(fn, nlines, stat) !line 9
  implicit none

  !! Arguments
  character(255), intent(in) :: fn
  integer, intent(out) :: nlines, stat

  !! Local variables
  character(len=1) :: one

  nlines = 0
  open(40, file=fn, status='OLD')
  do
    read(40, *, iostat=stat) one
    if (stat /= 0) exit
    nlines = nlines + 1
  end do
  close(40)

end subroutine
</code></pre>

<p>The Fortran code is stored in the <code>src</code> subdirectory of the R package, and is called with</p>

<pre><code>get_nlines &lt;- function(fn) {
  stopifnot(file.exists(fn))
  res &lt;- .Fortran('get_nlines', fn=as.character(fn), nlines=integer(1), stat=integer(1))
  if (res$nlines == 0 &amp; res$stat != 0) {
    warning(paste0('get_nlines did not read lines; IOSTAT error ', res$stat, '.'))
    return(structure(NA, code=res$stat))
  }
  res$nlines
}
</code></pre>

<p>So there it is. 
I don't know if my Fortran code is wrong, or if it's something that occurs on the win-builder server.</p>
",https://stackoverflow.com/questions/46180641/unit-testing-with-testthat-on-functions-that-write-read-files-or-a-fortran-er,"['r', 'unit-testing', 'fortran', 'testthat']",362,FALSE,3,1
.NET Unit Testing - How to to distinguish TestMethods from each other for variable initialization,"<p>I want to initialize often used variables in [TestInitialize] method, but I don't want the same variables initialized for every test method. Is there a way to distinguish test methods from each other by a decorator or something similar? For example</p>

<pre><code>[TestInitialize]
public Setup()
{
     //pseudocode
     if VariablesContainLetters
       var1 = a; var2 = b; var3 = c;
     else if VariablesContainNumbers
       var4 = 1; var5 = 2; var6 = 3;
}

[TestMethod]
[VariablesContainLetters]
public method1() {}

[TestMethod]
[VariablesContainNumbers]
public method2() {}
</code></pre>

<p>So that I can initialize different variables for different TestMethods?</p>
",https://stackoverflow.com/questions/45513207/net-unit-testing-how-to-to-distinguish-testmethods-from-each-other-for-variab,"['c#', '.net', 'unit-testing']",81,TRUE,2,2
Mongodb c# Unit testing: Object reference not set to an instance of an object,"<p>I'm trying to unit test a data repository for my Workorders.</p>

<p>The repository takes a DatabaseContext instance which accesses the mongodb database and exposes the IMongoCollection for the workorders as you will see posted below.</p>

<p>I use Moq to make mocks of both the IMongoCollection and DatabaseContext.
In the Moq setup for the DatabaseContext i choose to return the IMongoCollection when the exposed Workorder property is called. And in turn, the mocked IMongoCollection returns a DeleteResult.Acknowledged(1) task when DeleteOneAsync 
 is called.</p>

<p>In this way i hoped for some unit testing without needing the database running, but i got stuck with an error telling me ""<code>System.NullReferenceException : Object reference not set to an instance of an object.</code>"", pointing at a row when i am trying to do ""<code>return result.DeleteCount == 1</code>, in which result is the returned DeleteResult object.</p>

<p>It seems like my result isn't created properly, below is my code.</p>

<p><strong>The error itself</strong>
<em>Occurred when running the tests</em></p>

<pre><code>Test Name:  MESAPITests.RepositoryTests.WorkorderRepositoryTests.DeleteWorkorderById_ReturnsBooleanTrue
Test FullName: MESAPITests.RepositoryTests.WorkorderRepositoryTests.DeleteWorkorderById_ReturnsBooleanTrue
Test Source:    C:\Users\Zacke\Documents\Repositories\MES-API\MES-API Tests\RepositoryTests\WorkorderRepositoryTests.cs : line 22
Test Outcome:   Failed
Test Duration:  0:00:00.354

Result StackTrace:  
at MESAPI.Repositories.WorkorderRepository.&lt;DeleteWorkorderById&gt;d__2.MoveNext() in C:\Users\Zacke\Documents\Repositories\MES-API\MES-API\Repositories\WorkRepositories\WorkorderRepository.cs:line 28
--- End of stack trace from previous location where exception was thrown ---    
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at MESAPITests.RepositoryTests.WorkorderRepositoryTests.&lt;DeleteWorkorderById_ReturnsBooleanTrue&gt;d__1.MoveNext() in C:\Users\Zacke\Documents\Repositories\MES-API\MES-API Tests\RepositoryTests\WorkorderRepositoryTests.cs:line 34
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Result Message: System.NullReferenceException : Object reference not set to an instance of an object.
</code></pre>

<p><strong>DataRepositoryTests</strong></p>

<pre><code>public class WorkorderRepositoryTests
{
    private WorkorderRepository _repo;

    [Fact]
    public async void DeleteWorkorderById_ReturnsBooleanTrue()
    {
        var mockCollection = new Mock&lt;IMongoCollection&lt;Workorder&gt;&gt;();
        mockCollection
            .Setup(_ =&gt; _.DeleteOneAsync(It.IsAny&lt;Expression&lt;Func&lt;Workorder, bool&gt;&gt;&gt;(),
                default(CancellationToken)))
            .ReturnsAsync(await Task.Run&lt;DeleteResult&gt;(() =&gt; new DeleteResult.Acknowledged(1)));

        var mockContext = new Mock&lt;IDatabaseContext&gt;();
        mockContext.Setup(_ =&gt; _.Workorders).Returns(mockCollection.Object);

        _repo = new WorkorderRepository(mockContext.Object);
        var id = ObjectId.GenerateNewId().ToString();
        var result = await _repo.DeleteWorkorderById(id);
        Assert.True(result);
    }
}
</code></pre>

<p><strong>WorkorderRepository</strong>
<em>Error occurred on second line in DeleteWorkorderById</em></p>

<pre><code>public class WorkorderRepository : IWorkorderRepository
{
    private readonly IMongoCollection&lt;Workorder&gt; _workorders;

    public WorkorderRepository(IDatabaseContext context)
    {
        _workorders = context.Workorders;
    }

    public async Task&lt;bool&gt; DeleteWorkorderById(string id)
    {
        var result = await _workorders.DeleteOneAsync(w =&gt; w.Id == id);
        return result.DeletedCount == 1;
    }

    public async Task&lt;List&lt;Workorder&gt;&gt; GetAllWorkordersAsList()
    {
        return await _workorders.FindAsync(new BsonDocument()).Result.ToListAsync();
    }

    public async Task&lt;Workorder&gt; GetWorkorderById(string id)
    {
        return await _workorders.FindAsync(w =&gt; w.Id == id).Result.FirstOrDefaultAsync();
    }

    public async Task&lt;Workorder&gt; PostNewWorkroder(WorkorderPost workorderPost)
    {
        var newWorkorder = new Workorder(workorderPost);
        await _workorders.InsertOneAsync(newWorkorder);
        return await _workorders.FindAsync(w =&gt; w.Id == newWorkorder.Id).Result.FirstOrDefaultAsync();
    }

    public async Task&lt;bool&gt; UpdateWorkorder(Workorder workorder)
    {
        var result = await _workorders.ReplaceOneAsync(w =&gt; w.Id == workorder.Id, workorder);
        return result.MatchedCount != 0;
    }
}
</code></pre>

<p><strong>IDatabaseRepository</strong></p>

<pre><code>public interface IDatabaseContext
{
    /// &lt;summary&gt;
    /// Mongo database context.
    /// &lt;/summary&gt;
    IMongoDatabase Database { get; set; }

    /// &lt;summary&gt;
    /// BomFamily database context.
    /// &lt;/summary&gt;
    IMongoCollection&lt;BomFamily&gt; BomFamilies { get; set; }

    /// &lt;summary&gt;
    /// BomGroup database context.
    /// &lt;/summary&gt;
    IMongoCollection&lt;BomGroup&gt; BomGroups { get; set; }

    /// &lt;summary&gt;
    /// BomItem database context.
    /// &lt;/summary&gt;
    IMongoCollection&lt;BomItem&gt; BomItems { get; set; }

    /// &lt;summary&gt;
    /// Event database context.
    /// &lt;/summary&gt;
    IMongoCollection&lt;Event&gt; Events { get; set; }

    /// &lt;summary&gt;
    /// EventAttribute database context.
    /// &lt;/summary&gt;
    IMongoCollection&lt;EventAttribute&gt; EventAttributes { get; set; }

    /// &lt;summary&gt;
    /// EventType database context.
    /// &lt;/summary&gt;
    IMongoCollection&lt;EventType&gt; EventTypes { get; set; }

    /// &lt;summary&gt;
    /// Job database context.
    /// &lt;/summary&gt;
    IMongoCollection&lt;Job&gt; Jobs { get; set; }

    /// &lt;summary&gt;
    /// Product database context.
    /// &lt;/summary&gt;
    IMongoCollection&lt;Product&gt; Products { get; set; }

    /// &lt;summary&gt;
    /// QualityEvent database context.
    /// &lt;/summary&gt;
    IMongoCollection&lt;QualityEvent&gt; QualityEvents { get; set; }

    /// &lt;summary&gt;
    /// QualityTest database context.
    /// &lt;/summary&gt;
    IMongoCollection&lt;QualityTest&gt; QualityTests { get; set; }

    /// &lt;summary&gt;
    /// QualityVariable database context.
    /// &lt;/summary&gt;
    IMongoCollection&lt;QualityVariable&gt; QualityVariables { get; set; }

    /// &lt;summary&gt;
    /// Status database context.
    /// &lt;/summary&gt;
    IMongoCollection&lt;Status&gt; Statuses { get; set; }

    /// &lt;summary&gt;
    /// StatusGroup database context.
    /// &lt;/summary&gt;
    IMongoCollection&lt;StatusGroup&gt; StatusGroups { get; set; }

    /// &lt;summary&gt;
    /// User database context.
    /// &lt;/summary&gt;
    IMongoCollection&lt;User&gt; Users { get; set; }

    /// &lt;summary&gt;
    /// WorkArea database context.
    /// &lt;/summary&gt;
    IMongoCollection&lt;WorkArea&gt; WorkAreas { get; set; }

    /// &lt;summary&gt;
    /// WorkCell database context.
    /// &lt;/summary&gt;
    IMongoCollection&lt;WorkCell&gt; WorkCells { get; set; }

    /// &lt;summary&gt;
    /// Workorder database context.
    /// &lt;/summary&gt;
    IMongoCollection&lt;Workorder&gt; Workorders { get; set; }
}
</code></pre>

<p><strong>New error when changing input type on DeleteOneAsync</strong>
<em>To</em> <code>It.IsAny&lt;FilterDefinition&lt;Workorder&gt;&gt;()</code></p>

<pre><code>Test Name:  MESAPITests.RepositoryTests.WorkorderRepositoryTests.DeleteWorkorderById_ReturnsBooleanTrue
Test FullName:  MESAPITests.RepositoryTests.WorkorderRepositoryTests.DeleteWorkorderById_ReturnsBooleanTrue
Test Source: C:\Users\Zacke\Documents\Repositories\MES-API\MES-API     Tests\RepositoryTests\WorkorderRepositoryTests.cs : line 21
Test Outcome:   Failed
Test Duration:  0:00:00.283

Result StackTrace:  
at MESAPI.Repositories.WorkorderRepository.&lt;DeleteWorkorderById&gt;d__2.MoveNext() in C:\Users\Zacke\Documents\Repositories\MES-API\MES-API\Repositories\WorkRepositories\WorkorderRepository.cs:line 28
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at MESAPITests.RepositoryTests.WorkorderRepositoryTests.&lt;DeleteWorkorderById_ReturnsBooleanTrue&gt;d__1.MoveNext() in C:\Users\Zacke\Documents\Repositories\MES-API\MES-API Tests\RepositoryTests\WorkorderRepositoryTests.cs:line 33
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Result Message: System.NullReferenceException : Object reference not set to an instance of an object.
</code></pre>

<p><a href=""https://i.stack.imgur.com/Hk5cp.png"" rel=""nofollow noreferrer"">Picture: Hovering over result in the line above tells me it's null for some reason..</a></p>
",https://stackoverflow.com/questions/47414240/mongodb-c-unit-testing-object-reference-not-set-to-an-instance-of-an-object,"['c#', 'mongodb', 'unit-testing', 'asp.net-core', 'moq']",3008,TRUE,2,1
Swift unit-testing: Debug info from this module will be unavailable in the debugger,"<p>I have Objective-C project and I decided to write unit test in Swift.</p>

<p>Everything runs normally however I cannot see param values during debugging.</p>

<p>When I set cursor on value I see its name and not value:</p>

<p><a href=""https://i.stack.imgur.com/3Dn1b.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/3Dn1b.png"" alt=""enter image description here""></a></p>

<p>when I try to print it out in <code>lldb</code> I get following error:</p>

<pre><code>(lldb) po expectedEncryptedStr
warning: Swift error in module AppLibTests.
Debug info from this module will be unavailable in the debugger.

error: in auto-import:
failed to get module 'AppLibTests' from AST context:
</code></pre>

<p>I use <code>Version 8.2.1 (8C1002)</code></p>

<p>Any ideas?</p>

<p><strong>[EDIT]</strong></p>

<p>When I enter with braking point to Objective-C code - everything works as expected</p>
",https://stackoverflow.com/questions/42829189/swift-unit-testing-debug-info-from-this-module-will-be-unavailable-in-the-debug,"['ios', 'objective-c', 'swift', 'unit-testing']",452,FALSE,2,0
How to Unit testing my bot If I can&#39;t import Bot.Builder.Test branch was removed,"<p><strong>(The branch of Test was removed from the Microsoft.Bot.Builder package - so can't inherit from DialogBaseTest without copying it manually)</strong></p>

<p>I have a RootDialog which is invoked when the user sends the first message.
The RootDialog invokes another dialog named: NameResolutionDialog, which presents a question to the user and then according to the user answer, returns a Contact object (I've created that object) to the RootDialog.</p>

<p>I want to write unit tests for my bot on VS.
I've looked at: <a href=""https://github.com/Microsoft/BotBuilder/tree/master/CSharp/Tests"" rel=""nofollow noreferrer"">https://github.com/Microsoft/BotBuilder/tree/master/CSharp/Tests</a>
and couldn't really understand how should I start if I can't inherit from DialogTestBase without copying it manually (and all the other files in depends on) to my project...</p>

<p>Any other ways? </p>

<p>In addition do I need to test each dialog separately or should I test them together on each optional flow?</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/46023503/how-to-unit-testing-my-bot-if-i-cant-import-bot-builder-test-branch-was-removed,"['c#', 'unit-testing', 'botframework']",43,FALSE,1,0
"Unit-testing Electron-React app with Jest, TypeError: Cannot match against &#39;undefined&#39; or &#39;null&#39;","<p>Implementing <code>jest</code> snapshot tests in an <code>electron-react</code> app i run into an error:</p>

<blockquote>
  <p>TypeError: Cannot match against 'undefined' or 'null'.</p>
</blockquote>

<p><strong>I can't find any way to get the tests working when a <code>React</code> component contains <code>electron</code> navite elements such as <code>shell, Menu, MenuItem</code>.</strong></p>

<p>I have tried passing <code>shell</code> as a prop, as in the commented code in <strong>Home.spec.j</strong>s, but there is no change.</p>

<p><strong>Home.js</strong></p>

<pre><code>import React, { Component } from 'react';
import { remote } from 'electron';
const { shell } = remote;

export default class Home extends Component {
    openLink() {
        shell.openExternal('https://www.facebook.com')
    }

    render() {
        return (
            &lt;div&gt;
                &lt;button onClick={() =&gt; this.openLink()}&gt;
                    Open External
                &lt;/button&gt;
            &lt;/div&gt;
        )
    }
}
</code></pre>

<p><strong>Home.spec.js</strong></p>

<pre><code>import React from 'react';
import renderer from 'react-test-renderer';

import Home from '../../app/components/Home';

// import { remote } from 'electron'
// const { shell } = remote;

describe('Counter component', () =&gt; {
    it('should render snapshot', () =&gt; {
        const component = renderer.create(
            &lt;Home /&gt;
            //&lt;Home shell={shell} /&gt;
        )
        const tree = component.toJSON()
        expect(tree).toMatchSnapshot()
    })
});
</code></pre>
",https://stackoverflow.com/questions/46785179/unit-testing-electron-react-app-with-jest-typeerror-cannot-match-against-unde,"['javascript', 'reactjs', 'unit-testing', 'electron', 'jestjs']",1219,TRUE,1,1
How can we mock a response from another class using Mockito while unit testing,"<p>I have a method to test which is calling another class to get some information:</p>

<pre><code>public ClassToTest {

    public void methodToTest() {
        AnotherClass ac = Factory.getInstance();
        ResponseObj response = ac.anotherMethod();
    }
}
</code></pre>

<p>AnotherClass is part of another JAR and I would like to mock the response from it(to be specific mock ResponseObj response)</p>

<p>How can I achieve that using Mockito?</p>
",https://stackoverflow.com/questions/44378415/how-can-we-mock-a-response-from-another-class-using-mockito-while-unit-testing,"['java', 'mockito']",9996,TRUE,1,2
Why are the before- and afterEach blocks called multiple times in unit-testing with Quick?,"<p>I wrote a test case with some example groups including <code>beforeEach</code> and <code>afterEach</code>.
And I expected that each <code>beforeEach</code> and <code>afterEach</code> would be called once for each <code>it</code>.</p>

<p>Alas, for a single <code>it</code> the <code>beforeEach</code> and <code>afterEach</code> got called multiple times.</p>

<p>I've looked at some documentation (i.e. Quick's own documentation and <a href=""http://jasmine.github.io/2.1/introduction.html"" rel=""nofollow noreferrer"">http://jasmine.github.io/2.1/introduction.html</a>), but those don't help my cause.</p>

<p>Here is a small snippet that demonstrates this:</p>

<p>class CheckerTests: QuickSpec {</p>

<pre><code>override func spec() {

    describe(""something"") {
        beforeEach {
            tLog.info(""describe before"")
        }
        afterEach {
            tLog.info(""describe after"")
        }

        context(""of something"") {
            beforeEach {
                tLog.info(""context before"")
            }
            afterEach {
                tLog.info(""context after"")
            }

            it(""should behave like something"") {
                tLog.info(""in the `IT`"")
                expect(true).to(beTrue())
            }
        }
    }

}
</code></pre>

<p>}</p>

<hr>

<p>My console logs:</p>

<p><a href=""https://i.stack.imgur.com/UVakr.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/UVakr.png"" alt=""Console logs before""></a></p>

<p><strong>The above logs raise two questions:</strong></p>

<ul>
<li><strong>I'm not sure <em>when</em> <code>beforeEach</code> and <code>afterEach</code> are called now; nor do I know why I see multiple logs calling them. How come they are called multiple times?</strong></li>
</ul>

<p><del>- <strong>The above logs show that the <code>context</code>'s after block is called <em>before</em> the example passes...shouldn't that happen <em>after</em> the example?</strong></del></p>

<p>From my code snippet I would've expect the logs to return:</p>

<p><a href=""https://i.stack.imgur.com/O4Lb8.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/O4Lb8.png"" alt=""Console logs after""></a></p>

<p>Could someone explain what happens here? And is this the correct behaviour?</p>

<hr>

<p><strong>EDIT:</strong></p>

<p>As suggested by a comment; I also added a log <em>inside</em> the <code>it</code> example (see the revised code snippet above).
Which gives me the following logs:</p>

<pre><code>Test Suite 'CheckerTests' started at 2017-05-18 13:35:29.025
Test Case '-[CheckerTests something__of_something__should_behave_like_something]' started.
13:35:29.046 💙 INFO CheckerTests.spec():21 - describe before
13:35:29.046 💙 INFO CheckerTests.spec():21 - describe before
13:35:29.048 💙 INFO CheckerTests.spec():29 - context before
13:35:29.048 💙 INFO CheckerTests.spec():29 - context before
13:35:29.048 💙 INFO CheckerTests.spec():36 - in the `IT`
13:35:29.048 💙 INFO CheckerTests.spec():36 - in the `IT`
13:35:29.049 💙 INFO CheckerTests.spec():32 - context after
1Test Case '-[CheckerTests something__of_something__should_behave_like_something]' passed (0.024 seconds).
3:35:29.049 💙 INFO CheckerTests.spec():32 - context after
13:35:29.050 💙 INFOTest Suite 'CheckerTests' passed at 2017-05-18 13:35:29.050.
     Executed 1 test, with 0 failures (0 unexpected) in 0.024 (0.025) seconds
 CheckerTests.spec():24 - describe after
13:35:29.050 \360\237\222Test Suite 'CheckerTests.xctest' passed at 2017-05-18 13:35:29.051.
     Executed 1 test, with 0 failures (0 unexpected) in 0.024 (0.026) seconds
\231 INFO CheckerTests.spec():24 - describe after
Test Suite 'Selected tests' passed at 2017-05-18 13:35:29.051.
     Executed 1 test, with 0 failures (0 unexpected) in 0.024 (0.029) seconds
</code></pre>

<p>The above logs show me that the example is running twice, which confuses me even more.</p>

<hr>

<p><strong>EDIT:</strong><br>
One of the questions is answered:</p>

<p><del>- <strong>The above logs show that the <code>context</code>'s after block is called <em>before</em> the example passes...shouldn't that happen <em>after</em> the example?</strong></del>  </p>

<p><em>It seems the tests follow up in the correct order, so that answers the above question.</em></p>

<hr>

<p><strong>EDIT:</strong></p>

<p>For reference; this is what my Podfile looks like:</p>

<pre><code>def pods_for_testing
    pod 'Quick'
    pod 'Nimble'
    pod 'KIF'
end

target 'Checker' do
  project 'Checker.xcodeproj', 'dev' =&gt; :debug, 'ntrl' =&gt; :debug, 'acpt' =&gt; :release, 'prod' =&gt; :release, 'prod appstore' =&gt; :release

  pod 'SQLCipher'
  pod 'UrbanAirship-iOS-SDK'
  pod 'TBXML', :inhibit_warnings =&gt; true
  pod 'SSZipArchive'
  pod 'Google/Analytics'
  pod 'Moya', '&gt;= 8.0'
  pod 'Unbox'
  pod 'ProcedureKit'
  pod 'ProcedureKit/Mobile'
  pod 'SwiftyBeaver'
  pod 'OHHTTPStubs'
  pod 'OHHTTPStubs/Swift'

  target 'CheckerTests' do
      inherit! :search_paths
      pods_for_testing
  end

  target 'CheckerUITests' do
      inherit! :search_paths
      pods_for_testing
  end

end
</code></pre>

<p>Next to this I'm not sure what other settings could be affecting the tests.</p>
",https://stackoverflow.com/questions/44044433/why-are-the-before-and-aftereach-blocks-called-multiple-times-in-unit-testing-w,"['ios', 'unit-testing', 'quick-nimble']",1212,TRUE,6,1
Unit testing a flask application which requests external resources from other application over REST,"<p>I am very new to writing unit test cases for python and need some help.</p>

<p>I have a Flask based application which internally calls another url over REST</p>

<p>Sample code</p>

<pre><code>@sample.route('/testing', methods=[""GET""])
def testing():
    resp = requests.get(""some url"")
    data = resp.json()
    resp1 = requests.post(""another url"", data)
    return resp1.status_code()
</code></pre>

<p>Now since for unit testing, my other module is not available yet and i need to write unit test cases for this module.
so i would need to mock these rest requests and return custom data and status code for each request.</p>

<p>Can anyone please help on how to proceed for this.
I tried various links online but not working as per my expectation.</p>
",https://stackoverflow.com/questions/45813592/unit-testing-a-flask-application-which-requests-external-resources-from-other-ap,['flask'],651,FALSE,1,1
How to specify a range in nondet (to avoid choicepoints in PL Unit Testing),"<p>I wrote some tests for some Prolog codes and got ""Test succeeded with choicepoint"" warning. Here's one of my tests:</p>

<pre><code>test(overlap_intervals):-
    overlap_intervals([0, 10], [5, 15]).
</code></pre>

<p>Here's the codes:</p>

<pre><code>%% precondition: X1&lt;Y1 and X2&lt;Y2
overlap_intervals([X1,Y1], [X2,Y2]):-
    (X1&lt;X2, Y1&lt;Y2, Y1&gt;X2); !,
    (X1&gt;X2, Y1&gt;Y2, Y1&lt;X2).
</code></pre>

<p>I saw from other posts that I can use ""nondet"" <code>test(foo, nondet) :- ....</code> to avoid choice points, such as:</p>

<pre><code>test(member, all(X == [a,b,c])) :-
    member(X, [a,b,c]). % quoting Prolog document
</code></pre>

<p>However, I'm dealing with intervals in my case. The ""nondet"" would be a range of numbers, rather than an exhaustible list. For example (which apparently doesn't work but gets my goal across):</p>

<pre><code>test(overlap_intervals, all(Y&lt;10, Y&gt;0)):-
    overlap_intervals([0, 10], [Y, 15]).
</code></pre>

<p>Can someone explain why there are choicepoints and how to avoid them in my case?</p>
",https://stackoverflow.com/questions/46437063/how-to-specify-a-range-in-nondet-to-avoid-choicepoints-in-pl-unit-testing,['prolog'],95,TRUE,1,1
What is the purpose of Unit-Testing in a simple CRUD front-end application?,"<p>This might be a broad question, but in general, why is it important to unit test in a CRUD front-end. Imagine I have a CRUD server written using Node.js, and I black-box tests for all the endpoints that the backend API offers. Having this, is there a necessity to implement some kind of unit-test in let's say an iOS client? If so what kinds of things can be tested and what should not be tested?</p>
",https://stackoverflow.com/questions/44172371/what-is-the-purpose-of-unit-testing-in-a-simple-crud-front-end-application,"['unit-testing', 'testing', 'language-agnostic', 'crud']",97,FALSE,1,1
Do I need to create a test version of my factory for unit testing?,"<p>I create ship objects with my ShipFactory, but my ships have a dependency on my Acclerometer class (just a wrapper for the android acclerometer). So I have my factory, when its building a ship, pass in an accelerometer to the ships constructor.</p>

<p>This is my ShipFactory:</p>

<pre><code>public class ShipFactory {
    private int screenX;
    private int screenY;
    private Context context;

    private Bitmap bitmap;

    // How can I mock this from in my factory?
    private Accelerometer accel;

    private Ship ship;

    public ShipFactory(Context context){
        this.context = context;
        accel = new Accelerometer(context);
    }

    public Ship makeShip(String shipType){
        bitmap = BitmapFactory.decodeResource(context.getResources(),R.drawable.myship)
        ship = new Ship(context,screenX,screenY,bitmap,accel);
        return ship;
    }
}
</code></pre>

<p>So I make a ship like this:</p>

<pre><code>   ShipFactory shipFactory = new ShipFactory(context);
   ship = shipFactory.makeShip(""enemy"");
</code></pre>

<p>But now lets say I want to unit my ship class and I want to mock out these dependencies. Context is easy to mock because I can just pass a mock context to my factory, but my factory still depends on accelerometer.</p>

<p>For unit testing this should I be creating a new factory just for testing? Or is it a benefit of using a factory that in my unit test I could forgo the factory all together and directly create a new ship by passing my mocks to in the ships constructor.</p>
",https://stackoverflow.com/questions/46490907/do-i-need-to-create-a-test-version-of-my-factory-for-unit-testing,"['java', 'android', 'unit-testing', 'dependency-injection', 'factory']",597,TRUE,0,3
How to Perform Unit testing for Serialization and Deserialization of a class in C#?,"<p>I want to perform NUnit or MS tests on a class for serialized and deserialized behavior.</p>

<p>I looked at another stackoverflow article <a href=""https://stackoverflow.com/questions/236599/how-to-unit-test-if-my-object-is-really-serializable"">here</a>, but I still don't understand how to do this. Please help me to understand how to perform these tests,</p>

<p><strong>Below is my part of code:</strong></p>

<pre><code>namespace PMT.Service.Common.DataContract
{
    public partial class MyBankInfo
    {
        public string MyId { get; set; }
        public string MyAccountNumber { get; set; }
        public string MyAccountType { get; set; }
        public string MyBankName { get; set; }
        public string MyBankBranchName { get; set; }
        public string MyBankCity { get; set; }
        public string MyBankCityPincode { get; set; }
        public string MyBankIFSCCode { get; set; }

        public void Serialize(BinaryStreamWriter binaryStreamWriter)
        {           
            binaryStreamWriter.Write(MyId);
            binaryStreamWriter.Write(MyAccountNumber);
            binaryStreamWriter.Write(MyAccountType);
            binaryStreamWriter.Write(MyBankName);
            binaryStreamWriter.Write(MyBankBranchName);
            binaryStreamWriter.Write(MyBankCity);
            binaryStreamWriter.Write(MyBankCityPincode);
            binaryStreamWriter.Write(MyBankIFSCCode);
        }

        public bool Deserialize(BinaryStreamReader binaryStreamReader,out   string errorString)
        {
            errorString = string.Empty;
            try
            {
                MyId = binaryStreamReader.ReadString();
                MyAccountNumber = binaryStreamReader.ReadString();
                MyAccountType = binaryStreamReader.ReadString();
                MyBankName = binaryStreamReader.ReadString();
                MyBankBranchName = binaryStreamReader.ReadString();
                MyBankCity = binaryStreamReader.ReadString();
                MyBankCityPincode = binaryStreamReader.ReadString();
                MyBankIFSCCode = binaryStreamReader.ReadString();

            }
            catch (Exception ex)
            {
                errorString = ex.Message;
            }
            return string.IsNullOrEmpty(errorString);
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/43148735/how-to-perform-unit-testing-for-serialization-and-deserialization-of-a-class-in,"['c#', 'unit-testing', 'serialization', 'nunit']",2949,TRUE,0,1
AngularJS $window: how can it be beneficial in unit testing? (compared to using window),"<p>While the official docs says,</p>

<blockquote>
  <p>While window is globally available in JavaScript, it causes testability problems, because it is a global variable. In AngularJS we always refer to it through the $window service, so it may be overridden, removed or mocked for testing.</p>
</blockquote>

<p>I still cannot make sense of it. 😕 How can I benefit from <code>$window</code> in my unit tests code? In my snippet below, I can spy/mock and make use of the native window object, with or without <code>$window</code>. How does it cause testability problems?</p>

<pre><code>angular.module('messagePopper', [])
  .factory('popper', function popperFactory($window) {
    return {
      popupMessage(message) {
        alert(message);
      },

      popupMessageWith$window(message) {
        $window.alert(message);
      }
    };
  });

describe('messagePopper: popper service', () =&gt; {
  let $injector;
  let $window;
  let popper;

  beforeEach(() =&gt; {
    module('messagePopper');

    inject((_$injector_) =&gt; {
      $injector = _$injector_;
      $window = $injector.get('$window');
      popper = $injector.get('popper');
    });
  });

  it('should popupMessage correctly', () =&gt; {
    const message = 'welcome glenn@foodie.net';

    const alertMock = spyOn(window, 'alert');

    popper.popupMessage(message);

    expect(alertMock)
      .toHaveBeenCalledWith(message);
  });

  it('should popupMessageWith$window correctly', () =&gt; {
    const message = 'welcome glenn@foodie.net';

    const alertMock = spyOn($window, 'alert');

    popper.popupMessageWith$window(message);

    expect(alertMock)
      .toHaveBeenCalledWith(message);
  });
});
</code></pre>

<p>Fiddle here: <a href=""https://jsfiddle.net/glenn/x42uex66"" rel=""nofollow noreferrer"">https://jsfiddle.net/glenn/x42uex66</a>.</p>
",https://stackoverflow.com/questions/47699865/angularjs-window-how-can-it-be-beneficial-in-unit-testing-compared-to-using,"['javascript', 'angularjs', 'unit-testing']",50,TRUE,0,1
SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database (Only when unit testing the app),"<p>So I have recently added persistence in my application and I get this error, the interesting part though is that the application runs fine even persists objects retrieves them and everything but when running unit test I get the error written above. </p>

<p>Here are the interesting parts of my app </p>

<p>Manifest permissions:</p>

<pre><code>&lt;uses-permission android:name=""android.permission.INTERNET"" /&gt;
&lt;uses-permission android:name=""android.permission."" /&gt;
&lt;uses-permission android:name=""android.permission.GET_ACCOUNTS"" /&gt;
&lt;uses-permission android:name=""android.permission.READ_PROFILE"" /&gt;
&lt;uses-permission android:name=""android.permission.CAMERA"" /&gt;
&lt;uses-permission android:name=""android.permission.READ_EXTERNAL_STORAGE"" /&gt;
&lt;uses-permission android:name=""android.permission.WRITE_EXTERNAL_STORAGE"" /&gt;
&lt;uses-permission android:name=""android.permission.CAMERA"" /&gt;
&lt;uses-permission android:name=""android.permission.READ_CONTACTS"" /&gt;
</code></pre>

<p>Here is the gradle config defailtConfig block</p>

<pre><code> compileSdkVersion 24
    buildToolsVersion '25.0.0'


    defaultConfig {
        applicationId ""mehungry.com.myapplicationnavigationdawerdemo""
        testInstrumentationRunner ""android.support.test.runner.AndroidJUnitRunner""
        minSdkVersion 22
        targetSdkVersion 23
        versionCode 1
        versionName ""1.0""
        multiDexEnabled = true

        jackOptions {
            enabled true
        }
    }
</code></pre>

<p>My DatabaseHelper :</p>

<pre><code>import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper {

    public static final int DATABASE_VERSION = 2;
    public static final String DATABASE_NAME = ""MeHungryApp.db"";

    private SQLiteDatabase database;

    private final Context context;

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CreateStatments.ATABLE);
        db.execSQL(CreateStatments.BTABLE);
        db.execSQL(CreateStatments.CTABLE);

        db.execSQL(CreateStatments.DTABLE);
        db.execSQL(CreateStatments.ETABLE);
        db.execSQL(CreateStatments.FTABLE);
        db.execSQL(CreateStatments.GTABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(DatabaseHelper.class.getName(),
                ""Upgrading database from version "" + oldVersion + "" to ""
                        + newVersion + "", which will destroy all old data"");
        db.execSQL(""DROP TABLE IF EXISTS "" + ATableDef.TABLE_NAME);
        db.execSQL(""DROP TABLE IF EXISTS "" + BTableDef.TABLE_NAME);
        db.execSQL(""DROP TABLE IF EXISTS "" + CTableDef.TABLE_NAME);
        db.execSQL(""DROP TABLE IF EXISTS "" + DTableDef.TABLE_NAME);
        db.execSQL(""DROP TABLE IF EXISTS "" + ETableDef.TABLE_NAME);
        db.execSQL(""DROP TABLE IF EXISTS "" + FTableDef.TABLE_NAME);
        db.execSQL(""DROP TABLE IF EXISTS "" + GTableDef.TABLE_NAME);

        onCreate(db);
    }

}
</code></pre>

<p>My database Test class(doing nothing for now)</p>

<pre><code>@RunWith(AndroidJUnit4.class)
@LargeTest
public class MealEntityPersistenceTest {

private SQLiteDatabase database;
private DatabaseHelper databaseHelper;

public MealEntityPersistenceTest() {

}

@Before
public void setUp() {
    databaseHelper = new 
DatabaseHelper(InstrumentationRegistry.getContext());
    database = databaseHelper.getWritableDatabase();
}


@Test
public void testInsertRecipe() {
}


}
</code></pre>

<p>And here is what I ger in the Android Monitor </p>

<pre><code>    05-18 18:16:12.437 12672-12672/? I/MonitoringInstrumentation: Activities that are still in CREATED to STOPPED: 0
05-18 18:16:12.438 12672-12695/? E/SQLiteLog: (14) cannot open file at line 30046 of [9491ba7d73]
05-18 18:16:12.439 12672-12695/? E/SQLiteLog: (14) os_unix.c:30046: (2) open(/data/data/mehungry.com.myapplicationnavigationdawerdemo.test/databases/MeHungryApp.db) - 
05-18 18:16:12.441 12672-12695/? E/SQLiteDatabase: Failed to open database '/data/data/mehungry.com.myapplicationnavigationdawerdemo.test/databases/MeHungryApp.db'.
   android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
   at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
   at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:218)
   at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:202)
   at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
   at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
   at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
   at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:806)
   at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:791)
   at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
   at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:1181)
   at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223)
   at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
   at mehungry.MealEntityPersistenceTest.setUp(MealEntityPersistenceTest.java:37)
   at java.lang.reflect.Method.invoke(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:372)
   at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
   at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
   at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
   at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
   at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
   at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
   at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
   at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
   at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
   at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
   at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
   at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
   at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
   at org.junit.runners.Suite.runChild(Suite.java:128)
   at org.junit.runners.Suite.runChild(Suite.java:27)
   at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
   at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
   at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
   at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
   at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
   at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
   at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
   at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
   at android.support.test.internal.runner.TestExecutor.execute(TestExecutor.java:59)
   at android.support.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:262)
                                                       at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1853)
05-18 18:16:12.442 12672-12695/? I/TestRunner: failed: testInsertRecipe(mehungry.MealEntityPersistenceTest)
05-18 18:16:12.442 12672-12695/? I/TestRunner: ----- begin exception -----
05-18 18:16:12.443 12672-12695/? I/TestRunner: android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
   at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
   at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:218)
   at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:202)
   at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
   at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
   at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
   at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:806)
   at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:791)
   at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
   at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:1181)
   at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223)
   at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
   at mehungry.MealEntityPersistenceTest.setUp(MealEntityPersistenceTest.java:37)
   at java.lang.reflect.Method.invoke(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:372)
   at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
   at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
   at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
   at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
   at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
   at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
   at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
   at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
   at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
   at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
   at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
   at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
   at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
   at org.junit.runners.Suite.runChild(Suite.java:128)
   at org.junit.runners.Suite.runChild(Suite.java:27)
   at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
   at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
   at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
   at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
   at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
   at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
   at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
   at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
   at android.support.test.internal.runner.TestExecutor.execute(TestExecutor.java:59)
   at android.support.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:262)
   at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1853)
05-18 18:16:12.443 12672-12695/? I/TestRunner: ----- end exception -----
</code></pre>

<p>I am getting desperate since I have seen tons of similar issues but nothing helped me, so any kind of direction or wild guess will be greatly appreciated.</p>
",https://stackoverflow.com/questions/44053270/sqlitecantopendatabaseexception-unknown-error-code-14-could-not-open-databas,"['android', 'sqlite', 'unit-testing', 'android-studio', 'android-testing']",949,TRUE,5,1
Unit testing a Tapestry 4 page (Currently using Mockito; any drawbacks to my approach?),"<p>What is a good way to unit test a Tapestry 4 page?</p>

<p>So far, this is what I have, which seems to work well: I am using Mockito to mock the tapestry page class, and then using doCallRealMethod() to access the real method I want to test.  I'm wondering if Tapestry 4 offers a more integrated solution, like Tapestry 5 would.  However, this solution seems to be rather good.  </p>

<p>As a secondary question, are there any hidden drawbacks to this approach?</p>

<pre><code>import static org.mockito.Mockito.*;

public void testTapestryPage() {
   //setup
   MyTapestryPage partiallyMockedTapestryPage = mock(MyTapestryPage.class);

   //exercise    
   doCallRealMethod().when(partiallyMockedTapestryPage).someMethod(); /*Working around abstract class and tapestry pain.*/
   partiallyMockedTapestryPage.someMethod();

   //verify
    ...
}
</code></pre>
",https://stackoverflow.com/questions/44854881/unit-testing-a-tapestry-4-page-currently-using-mockito-any-drawbacks-to-my-app,"['java', 'unit-testing', 'mockito', 'tapestry']",54,FALSE,0,0
unit testing a DAO method using mocked entity manager get issue when testing Exception,"<p>I have a simple DAO method that I'm trying to test:</p>

<pre><code>public boolean insertUser (User user) throws DaoException {
    boolean result = false;

    try {
        em.persist(user);
        result = true;
    } catch ( Exception e) {
        throw new DaoException( e );
    }

    return result;
}
</code></pre>

<p>as persist can return an exception I want to unit test this case:</p>

<p>I have mocked the entity manager:</p>

<pre><code>@Mock
EntityManager mockEm;
</code></pre>

<p>And my test:</p>

<pre><code>@Test
public void testExceptionEntityExistInsertUser() throws Exception {
    System.out.println(""entity already exist exception"");
    boolean result;
    when(mockEm.persist(user)).thenThrow(EntityExistsException.class);
    result = userDao.insertUser(user);
}
</code></pre>

<p>But on line when(mockEm.persist(user)).thenThrow(EntityExistsException.class); I have the following error:
'void' type not allowed here</p>

<p>I don't understand where the issue come from.</p>
",https://stackoverflow.com/questions/41961343/unit-testing-a-dao-method-using-mocked-entity-manager-get-issue-when-testing-exc,"['java', 'unit-testing', 'mocking', 'persistence']",291,TRUE,0,1
how do I set up jasmine unit testing framework for a .net mvc solution?,"<p>I downloaded the jasmine-standalone zip and I'm able to run the sample tests provided in the zip.  However, I'm not sure how I would go about setting this up for ng2 components within a .NET MVC solution.  My solution has a standard .NET MVC setup with an ng2 folder which contains all of the ng2 related code.  The jasmine-standalone project has the following structure:</p>

<ul>
<li>lib</li>
<li>spec</li>
<li>src</li>
<li>SpecRunner.html</li>
</ul>

<p>I'm not clear on what structure or process I should use to adapt this to my MVC/ng2 hybrid project.</p>
",https://stackoverflow.com/questions/45244321/how-do-i-set-up-jasmine-unit-testing-framework-for-a-net-mvc-solution,"['javascript', 'angular', 'unit-testing', 'jasmine']",204,FALSE,0,0
How to call the methods in test class to main class for unit testing?,"<p>Am using Maven, I want to import the methods which are in test class to the main class,please let me know how to do this.
Actually I have done importing the class of test to main function and created an object using the class of test, but the am getting an error like can not resolve methods.</p>

<p>Actually am doing unit testing , I want to import the test class(1) to the other test class(2) and in test class (2) I have to write main() and inside main() am  creating the object to test class(1) and calling the required methods from test class(1) using the object created. Do I have to add any dependencies in pom.xml file of test class(2)(am using maven) or any other suggestions to do this.</p>

<p>Test class1.java</p>

<pre><code>public class testclass1{

public void a(){

 statements
 }
public void a(){

  statements
 }
}
</code></pre>

<p>Testclass2.java</p>

<pre><code>import testclass1;
public static void main (String args[]){

testclass1 ET =new testclass1();
 ET.a();
 ET.b();

   }
</code></pre>
",https://stackoverflow.com/questions/47545463/how-to-call-the-methods-in-test-class-to-main-class-for-unit-testing,"['java', 'maven', 'junit']",2722,FALSE,0,0
Unit testing javascript using Jasmine - Karma : How to mock variables used inside a function,"<p><strong>Function need to test:</strong></p>

<pre><code>function validate() { 
   var isOk   = false; 
   var radios = $('input[name=""abc""]:checked', '#parentDiv'). val() ;

   If(radios === ""ok"" )    
      isOk = true;

    return isOk; 
}
</code></pre>

<p>I want to write test case for the above code. I am using Jasmine-Karma for achieving that.  I have a doubt
How do i mock the radios variable which is getting value from a jquery selector and assign to it a mocked value,  so that test case can continue testing rest part of the remaining function</p>

<p><strong>Test case:</strong></p>

<pre><code>describe(""validate ok check"",  function() {
it(""validate returns true"", function () {
expect(validate()).tobe(true);
}) ;
}) ;
</code></pre>

<p>Currently on running the test case the radios variable is getting assigned undefined value,  but i want to mock it to get ""ok"" value assigned to it to successfully pass the testcase. </p>
",https://stackoverflow.com/questions/41479611/unit-testing-javascript-using-jasmine-karma-how-to-mock-variables-used-insid,"['javascript', 'jquery', 'unit-testing', 'karma-runner', 'karma-jasmine']",1101,TRUE,-1,1
can I do unit testing of an ASP.net MVC project from a console program?,"<p>I'm getting started on unit testing in an ASP.NET MVC project. What I've seen of unit testing methodology suggests that people create different controllers to run the unit tests, which suggests that the unit testing occurs within the MVC environment. Is there a way to set up enough of an environment so that you can link to the MVC dll as a project from a console application and call controller tests from the console program? That would avoid having to have a local IIS running to do test, etc.</p>

<p>thanks!</p>

<p>john</p>
",https://stackoverflow.com/questions/45757993/can-i-do-unit-testing-of-an-asp-net-mvc-project-from-a-console-program,"['c#', 'asp.net-mvc', 'unit-testing']",228,TRUE,0,1
How to save the output(pdf file) in Visual studio unit testing C Sharp,"<p>I am new to unit testing in c#. I have create a C# method that creates a pdf document. </p>

<p>I would like to write an unit to test method is creating pdf or not. Successfully written.</p>

<p>I am looking for a way to save the pdf file in the out folder of Test Results, Can some one suggest what is the way ?</p>

<pre><code>    [TestMethod()]
    public void Test_CreatePDFReport_ByDocumentID()
    {
        //act
        var result = factory.CreatePDFByDocumentID(new BDDocument { document_id = ""1"" });

        //TODO:I can save the document like below... Didn't figure out class to pull out folder
        result.Save("""");

        //assert
        Assert.IsTrue(result.Pages.Count &gt; 0);
        Assert.IsTrue(result.GetType() == typeof(Document));
    }
</code></pre>
",https://stackoverflow.com/questions/41990400/how-to-save-the-outputpdf-file-in-visual-studio-unit-testing-c-sharp,"['c#', 'visual-studio', 'unit-testing']",944,FALSE,0,1
Is a call of the static method is a test case for unit testing?,"<p>This is a simplified model of my class.</p>

<pre><code>public static FooFactory
{
    public void CreateFooByUrl(string url) 
    {
        try 
        {
           // business logic
        }
        catch(Exception exc) 
        {
           ApplicationLogger.LogError(exc);
        }
    }
}
</code></pre>

<p><code>ApplicationLogger</code> is a static class which is used across the solution. How can I verify that error was logged?</p>

<p>This is example of my test method.</p>

<pre><code>[TestMethod]
public void CreateFooExpectedError()
{
    // Arrange
    string testUrl = ""fakeUrl"";

    // Act
    FooFactory.CreateFoo(testUrl);

    // Assert
    /ApplicationLogger.LogError();
}
</code></pre>

<p>How to check that <code>LogError</code> method was called? Does it a test case? </p>
",https://stackoverflow.com/questions/44505264/is-a-call-of-the-static-method-is-a-test-case-for-unit-testing,"['c#', 'unit-testing', 'moq']",75,TRUE,0,1
"Python unit testing, error happened and exception matched, but my program returns an `AssertionError`","<p>Here is my Python code.</p>

<pre><code>try: ct(""table_that_does_not_exist"", ""database_that_does_not_exists"")
except r.errors.ReqlOpFailedError as e: self.fail()
</code></pre>

<p><code>ct</code> is a function to check if a table is exist in a database. <code>ct</code> returns <code>True</code> if a table exists in the database and <code>False</code> for otherwise.</p>

<p><code>try: ct(""table_that_does_not_exist"", ""database_that_does_not_exists"")</code> is trying to check a non-existent table in a non-existent database. This should returns an error of this.</p>

<pre><code>rethinkdb.errors.ReqlOpFailedError: Database `database_that_does_not_exists` does not exist in:
r.db('database_that_does_not_exists').table_list().contains('table_that_does_not_exist')
</code></pre>

<p>However, the error is somewhat not capture in <code>except r.errors.ReqlOpFailedError as e: self.fail()</code> and returns an <code>AssertionError</code>.</p>

<p>I expect this to pass the test, since <code>ct(""table_that_does_not_exist"", ""database_that_does_not_exists"")</code> will return <code>r.errors.ReqlOpFailedError</code>. But I got this instead.</p>

<pre><code>======================================================================
FAIL: test_check_table (__main__.test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File ""test.py"", line 61, in test_check_table
    try: ct(""table_that_does_not_exist"", ""database_that_does_not_exists"")
rethinkdb.errors.ReqlOpFailedError: Database `database_that_does_not_exists` does not exist in:
r.db('database_that_does_not_exists').table_list().contains('table_that_does_not_exist')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^                                                   

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File ""test.py"", line 62, in test_check_table
    except r.errors.ReqlOpFailedError as e: self.fail()
AssertionError

----------------------------------------------------------------------
Ran 7 tests in 0.050s

FAILED (failures=1)
</code></pre>

<p>The error is match but not proceed through <code>except</code>.</p>

<p>What is wrong with my test?</p>
",https://stackoverflow.com/questions/42099154/python-unit-testing-error-happened-and-exception-matched-but-my-program-return,"['python', 'unit-testing', 'rethinkdb']",983,TRUE,0,1
How to ignore non virtual methods while doing mock in unit testing in c#?,"<p><em>In my project I want to test logic of service so that's why I have mocked repository methods (DB calls) which have used in my services.</em>
But there are some methods has been called in my services. Those methods are not virtual methods and not even called in the interface.</p>

<p>As per my knowledge in unit testing, we can mock only virtual methods. So what can I do here?</p>

<p>Example:
In my service below code is there:</p>

<pre><code> ErrorDataCaptureProcess errorDataCaptureProcess = new ErrorDataCaptureProcess(user.Id);
                    **errorDataCaptureProcess.UpdateErrorCaptureData();**
</code></pre>

<p>Here is the main problem because errorDataCaptureProcess is calling a method of it. Which I can't mock. </p>

<p>Here is my method which is calling internally which is interacting with the database which I don't' want.</p>

<pre><code>  public void UpdateErrorCaptureData()
            {
    ErrorDataCapture.Add(Mapper.Map&lt;ErrorDataCapture&gt;(error));
            }
</code></pre>

<p>I am using x-unit for unit testing.</p>

<p>Please help me what can I do if there are any other ways of doing it.</p>

<p>Thank you in advance.</p>
",https://stackoverflow.com/questions/47608162/how-to-ignore-non-virtual-methods-while-doing-mock-in-unit-testing-in-c,"['c#', 'unit-testing', 'mocking', 'xunit']",49,FALSE,0,0
NodeJS unit testing with Mocha and Supertest - `assert` does not seem working as expected?,"<p><code>assert</code> does not seem working as expected.</p>

<p>This is my package.json:</p>

<pre><code>""devDependencies"": {
    ""babel-eslint"": ""^7.2.3"",
    ""backpack-core"": ""^0.4.1"",
    ""mocha"": ""^3.5.0"",
    ""supertest"": ""^3.0.0""
  },
  ""scripts"": {
    ""test"": ""NODE_PATH=./server:./server/modules mocha ./test/*.js --compilers js:babel-core/register --recursive"",
    ""dev"": ""backpack dev"",
    ""build"": ""nuxt build &amp;&amp; backpack build"",
    ""start"": ""cross-env NODE_ENV=production node build/main.js""
  },
</code></pre>

<p>My test:</p>

<pre><code>'use strict'

import app from '../server/index'
import supertest from 'supertest'
import assert from 'assert'

const request = supertest.agent(app)

var _id
var name
describe('POST /api/users with data', function () {
  it('status code should be 200', function (done) {
    request
      .post('/api/users')
      .type('form')
      .send({name: 'tom'})
      .expect('Content-Type', /json/)
      .expect(200)
      .end(function(err, res) {
        console.log(res.body)
        if (err) return done(err)

        name = res.body.ops[0].name.toString()
        _id = res.body.ops[0]._id.toString()
        console.log(name)

        assert(name, 'tomx') // should not pass this.

        done()
      })
  })
})
</code></pre>

<p>Result:</p>

<pre><code>  POST /api/users with data
{ result: { ok: 1, n: 1 },
  ops: [ { id: 'xxx', name: 'tom', _id: '59a7c33ba17bd32431c4134b' } ],
  insertedCount: 1,
  insertedIds: [ '59a7c33ba17bd32431c4134b' ] }
tom
    ✓ status code should be 200 (54ms)
</code></pre>

<p>At <code>assert(name, 'tomx')</code> - Why is passed? It is <code>tom</code> that should be passed.</p>

<p>Any ideas?</p>
",https://stackoverflow.com/questions/45976491/nodejs-unit-testing-with-mocha-and-supertest-assert-does-not-seem-working-as,"['node.js', 'mocha.js', 'assert', 'supertest']",513,TRUE,0,1
How to inject http to class constructor in unit testing angular class using jasmine?,"<p>I have a abstract class called logPublisher. Below is the code:</p>

<pre><code>  export abstract class LogPublisher {
    location: string;

    abstract log(record: LogEntry): Observable&lt;boolean&gt;;
    abstract clear(): Observable&lt;boolean&gt;;
}
</code></pre>

<p>Class LogWebApi extends LogPublisher:</p>

<pre><code>export class LogWebApi extends LogPublisher {

    constructor(private http: Http) {
        super();
        this.location = ""http://localhost:59143/api/v1/Log"";
    }

    log(record: LogEntry): Observable&lt;boolean&gt; {
        let ret: boolean = false;
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        let values: LogEntry[];

        return this.http.post(this.location, record, options)
            .map(response =&gt; response.json)
            .catch(this.handleErrors);
    }

    clear(): Observable&lt;boolean&gt; {
        //TODO: call webapi to clear all log entries
        return Observable.of(true);
    }

    private handleErrors(error: any): Observable&lt;any&gt; {
      console.log(""Error while logging: "" + error);
      return Observable.throw(error);
    }
}
</code></pre>

<p>Now in my unit test for class LogWebApi, how will i inject ""http"" ?
I am writing unit tests using jasmine.</p>

<p>Any code snippet will be helpful.</p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/47273849/how-to-inject-http-to-class-constructor-in-unit-testing-angular-class-using-jasm,"['angular', 'unit-testing', 'jasmine', 'angular-unit-test']",990,FALSE,0,1
Is there an easier way to handle unit testing a method with too many conditions?,"<p>I have a method which has a lot of conditions in it:</p>

<pre><code>public bool IsLegalSomething(Order order)
{
    var item0 = order.Items.SingleOrDefault(x =&gt; x.ItemCode == ""ItemCode0"");
    var item1 = order.Items.SingleOrDefault(x =&gt; x.ItemCode == ""ItemCode1"");
    ...
    var itemN = order.Items.SingleOrDefault(x =&gt; x.ItemCode == ""ItemCodeN"");

    return ((item0.Status == Status.Open) &amp;&amp; (item1.Status == Status.Closed)
         &amp;&amp; ...
         &amp;&amp; (itemN.Status == Status.Canceled));
}
</code></pre>

<hr>

<p>I want to unit test this function, but there are so many conditions that the number of unit tests is crazy if you consider every combination. There are 16 conditions in that return statement, and since each condition is true/false that is 2^16 different combinations I would need to check on. Do I really need to create 2^16 different unit tests here to ensure that every condition is utilized? Mind you, this is a simple example. Some of my functions have complex conditions due to legal requirements:</p>

<pre><code>return (condition0 &amp;&amp; condition1 &amp;&amp; (condition2 || condition3)
     &amp;&amp; (condition4 || (condition5 &amp;&amp; condition6)) ...)
</code></pre>

<p>By the math of some of my functions, the number of different combinations that the conditions can produce is millions! I looked into Data-Driven Unit Tests (DDUT), as well as Parameterized Unit Tests (PUT), but that just makes it so that the unit test is a ""fill in the blanks"" style. I still have to supply all of the various combinations and the expected result! For example:</p>

<pre><code>// Parameterized Unit Test
[TestCase(..., Result = true)]  // Combination 0
[TestCase(..., Result = true)]  // Combination 1
[TestCase(..., Result = false)] // Combination 2
public bool GivenInput_IsLegalSomething_ReturnsValidResult(...) { }
</code></pre>

<p>If I use MSTest to pull in a datasource (csv for example), I still have the same problem. I have way too many combinations that give different results. Is there an alternative I just am unaware of?</p>
",https://stackoverflow.com/questions/41858470/is-there-an-easier-way-to-handle-unit-testing-a-method-with-too-many-conditions,"['c#', 'unit-testing', 'data-driven-tests', 'parameterized-unit-test']",1434,TRUE,4,2
Unit Testing: How to verify and mock onCompleted for an Observable in RxJava within Android,"<p>I am trying to write some unit tests for an Android application that is using Retrofit 2, Mockito 1.10 and RXJava 1.0. I am not using a java version that supports lambdas!</p>

<p>My code uses Observables and I can do the following:</p>

<pre><code>when(myAPI.Complete(anyString(), any(MyContainer.class)))
        .thenReturn(Observable.&lt;GenericResponse&gt;error(new Throwable(""An error has occurred!"")));

Subscriber genericResponseSubscriber = mock(Subscriber.class);

myPresenter.myUseCase(id, container, genericResponseSubscriber);

verify(genericResponseSubscriber, times(1)).onError(any(Throwable.class));
</code></pre>

<p>The above code works fine and allows me to throw an error and capture it within the test.</p>

<p>What I need to be able to do as well (of course) :) is to capture positive conditions. I feel like it's obvious but can't find the answer I need.</p>

<p>How can I capture onComplete and onNext cases ?</p>

<p>I know that the verification for onComplete would be...</p>

<p>verify(genericResponseSubscriber, times(1)).onCompleted();</p>

<p>But I can't see what my 'when' clause should be. I tried the following but that fails:</p>

<pre><code>GenericResponse response = new GenericResponse();
response.setSuccess(true);

when(myAPI.orderComplete(anyString(), any(MyContainer.class)))
        .thenReturn(Observable.just(response));

Subscriber genericResponseSubscriber = mock(Subscriber.class);

myPresenter.myUseCase(id, container, genericResponseSubscriber);

verify(genericResponseSubscriber, times(1)).onCompleted();
</code></pre>

<p>The failure here is that subscriber.onStart() was instead called.</p>

<p>So, what I would like to know is, how I can mock and verify the 'onComplete' and 'onNext' calls, please and more importantly what I should have looked to be able to have resolved this myself rather than having to ask! :)</p>

<p>As always, any help is appreciated.</p>

<p>Edit..</p>

<p>My onError working test case..</p>

<pre><code>    public void UseCaseOnError() throws Exception {         
     String id = ""5"";              
     order Order = new Order();         
     SomeContainer myContainer = new SomeContainer(order);              

     when(myRetroFitAPI.complete(anyString(), any(SomeContainer.class)))
</code></pre>

<p>.thenReturn(Observable.error(new Throwable(“My error!"")));              </p>

<pre><code>     Subscriber genericResponseSubscriber = mock(Subscriber.class);              

     orderPresenter.doUseCase(id, myContainer, genericResponseSubscriber);              

     verify(genericResponseSubscriber,times(1)).onError(any(Throwable.class));          

}
</code></pre>

<p>What I should really add is that, I feel there should be an equivalent for onError in terms of a positive state, i.e. onCompleted. If I do the same but with onCompleted instead, my verification fails as it detects onStart has been called instead which I am finding rather confusing.</p>

<p>I have tried using the ReplaySubject as such:</p>

<pre><code>public void createOrderOnCompleteError() {
    orderOnCompleteSubject.onError(new Throwable(""I am an error""));
}

public void createOrderOnCompleteSuccess() {
    orderOnCompleteSubject.onNext(new GenericResponse().setSuccess(true));
    orderOnCompleteSubject.onCompleted();
}
</code></pre>

<p>The error mechanism works fine.. the completed mechanism does not...</p>
",https://stackoverflow.com/questions/44949797/unit-testing-how-to-verify-and-mock-oncompleted-for-an-observable-in-rxjava-wit,"['android', 'unit-testing', 'mockito', 'rx-java']",15111,TRUE,4,3
"How can I do unit testing in an XPage page, without access to the server?","<p>I need to have some kind of unit testing in my current XPage project. Problem is that I do not have access to the server so I can not install testing frameworks onto the server. I can only access the application from the Notes Designer and get all files from the git repository.</p>

<p>How can I implement unit testing under these conditions?</p>
",https://stackoverflow.com/questions/46119660/how-can-i-do-unit-testing-in-an-xpage-page-without-access-to-the-server,"['unit-testing', 'testing', 'xpages']",120,FALSE,3,2
How to set api version related data to httpcontext for unit testing in .net core?,"<p>I have the following method in my controller</p>

<pre><code>        private string GetPathBase()
        {
            return _configuration[""ApiPathBase""] + $""/v{_httpContext.GetRequestedApiVersion().MajorVersion}"";
        }
</code></pre>

<p>I am not able to mock _httpContext.GetRquestedApiVersion method using moq, as it is an extension method. How can I fill httpContext with test version details, so that the original GetRequestedApiVersion method works?</p>
",https://stackoverflow.com/questions/42998343/how-to-set-api-version-related-data-to-httpcontext-for-unit-testing-in-net-core,"['c#', '.net', 'asp.net-core']",2282,TRUE,3,2
how to mock the SmtpClient object which is used inside a function for Unit Testing,"<p>I want to write the Nunit or unit test for the SendMail method which is present in the BatchProcess without sending mails.</p>

<p>How to can I mock the SmtpClient which is present inside another method. Please help.</p>

<pre><code>namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Assuming we are populating the emails from the data from database
            List&lt;EmailEntity&gt; emails = new List&lt;EmailEntity&gt;();
            BatchProcess.SendMail(emails);
        }
    }

    public class EmailEntity
    {
        public string ToAddress { get; set; }
        public string Subject { get; set; }
        public string Body { get; set; }
    }

    public class BatchProcess
    {
        public static void SendMail(List&lt;EmailEntity&gt; emails)
        {
            foreach (EmailEntity email in emails)
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient(""sampleSmtp.sampleTest.com"");
                mail.From = new MailAddress(""your_email_address@gmail.com"");
                mail.To.Add(email.ToAddress);
                mail.Subject = email.Subject;
                mail.Body = email.Body;
                SmtpServer.Port = 587;
                SmtpServer.Credentials = new System.Net.NetworkCredential(""username"", ""password"");
                SmtpServer.EnableSsl = true;
                SmtpServer.Send(mail);
            }
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/47321246/how-to-mock-the-smtpclient-object-which-is-used-inside-a-function-for-unit-testi,"['c#', 'unit-testing', 'mocking', 'nunit', 'moq']",3471,TRUE,2,1
Angular Unit testing : Failed: Unexpected value &#39;DxTemplateHost&#39; imported by the module &#39;DynamicTestModule&#39;: Add a @NgModule annotation,"<p>Am implementing a simple unit test for my Component .</p>

<ul>
<li><p>i imported everything necessary : services , RouterModuleTesting ,FormsModule HttpModule ...</p></li>
<li><p>Wanna note that I'm using DevExtreme Widgets.</p></li>
</ul>

<p>but again , i confront some strange error :</p>

<p>the error says that i should add a <strong>@NgModule annotion</strong> somewhere , but it's not clear.</p>

<p><strong>My test file is the following :</strong> </p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { CustomersListComponent } from './customers-list.component';
// DevExtreme Module
import {DxTemplateHost} from 'devextreme-angular';
// Router Testing Module
import {RouterTestingModule} from '@angular/router/testing';
// Services and HTTM Module
import { CustomerService } from './../customer.service';
import {HttpService} from '../../../shared/service/http.service';
import {SessionService} from '../../../shared/service/session.service';
import {HttpModule} from '@angular/http';
// Forms Module (ngModel)
import {FormsModule} from '@angular/forms';
// Schemas(datasource error)
import {CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';

describe('CustomerListComponent', () =&gt; {
  let component: CustomersListComponent;
  let fixture: ComponentFixture&lt;CustomersListComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ CustomersListComponent ],
      imports: [
        HttpModule,
        FormsModule,
        DxTemplateHost,
        RouterTestingModule,
      ],
      providers: [ CustomerService , SessionService , HttpService ],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(CustomersListComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('Customer-list component should be well defined', () =&gt; {
    expect(component).toBeDefined();
  });
});
</code></pre>

<p>When running Karma serve , the test falis and throws this :</p>

<pre><code>Failed: Unexpected value 'DxTemplateHost' imported by the module 'DynamicTestModule'. Please add a @NgModule annotation.
    Error: Unexpected value 'DxTemplateHost' imported by the module 'DynamicTestModule'. Please add a @NgModule annotation.
        at syntaxError (webpack:///~/@angular/compiler/@angular/compiler.es5.js:1690:21 &lt;- src/test.ts:117724:34)
        at webpack:///~/@angular/compiler/@angular/compiler.es5.js:15383:0 &lt;- src/test.ts:131417:44
        at Array.forEach (&lt;anonymous&gt;)
        at CompileMetadataResolver.Array.concat.CompileMetadataResolver.getNgModuleMetadata (webpack:///~/@angular/compiler/@angular/compiler.es5.js:15366:0 &lt;- src/test.ts:131400:49)
        at JitCompiler.Array.concat.JitCompiler._loadModules (webpack:///~/@angular/compiler/@angular/compiler.es5.js:26796:25 &lt;- src/test.ts:142830:70)
        at JitCompiler.Array.concat.JitCompiler._compileModuleAndAllComponents (webpack:///~/@angular/compiler/@angular/compiler.es5.js:26782:0 &lt;- src/test.ts:142816:36)
        at JitCompiler.Array.concat.JitCompiler.compileModuleAndAllComponentsAsync (webpack:///~/@angular/compiler/@angular/compiler.es5.js:26714:0 &lt;- src/test.ts:142748:37)
        at TestingCompilerImpl.Array.concat.TestingCompilerImpl.compileModuleAndAllComponentsAsync (webpack:///~/@angular/compiler/@angular/compiler/testing.es5.js:478:0 &lt;- src/test.ts:232778:31)
        at TestBed.Array.concat.TestBed.compileComponents (webpack:///~/@angular/core/@angular/core/testing.es5.js:739:0 &lt;- src/test.ts:40380:31)
        at Function.Array.concat.TestBed.compileComponents (webpack:///~/@angular/core/@angular/core/testing.es5.js:622:45 &lt;- src/test.ts:40263:67)
</code></pre>

<p><strong>Suggestions ??</strong></p>
",https://stackoverflow.com/questions/45508894/angular-unit-testing-failed-unexpected-value-dxtemplatehost-imported-by-the,"['angular', 'unit-testing', 'typescript', 'devexpress', 'karma-jasmine']",12756,TRUE,7,3
Angular 2: Jasmine: Why value is not updated when calling onClick method in unit testing,"<p>I have created an app using angular cli and I am writing unit tests using jasmine and Karma as their runner.
I have a component with a value named x which updated whenever user click a button(cancel button). I have written a unit test case in which I am testing two things. I have written both in one it, I comment the other one while testing the other one.
1. Is my button is clickable 
2. changing value of x from blank to 'changed'.</p>

<p>My first test is passing but second is failing. Can somebody help ? 
Below are my code files.</p>

<pre><code>//app.component.ts
    import { Component } from '@angular/core';
    import { Http } from '@angular/http';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      constructor(private http: Http) {

      }
      title = 'app works!';
      x = ''
      onClearClick() {
        this.x = 'changed';
      };
    }


//spec file
    import { Http, ConnectionBackend, Request, Response, RequestOptions } from '@angular/http';
    import { AppComponent } from './app.component';

    import { TestBed, ComponentFixture, async, inject } from '@angular/core/testing';
    import { By } from '@angular/platform-browser';
    import { DebugElement, NO_ERRORS_SCHEMA } from '@angular/core';

    describe('AppComponent', () =&gt; {
      let fixture: ComponentFixture&lt;AppComponent&gt;;
      let comp: AppComponent;
      let component: any;
      let MockConnectionBackend = {
        navigate: jasmine.createSpy('ConnectionBackend')
      }
      let MockResponse = {
        navigate: jasmine.createSpy('Response')
      }

      let MockRequestOptions = {
        navigate: jasmine.createSpy('RequestOptions')
      }

      let MockRequest = {
        navigate: jasmine.createSpy('Request')
      }

      beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
          declarations: [
            AppComponent
          ],
          providers: [Http,
            { provide: Response, useValue: MockResponse },
            { provide: RequestOptions, useValue: MockRequestOptions },
            { provide: Request, useValue: MockRequest },
            { provide: ConnectionBackend, useValue: MockConnectionBackend }]
        }).compileComponents();
        fixture = TestBed.createComponent(AppComponent);
        component = fixture.componentInstance;
      }));



      it('should render title in a h1 tag', async(() =&gt; {
        const fixture = TestBed.createComponent(AppComponent);
        fixture.detectChanges();
        const compiled = fixture.debugElement.nativeElement;
        expect(compiled.querySelector('h1').textContent).toContain('app works!');
      }));

      it('should', async(() =&gt; {
        spyOn(component, 'onClearClick');
        let de: DebugElement = fixture.debugElement.query(By.css('#clearSearch'));
        let el: HTMLElement = de.nativeElement;

        fixture.whenStable().then(() =&gt; {

          el.click();
          fixture.detectChanges();
          // expect(component.onClearClick).toHaveBeenCalled();
          expect(component.x).toContain('changed');
        })
      }));


    });
</code></pre>
",https://stackoverflow.com/questions/44800850/angular-2-jasmine-why-value-is-not-updated-when-calling-onclick-method-in-unit,"['angular', 'unit-testing', 'karma-jasmine']",971,FALSE,2,1
Error when unit testing: &quot;Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1&quot;,"<p>I'd like to unit test a service, however, when running the test, I get the following error:</p>

<blockquote>
  <p>Uncaught (in promise) SyntaxError: Unexpected token o in JSON at
  position 1
      at MapSubscriber.project (auth.service.ts:217) 
      at MapSubscriber.Array.concat.MapSubscriber._next (map.js:77)
      at MapSubscriber.Array.concat.Subscriber.next (Subscriber.js:89)
      at TakeSubscriber.Array.concat.TakeSubscriber._next (take.js:80)
      at TakeSubscriber.Array.concat.Subscriber.next (Subscriber.js:89)
      at ReplaySubject.Array.concat.ReplaySubject._subscribe (ReplaySubject.js:55)
      at ReplaySubject.Array.concat.Observable._trySubscribe (Observable.js:57)
      at ReplaySubject.Array.concat.Subject._trySubscribe (Subject.js:97)
      at ReplaySubject.Array.concat.Observable.subscribe (Observable.js:45)
      at TakeOperator.Array.concat.TakeOperator.call (take.js:60)
      at AnonymousSubject.Array.concat.Observable.subscribe (Observable.js:42)
      at MapOperator.Array.concat.MapOperator.call (map.js:54)
      at AnonymousSubject.Array.concat.Observable.subscribe (Observable.js:42)
      at CatchOperator.Array.concat.CatchOperator.call (catch.js:79)
      at AnonymousSubject.Array.concat.Observable.subscribe (Observable.js:42)</p>
</blockquote>

<p>The corresponding line (<code>auth.service.ts:217</code>) is highlighted below in code. Running the application works perfectly fine, therefore I do not see an obvious reason for the test to fail.</p>

<p>NB: <a href=""https://stackoverflow.com/questions/8081701/i-keep-getting-uncaught-syntaxerror-unexpected-token-o"">This SO post</a> suggests that I'm parsing the object twice. But shouldn't it fail when running the application then, too?</p>

<p><strong>auth.service.ts</strong></p>

<pre><code>public login(username: string, password: string): Observable&lt;User&gt; {
    // ...

    return this.http.request(path, requestOptions).map((response: Response) =&gt; {
        if (response.status === 200) {
          const token = response.json().token; // &lt;&lt;-- Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1

          const user = this.extractUser(response);
          return user;
        }

        return null;
      })
      .catch(this.handleError);
  }
</code></pre>

<p><strong>auth.service.spec.ts</strong></p>

<pre><code>describe('AuthService', () =&gt; {
  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      providers: [
        AuthService,
        MockBackend,
        BaseRequestOptions,
        {
          provide: Http,
          useFactory: (backend: MockBackend, options: BaseRequestOptions) =&gt; new Http(backend, options),
          deps: [MockBackend, BaseRequestOptions]
        }
      ],
      imports: [
        RouterTestingModule
      ],
    });
  });

  it('should return an Observable&lt;User&gt;', inject([AuthService, MockBackend], (authService: AuthService, mockBackend: MockBackend) =&gt; {
    mockBackend.connections.subscribe((connection: any) =&gt; {
      connection.mockRespond(new Response(new ResponseOptions({
        body: '{""token"": ""abc123"", ""name"":""Jeff""}'
      })));
    });

    authService.login('jeff@example.com', 'password').subscribe(user =&gt; {
      expect(user.name).toEqual('Jeff');
    });
  }));

});
</code></pre>

<p>Logging the response outputs the following:</p>

<pre><code>Response
  body: ReadableStream
    locked: true
    __proto__: Object
  bodyUsed: true
  headers: Headers
    __proto__: Headers
  ok: true
  redirected: false
  status: 200
  statusText: ""OK""
  type: ""default""
  url: """"
    __proto__: Response
</code></pre>
",https://stackoverflow.com/questions/43612837/error-when-unit-testing-uncaught-in-promise-syntaxerror-unexpected-token-o,"['json', 'unit-testing', 'angular', 'mocking']",5198,TRUE,6,4
Why is Karma starting my complete React App when unit testing a single utils function?,"<p>I am trying to use Karma to test my React JS app. 
However, it get all kind of errors because it is trying to load/start the complete app.
My first error was </p>

<blockquote>
  <p>Invariant Violation: _registerComponent(…): Target container is not a
  DOM element
  Which appears in my entry.js that is listed in webpack as entry point, but I remove it in my karma.conf.js.</p>
</blockquote>

<p>I solved it in the entry.js by adding the dom element in case it doesn't exists.
Then I it's trying to call the method ""getCurrentLocation()"" on some undefined history object, that appears in some module that isn't mine :(</p>

<p>Bottom line: why is karma loading/starting my complete app while just testing a single method in my utils.js.
My test.js currently looks like:</p>

<pre><code>let Utils = require('../utils');
</code></pre>

<p>I commented al the rest to isolate the errors.
My karma.conf.js en webpack.config.js are listed below:
karma.conf.js:</p>

<pre><code>let webpackConfig = require('./webpack.config');
webpackConfig.entry = {};

module.exports = function (config) {
    config.set({
        basePath: 'src/js/',
        frameworks: ['jasmine-jquery', 'jasmine'],
        files: [
            ""**/tests/*.test.js"",
        ],
        preprocessors: {
            ""**/tests/*.test.js"": ['webpack', 'sourcemap'],
        },

        webpack: webpackConfig(),
        webpackMiddleware: {
            stats: ""errors-only""
        },

        reporters: ['mocha'],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: true,
        phantomJsLauncher: {
            exitOnResourceError: true
        },
        singleRun: false,
        concurrency: Infinity
    })
};
</code></pre>

<p>--- webpack.config.js:</p>

<pre><code>""use strict"";

const webpack = require('webpack');
const path = require('path');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

let mode = process.env.WEBPACK_ENV;
let isProdBuild = mode === 'prod';
let isAcceptBuild = mode === 'accept';
let isTestBuild = mode === 'test';
let isTestRun = mode === 'testRun';
let isDev = mode === 'dev';
console.log(""Mode: "" + mode)

let devServer = {};
let devTool = 'source-map';
let plugins = [];

/* plugins.push(new CopyWebpackPlugin([
 {from: 'src/js/vendor.js', to: 'src/js/vendor.js'},
 ])); */

// Used to inject the entry.js.
plugins.push(new HtmlWebpackPlugin({
    template: 'index.tpl',
    inject: 'body',
}));

plugins.push(new CleanWebpackPlugin(['dist/*'], {verbose: true}));

if (isProdBuild || isAcceptBuild) {
    plugins.push(new webpack.optimize.UglifyJsPlugin({minimize: true, sourceMap: true}));
    plugins.push(new webpack.optimize.AggressiveMergingPlugin());

    plugins.push(new webpack.DefinePlugin({'process.env': {'NODE_ENV': JSON.stringify('production')}}));

    let CompressionPlugin = require(""compression-webpack-plugin"");
    plugins.push(new CompressionPlugin({
        asset: ""[path].gz[query]"",
        algorithm: ""gzip"",
        test: /\.js$|\.css$|\.html$/,
        threshold: 10240,
        minRatio: 0.8
    }));
}
else if (isDev) {
    devServer = {inline: true, port: 3000};
    devTool = 'inline-source-map';
}

if (!isTestRun) {
    plugins.push(new webpack.optimize.CommonsChunkPlugin({
        name: 'common',
        minChunks(module, count) {
            let context = module.context;
            return context &amp;&amp; context.indexOf('node_modules') &gt;= 0;
        },
    }));

    plugins.push(new webpack.optimize.CommonsChunkPlugin({name: 'manifest'}));
}

module.exports = function (env) { 
    return {
        entry: {
            entry: ['./src/entry.js', './src/js/utils.js'],
        },
        devtool: devTool,
        devServer: devServer,
        output: {
            path: __dirname + '/dist',
            filename: '[name]-[hash].cache.js', 
            sourceMapFilename: '[name]-[hash].cache.js.map',
        },
        module: {
            rules: [
                { // The Babel loader:
                    test: /(\.jsx|\.js)$/, 
                    exclude: /(node_modules|bower_components)/,
                    use: [{
                        loader: 'babel-loader',
                        options: {
                            presets: ['babel-preset-es2015', 'babel-preset-react'].map(require.resolve),
                            plugins: ['babel-plugin-transform-react-jsx-img-import'].map(require.resolve) 
                        }
                    }]
                },
                { 
                    test: /\.s?css$/,
                    use: ['style-loader', 'css-loader', 'sass-loader']
                },
                { 
                    test: /\.(png|gif|jpe?g)$/,
                    use: [{
                        loader: 'file-loader',
                        options: {
                            name: 'resources/images/[name]-[hash]-cache.[ext]'
                        }
                    }]
                },
                { 
                    test: /\.(otf|svg|eot|ttf|woff2?)(\?.*$|$)/,
                    use: [{
                        loader: 'file-loader',
                        options: {
                            name: 'resources/fonts/[name]-[hash]-cache.[ext]'
                        }
                    }]
                },
            ]
        },
        plugins: plugins,
    };
};
</code></pre>
",https://stackoverflow.com/questions/45037162/why-is-karma-starting-my-complete-react-app-when-unit-testing-a-single-utils-fun,"['reactjs', 'karma-runner', 'karma-webpack']",132,FALSE,2,0
How to do unit testing in Xcode while including a Metal library in the project,"<p>I have a library project (A) and a Metal library project (M). M is included into A in the ""Copy files"" phase. That introduces a build dependency, meaning that I can't build A for the simulator because it tries to build M first, and Metal is not supported on the simulator.</p>

<p>That's fine, but the problem is that A contains some unit tests, and when I try to test the project, I get this error message,</p>

<p><code>Logic Testing Unavailable. Logic testing on iOS devices is not supported. You can only run logic tests on the Simulator.</code></p>

<p>But I can't build for the Simulator because of the aforementioned dependency...</p>

<p>I read <a href=""https://medium.com/the-sup-app/bare-metal-working-with-metal-and-the-simulator-70e085e3a45"" rel=""nofollow noreferrer"">https://medium.com/the-sup-app/bare-metal-working-with-metal-and-the-simulator-70e085e3a45</a> -- perhaps this could help me removing the dependency of M in A for the simulator, but I'm trying to do this without Cocoapods, purely in Xcode.</p>

<p>Is there any workaround for this?</p>
",https://stackoverflow.com/questions/43569473/how-to-do-unit-testing-in-xcode-while-including-a-metal-library-in-the-project,"['ios', 'xcode', 'unit-testing', 'xcode8', 'metal']",723,TRUE,1,1
Node js Unit testing method where fields of a model are not selected by default,"<p>Node js with mongoose.
model has fields that are not selected by default queries(<code>select:false</code> in model). In some scenarios I need to test the result to have the field selected. I have tried <code>sinon-mongoose</code> but it just tells me if a <code>populate</code> or <code>select</code> method was called, but for more flexibility I need to check the result data. And a requirement is not to use any real db connection, as it is a unit test.</p>

<p>The model
</p>

<pre><code>    var DoctorSchema = new Schema({
        firstName: {
            type: String,
            required: true,
        },
        lastName: {
            type: String,
            required: true
        },
        middleName: {
            type: String
        },
        institutionName: {
            type: String,
            required: true,
            select: false
        }
    });
</code></pre>

<p>The Service</p>

<pre class=""lang-js prettyprint-override""><code>module.exports = function (Doctor) {
    service.getById = function(req, res, next){
        Doctor.findOne({""_id"" : req.params.id}).select('+institutionName').exec(function (err, doc) {
            if (err) {
                console.log(err);
                return
            };
            if (!doc) {
                res.send(404);
            }
            else {
                res.json(doc);
            }
        });
    }
}
</code></pre>

<p>So this can be tested </p>

<pre class=""lang-js prettyprint-override""><code>describe('doctorService getById', function () {
        it('presentationService should call getById', function (done) {
            var DoctorMock = sinon.mock(DoctorModel);
            DoctorMock
                .expects('findOne').withArgs({ ""_id"": ""123"" })
                .chain(""select"").withArgs('+institutionName')
                .chain('exec')
                .yields(null, seed.doctor);
            var serviceMock = doctorService(DoctorModel);
            var res = {
                json: function (data) {
                    DoctorMock.verify();
                    DoctorMock.restore();
                    assert.equal(seed.doctor, data, ""Test fails due to unexpected result"");
                    done();
                }
            };
            serviceMock.getById({param:{id:""123""}}, res);
        });
    });
</code></pre>

<p>But in my example the test is bound to the chain. My intuition tells me that this is not a good approach.</p>
",https://stackoverflow.com/questions/42623050/node-js-unit-testing-method-where-fields-of-a-model-are-not-selected-by-default,"['javascript', 'node.js', 'mongodb', 'unit-testing', 'mongoose']",100,FALSE,1,0
Jest run async function ONCE before all tests,"<p>I want to use jest for my server unit testing (instead of mocha+chai).
Is there a way I can run async function before all tests start (init purposes) only once and not for every test file? And also if there's a way of running something after all tests are done?</p>
",https://stackoverflow.com/questions/45315679/jest-run-async-function-once-before-all-tests,"['javascript', 'jestjs']",62735,TRUE,75,5
"How to unit test a code snippet running inside executor service, instead waiting on Thread.sleep(time)","<p>How to unit test a code that is running in executor service?
In my situation,</p>

<pre><code>public void test() {
    Runnable R = new Runnable() {
        @Override
        public void run() {
            executeTask1();
            executeTask2();
        }
    };

    ExecutorService executorService = Executors.newSingleThreadExecutor();
    executorService.submit(R);
}
</code></pre>

<p>When I am unit testing, I would like to make some validations that method executes.</p>

<p>I am executing this in an executor service, as it makes some network operations.</p>

<p>In my unit testing, I had to wait until this method finishes execution. Is there a better way I can do this, instead of waiting for <code>Thread.sleep(500)</code>.</p>

<p>Unit testing code snippet:</p>

<pre><code>@Test
public void testingTask() {
    mTestObject.test();
    final long threadSleepTime = 10000L;
    Thread.sleep(threadSleepTime);
    verify(abc, times(2))
            .acquireClient(a, b, c);
    verify(abd, times(1)).addCallback(callback);
}
</code></pre>

<p>Note: I am passing an executor service object into this constructor class.
I would like to know if there is a good way of testing instead of waiting for sleep time.</p>
",https://stackoverflow.com/questions/46393697/how-to-unit-test-a-code-snippet-running-inside-executor-service-instead-waiting,"['java', 'unit-testing', 'executorservice']",46450,TRUE,28,10
How to use Yii2 user Identity in Codeception unit test case?,"<p>I am new to unit testing. Trying to create some test cases in my Yii2 project using codeception plugin. From last 1 week i am learning it.</p>

<p>Now i know how to use Fixtures, Mocks and Stubs in Unit testing.</p>

<p>I just want to ask that can we use Yii2 user identity class in unit testing in some cases. for example there may be case when we have to check some condition for logged in user. in that case how to use user session or user identity in unit testing.</p>
",https://stackoverflow.com/questions/44745808/how-to-use-yii2-user-identity-in-codeception-unit-test-case,"['php', 'yii', 'yii2', 'phpunit', 'codeception']",442,FALSE,2,1
How to unit test the right way with MochaJS in AngularJS,"<p>I am new to Unit testing with MochaJS. So, I need some help of my unit testing code that I tested my app. But, for some reason I am getting <code>TypeError: module is not a function</code> . Also, does any one know any good tutorials on unit testing or end-to-end testing? Thanks for your help. </p>

<blockquote>
  <p>Here is my unit test </p>
</blockquote>

<pre><code>    describe('Testing AngularJS Test Suite', function(){
describe('Testing AngularJS Controller', function(){

    it('should initialize the update user in the scope', function(){

    module('Portal');

    var scope = {};
    var ctrl;

    inject(function($controller){

        ctrl = $controller('HomeController', {$scope:scope});


    });

    expect(scope.title).toBeDefine();  
    expect(scope.title).toBe('Portal');  




    });




});
}); 
</code></pre>
",https://stackoverflow.com/questions/44665067/how-to-unit-test-the-right-way-with-mochajs-in-angularjs,"['angularjs', 'unit-testing', 'mocha.js', 'karma-mocha']",201,FALSE,0,0
I want to apply unit tests to simple numeric playback code,"<p>I recently started programming with Python for the first time. I have been told that I can not access the essence of unit testing for this code. I tried to practice by listening to the importance of unit testing and Python unit testing.</p>

<p>The code is shown below.</p>

<pre><code># UpDown.py

import random
import unittest

servicenumber = 0
exp = 0

## Game play screen
def start_screen():
    global servicenumber
    exe = """"""
==============================
1. Up/Down Game Start
2. Exp check
3. exit
==============================
Please enter your desired service number.""""""

    print(exe)
    servicenumber = input()
    if servicenumber == 1:
        start_game()
    elif servicenumber == 2:
        check_exp()
    elif servicenumber == 3:
        game_exit()
    else:
        print ""Please enter one of 1, 2, or 3.""


## Up/Down This is the part of the game.
def start_game():
        re = 1
        global servicenumber
        global exp
        if servicenumber == 1:
            while re != 0:
                notice = """"""
    ==============================
    Randomly generated values ​​are from 1 to 100.
    Players should enter a number between 1 and 100.
    If you win, you gain 2 exp, and if you lose, it decreases by 1.
    Please enter 0 to finish.
    ==============================\n""""""
                print(notice)
                var = input('input : ')
                if var &gt; 100:
                    print 'Please enter a value between 1 and 100.'
                    continue
                elif var &lt; 0:
                    print 'Please enter a value between 1 and 100.'
                    continue
                elif var == 0:
                    re = 0
                else:
                    print ''

                randvalue = random.randrange(1,101)
                if var &gt; randvalue:
                    print 'Up'
                    exp = exp + 2
                    print ""exp+2""
                    print ""Your experience "",exp
                    print ""Randomly generated values "",randvalue
                    continue
                elif var &lt; randvalue:
                    print 'Down'
                    exp = exp-1
                    print 'Decreasing story ~~'
                    continue
                elif var == randvalue:
                    print 'The story of being tapped ~~'
                    continue
                else:
                    print ""Randomly generated values "",randvalue
                    continue
        start_screen()


def check_exp():
    global servicenumber
    if servicenumber == 2:
        print ""Experience: "",exp
        start_screen()


## (exit)
def game_exit():
    global servicenumber
    if servicenumber == 3:
        print 'Exit'
        exit()


if __name__ == ""__main__"":
    start_screen()
else:
    print ""Imported. Start unit testing.\n""
</code></pre>

<p>And the code I tried to practice
I think it is pointless.</p>

<pre><code>import unittest
import UpDownGame

class testing(unittest.TestCase):
    def test_start(self):
        self.assertTrue(UpDownGame.start_screen)

    def test_game(self):
        self.assertTrue(UpDownGame.start_game)

    def test_chkexp(self):
        self.assertTrue(UpDownGame.check_exp)

    def test_exit(self):
        self.assertTrue(UpDownGame.game_exit)


def initialize():
    return testing


if __name__ == ""__main__"":
    testsuite = (unittest.makeSuite(testing))
    unittest.TextTestRunner(verbosity=2).run(testsuite)
</code></pre>

<p>So I want advice on unit testing.
I would really appreciate it if you let me know how to apply unit tests to this code.
Also, let me know if you think I have the basic knowledge I need.</p>

<p>Thank you.</p>
",https://stackoverflow.com/questions/45033534/i-want-to-apply-unit-tests-to-simple-numeric-playback-code,"['python', 'unit-testing']",45,TRUE,-2,1
Mocking a Class For Unit Tests,"<p>I've <code>Class A</code> that has an instance of another <code>Class B</code>. I've completed unit testing of independent code in <code>Class B</code>. For other operations, <code>Class A</code> invokes methods of <code>Class B</code>, does some processing using other classes and then invokes methods of <code>Class B</code>.</p>

<p>My question is how do I mock the dependency of <code>Class A</code> and complete unit testing of <code>Class B</code>? If <code>Class B</code> uses instance of <code>Class A</code>, I can mock <code>Class A</code> and complete the task. However, in my case <code>Class A</code> uses instance of <code>Class B</code>.</p>

<p>How do I mock in this scenario for unit testing?</p>
",https://stackoverflow.com/questions/44964539/mocking-a-class-for-unit-tests,"['c++', 'unit-testing', 'googletest', 'googlemock']",3981,FALSE,0,1
Angular Karma-Jasmine Cannot read property &#39;get&#39; of undefined,"<p>example.service.ts</p>

<pre><code>import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, URLSearchParams, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import { environment as ENV } from '../../environments/environment';
import { SharedService } from './shared.service';

video(id): Observable&lt;any&gt; {
let sessionId = this.sharedService.sessionId();

return this.http.get(ENV.api_url + '&amp;videoId=' + id)
      .map(this.extractData)
      .catch(this.handleError);
</code></pre>

<p>}</p>

<p>example.service.spec.ts</p>

<pre><code>import { async, ComponentFixture, TestBed } from 

'@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { Http, HttpModule } from '@angular/http';
import { MockBackend } from '@angular/http/testing';


describe('VideosComponent', () =&gt; {
  let component: VideosComponent;
  let fixture: ComponentFixture&lt;VideosComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [ VideosComponent ],
      providers: [
        {
          provide: Http,
          deps: [MockBackend]
        },
      ]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(VideosComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p>I got <strong>TypeError: Cannot read property 'get' of undefined</strong> when i'm trying to run tests.
I'm very new to unit testing, but I posted the code here for the unit testing files and service that returns 'get'.</p>
",https://stackoverflow.com/questions/45862142/angular-karma-jasmine-cannot-read-property-get-of-undefined,"['angular', 'unit-testing', 'karma-jasmine']",5684,FALSE,2,1
CakePHP 2.x: BindModel not working in Unit testig,"<p>I am checking Unit Testing in CakePHP2.</p>

<p><strong>OrdersController</strong></p>

<pre><code>$this-&gt;Discount-&gt;bindModel(array(
    'hasOne' =&gt; array(
        'Coupon' =&gt; array(
            'foreignKey' =&gt; 'discount_id',
            'join' =&gt; 'INNER',
        ),
    ),
));  

$options = array();
$options['conditions'] = [
    'Discount.status' =&gt; 1,
    'Coupon.status' =&gt; 1,
];
$all_discounts = $this-&gt;Discount-&gt;find('all', $options);
</code></pre>

<p><strong>OrdersControllerTest</strong></p>

<pre><code>public function testRestaurantDomain()
{
    $this-&gt;testAction('/orders/index');
}
</code></pre>

<p>I am getting <code>SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Coupon.status' in 'where clause'</code> error.</p>

<p>When I comment out <code>Coupon.status</code> condition then it is working fine. So what am I missing here for bindmodel to work with Unit Testing?</p>
",https://stackoverflow.com/questions/43361804/cakephp-2-x-bindmodel-not-working-in-unit-testig,"['unit-testing', 'cakephp', 'phpunit', 'cakephp-2.0']",41,FALSE,0,0
Procedure with refcursor .refcursor should be out parameter,"<p>Please help me writing a program procedure with refcursor. Refcursor should be out parameter. </p>

<p>If i give input deptno it shows employee details in that department,also write unit testing block :</p>

<p>I tried like:</p>

<pre><code>CREATE OR REPLACE PROCEDURE poph (i IN NUMBER, p OUT SYS_REFCURSOR)
IS
BEGIN
   OPEN p FOR 'select * from emp where deptno=' || i;

   FOR i IN p
   LOOP
      DBMS_OUTPUT.put_line (i.ename || '**' || i.JOB);
   END LOOP;

   CLOSE p;
END;
/
</code></pre>

<p>///////unit testing///// </p>

<pre><code>DECLARE
   M   NUMBER := '&amp;n';
   n   SYS_REFCURSOR;
BEGIN
   poph (M, n);
END;
</code></pre>
",https://stackoverflow.com/questions/45581378/procedure-with-refcursor-refcursor-should-be-out-parameter,['plsql'],475,FALSE,-2,1
JUnit 5 for Android testing,"<p>How to configure JUnit 5 for Android unit testing?
I tried:</p>

<pre><code>testCompile(""org.junit.jupiter:junit-jupiter-api:5.0.0"")
</code></pre>

<p>But it doesn't work, when I run previous the simplest unit test:</p>

<pre><code>@Test
public void addition_isCorrect() throws Exception {
    assertEquals(4, 2 + 2);
}
</code></pre>

<p>I get error:</p>

<pre><code>Exception in thread ""main"" java.lang.NoSuchMethodError: org.junit.platform.commons.util.ReflectionUtils.getDefaultClassLoader()Ljava/lang/ClassLoader;
    at org.junit.platform.launcher.core.ServiceLoaderTestEngineRegistry.loadTestEngines(ServiceLoaderTestEngineRegistry.java:31)
    at org.junit.platform.launcher.core.LauncherFactory.create(LauncherFactory.java:42)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:36)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

Process finished with exit code 1
Empty test suite.
</code></pre>
",https://stackoverflow.com/questions/46161113/junit-5-for-android-testing,"['java', 'android', 'unit-testing', 'junit', 'junit5']",22391,TRUE,28,5
Static member value being carried to next test,"<p>I am unit testing a class like below </p>

<pre><code>public class A {
 private static String aStr = null;

 public void doSomething() {
    if (null == aStr) {
       // do something to init aStr, and this initialized val gets cached for future calls.
       aStr = some_val;
    } else {
      // do something else using aStr value.
   }
 }
</code></pre>

<p>Now while unit testing this I am doing :</p>

<pre><code>public class ATest {
 private A a;

 @BeforeMethod
 public void setup() {
    a = new A();
 }

  @Test
  public void test1() {
    a.doSomething();
    // assert on some_val being fetched correctly.
  }

  @Test
  public void test2() {
    a.doSomething();
    // assert again for some_val

    // this is where some_val fetching is not invoked at all, while debugging I 
    // can see that aStr is already being initialized from previous test. 
  }
}
</code></pre>

<p>I was assuming that since i am reinitializing object 'a' in @BeforeMethod setup, i should get null value for all tests.. Isn't this assumption correct?</p>
",https://stackoverflow.com/questions/46866838/static-member-value-being-carried-to-next-test,"['java', 'unit-testing', 'testng']",60,TRUE,0,1
How to unit test Go errors,"<p>When you are unit testing functions that have an <code>error</code> return type, I was wondering how to properly unit test for this error. Are you supposed to just check if the error is nil or not nil? Or are you supposed to verify the error string matches an expected string as well?</p>
",https://stackoverflow.com/questions/42035104/how-to-unit-test-go-errors,"['unit-testing', 'go', 'error-handling']",76960,TRUE,51,4
Mocking httpclient json data for offline dev environment,"<p>there are quite a few howto's on unit testing and mocking in angular but all of them are for <strong>unit testing</strong></p>

<p>i need an offline development mode where the http requests are fed from constant json, how can this be done in angular5 ?</p>
",https://stackoverflow.com/questions/47748361/mocking-httpclient-json-data-for-offline-dev-environment,"['angular', 'mocking', 'angular5']",687,FALSE,1,2
Wrapper around TASKs in C#,"<p>I am using tasks in WinForms (<code>.NET 4.0</code>) to perform lengthy operations like <code>WCF</code> call. Application is already in product with heavy use of Tasks (almost all the methods which uses Tasks are <code>void</code>).</p>

<p>During the unit testing we have used <code>AutoResetEvent</code>s (in actual code) to find out when the given task is completed then perform assert.</p>

<p>This gives me a thought that almost all the <code>AutoResetEvent</code> are waste of effort. They are just fulfilling unit testing needs, nothing else.</p>

<p>Can we create a wrapper around Tasks likewise when actual code run... they should work in background and in case of unit testing they should be synchronous.</p>

<p>Similar to below link for <code>BackgroundWorker</code>.</p>

<p><a href=""http://si-w.co.uk/blog/2009/09/11/unit-testing-code-that-uses-a-backgroundworker/"" rel=""nofollow noreferrer"">http://si-w.co.uk/blog/2009/09/11/unit-testing-code-that-uses-a-backgroundworker/</a></p>
",https://stackoverflow.com/questions/43512845/wrapper-around-tasks-in-c,"['unit-testing', 'asynchronous', 'c#-4.0', 'task-parallel-library', 'task']",311,TRUE,-1,1
When should I use Snapshot testing?,"<p>It's fairly easy to implement snapshot testing in jest, but it's something I am not really comfortable with because it feels like I am not actually testing anything.</p>
<p>In unit testing I can easily take components I want to test and write expectations on their actual behavior and also test what they should be rendering. But all I can see about snapshot testing is that it yields when you change something and shows you the difference... similar to what <code>git diff</code> does.</p>
<p>So when should I use snapshot testing over unit testing?</p>
",https://stackoverflow.com/questions/43771602/when-should-i-use-snapshot-testing,"['reactjs', 'unit-testing', 'jestjs', 'snapshot-testing']",9721,TRUE,24,2
Error : java.lang.UnsatisfiedLinkError with roboelectric and realm,"<p>Hi I am using <code>realm</code> database for my application and using <code>roboelectric</code> unit testing framework for performing unit testing. I see <code>realm</code> is written in native c code, it has <code>librealm-jni.so</code> file for their functionality. </p>

<p>I am getting <code>UnsatisfiedLinkError</code> error, read somewhere that robolectric does not support native libraries. I believe that there must be some way to resolve it. I tried accepted answer of this <a href=""https://stackoverflow.com/questions/34554998/how-to-load-so-when-using-robolectric"">How to load .so when using Robolectric?</a> but no luck.</p>

<pre><code>java.lang.UnsatisfiedLinkError: Can't load library: C:\Users\XS~1\AppData\Local\Temp\android-tmp-robolectric7796034244909642596\app_lib\realm-jni.dll.2.3.1
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1824)
    at java.lang.Runtime.load0(Runtime.java:809)
    at java.lang.System.load(System.java:1086)
    at com.getkeepsafe.relinker.SystemLibraryLoader.loadPath(SystemLibraryLoader.java:29)
    at com.getkeepsafe.relinker.ReLinkerInstance.loadLibraryInternal(ReLinkerInstance.java:198)
    at com.getkeepsafe.relinker.ReLinkerInstance.loadLibrary(ReLinkerInstance.java:136)
    at com.getkeepsafe.relinker.ReLinker.loadLibrary(ReLinker.java:70)
    at com.getkeepsafe.relinker.ReLinker.loadLibrary(ReLinker.java:57)
    at io.realm.internal.RealmCore.loadLibrary(RealmCore.java:59)
    at io.realm.Realm.init(Realm.java:187)
    at com.xyz.helloworld.HelloWorldApplication.onCreate(HelloWorldApplication.java:17)
    at org.robolectric.internal.ParallelUniverse.setUpApplicationState(ParallelUniverse.java:147)
    at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:329)
    at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:259)
    at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:41)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:199)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:114)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:57)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:66)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:109)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:377)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
    at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
</code></pre>

<blockquote>
  <p>HelloWorldApplication.java</p>
</blockquote>

<pre><code>public class HelloWorldApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        Realm.init(this);

        RealmConfiguration config = new RealmConfiguration.Builder()
                .name(""book.realm"")
                .schemaVersion(1)
                .build();

        Realm.setDefaultConfiguration(config);
    }

    protected void loadNativeLibraries() {
        try {
            System.loadLibrary(""librealm-jni"");
        } catch (UnsatisfiedLinkError e) {
        }
    }
}
</code></pre>

<blockquote>
  <p>TestHelloWorldApplication.java</p>
</blockquote>

<pre><code>public class TestHelloWorldApplication extends HelloWorldApplication  {

    @Override
    protected void loadNativeLibraries() {
        //do nothing
    }
}
</code></pre>
",https://stackoverflow.com/questions/42413971/error-java-lang-unsatisfiedlinkerror-with-roboelectric-and-realm,"['java', 'android', 'realm', 'robolectric']",2033,TRUE,14,1
How can I Mock node-rest-client request?,"<p>I'm using node-rest-client for my project and I've come to the point where I want to start unit testing my classes that utilize <a href=""https://www.npmjs.com/package/node-rest-client"" rel=""nofollow noreferrer"">node-rest-client</a>. Is there any examples on how I can <strong>mock</strong> the Client in my tests? I am using <a href=""http://sinonjs.org/"" rel=""nofollow noreferrer"">Sinon</a> in my unit testing.</p>
",https://stackoverflow.com/questions/43756402/how-can-i-mock-node-rest-client-request,"['node.js', 'sinon-chai', 'node-rest-client']",1254,TRUE,0,1
"In a custom NodeJS package, how to perform unit testing on a function that depends on functions in the same package?","<p>I am a newbie in unit testing.</p>

<p>I am performing unit testing on each function in my custom NodeJS package.<br>
Suppose that my package exports functions as follows,  </p>

<pre><code>//my-package.js
module.exports = {
    listFiles,
    copyFiles
}

/**
 * @return &lt;list&gt; a list of files under src_dir
 */
function listFiles(src_dir){
    //stat all files under src_dir and make a list containing all file names
    ...
}

/**
 * @param [allowed_ext] a list of file extensions
 */
function copyFiles(src_dir, dst_dir, allowed_ext = []){
    //filter files under src_dir according to allowed_ext
    var files = listFiles(src_dir).filter(function(){...})

    for(var a_file of files){
        //other operations on each single file
        ...
    }
}
</code></pre>

<p>I want to do unit test on both <code>listFiles()</code> and <code>copyFiles()</code>; however, <code>copyFiles()</code> actually depends on <code>listFiles()</code>. What is the best practice to write a unit test for these functions?</p>
",https://stackoverflow.com/questions/46112987/in-a-custom-nodejs-package-how-to-perform-unit-testing-on-a-function-that-depen,"['node.js', 'unit-testing']",33,TRUE,1,1
What is the difference between Jest and enzyme?,"<p>I'm new to Unit testing. I want to test React project. As I started with React documentation which refers to enzyme as test utility which is kind of ambiguous to me.<br></p>

<p>What is the difference between <code>Jest</code> and <code>enzyme</code>?</p>

<ul>
<li>Is <code>enzyme</code> assertion library or task runner?</li>
<li>Can I use <code>karma</code> with <code>Jasmine</code>?</li>
<li>What is the best way to test a <code>react-redux</code> project?</li>
</ul>
",https://stackoverflow.com/questions/42616576/what-is-the-difference-between-jest-and-enzyme,"['javascript', 'reactjs', 'jasmine', 'jestjs', 'enzyme']",15143,TRUE,48,3
Java lombok unit tests for getters setters,"<p>I am using <code>lombok</code> in my Java project annotating my object's private member variables with <code>@Getter</code> and <code>@Setter</code> annotations. We know that those getters and setters would work as expected. So we don't really need those to be unit tested. However, that brings down the <code>code coverage</code> of the code in unit testing.</p>

<p>Is there a way to tell the unit testing engine that the getters and setters generated by lombok need not be tested? </p>
",https://stackoverflow.com/questions/41726618/java-lombok-unit-tests-for-getters-setters,"['java', 'unit-testing', 'code-coverage', 'lombok']",15734,TRUE,7,2
C# unit test n-tier mvc application,"<p>I am new to Unit testing. I didn't found a complete example/sample of unit testing a CRUD application. </p>

<p>I want to add unit test in MVC application which is using entity framework. </p>

<p>Do we actually add data in database everytime we run a test? 
Do we create seperate unit test projects for every project?</p>
",https://stackoverflow.com/questions/47962276/c-unit-test-n-tier-mvc-application,"['asp.net-mvc', 'unit-testing']",224,TRUE,0,1
How to connect a API database connection in unit test project?,"<p>I am new for unit testing. I have created test method in unit testing project. In that test method I called API method for testing . 
API method connected with database. When i run unit test project  getting <code>""No connection found""</code> error. 
Test method always getting failure. </p>

<p>Please suggest you solution.
Please find my code </p>

<p><strong>TestCase:</strong> </p>

<pre><code>[TestMethod] 
public void ValidateCheckInCheckOut_Test2() 
{ 
    int task_id = 0; 
    var userToken = ""dsdjs2""; 
    Object response = new Object (); 
    var actual = class.GetValidationResponse(task_id, userToken); Assert.AreNotEqual(actual.GetType(), response.GetType());
}
</code></pre>

<p><strong>API method:</strong> </p>

<pre><code>public void GetValidationResponse(int taskid , string userToken) 
{ 
    using(var context = new DbContext()) 
    { 
        Some logic......
    } 
}
</code></pre>
",https://stackoverflow.com/questions/46557454/how-to-connect-a-api-database-connection-in-unit-test-project,"['c#', 'api', 'unit-testing']",244,TRUE,0,1
How to raise CancelEventArgs,"<p>How to raise CancelEventArgs in unit testing using C# </p>

<pre><code>void OnCloseWindow(object sender, CancelEventArgs e)
        {
            var window = base.DataContext as IWindowManagerService;
            if (window != null)
            {
                e.Cancel = !window.CloseWindow();
            }
        }
</code></pre>
",https://stackoverflow.com/questions/43467135/how-to-raise-canceleventargs,"['c#', 'wpf']",67,FALSE,0,0
How can we unit test the sessionstorage in Angular?,"<p>I am new to unit testing in Angular, and I am trying to test the sessionstorage and localstorage. </p>

<p>My code is:</p>

<pre><code>subscribe(data) {
        sessionStorage.setItem('myProductDetail', JSON.stringify(data));
    }

subscribe(data) {
        LocalStorage.setItem('dummyname', data[0].name);
    }
</code></pre>

<p>Is it a good practice to do unit testing for session, local storage and private classes?</p>

<p>I am trying to follow the example code below to mock my localstorage and sessionstorage.</p>

<pre><code>beforeEach(function () {
  var store = {};

  spyOn(localStorage, 'getItem').andCallFake(function (key) {
    return store[key];
  });
  spyOn(sessionStorage, 'setItem').andCallFake(function (key, value) {
    return store[key] = value + '';
  });
  spyOn(localStorage, 'clear').andCallFake(function () {
      store = {};
  });
});
</code></pre>

<p>Any guidance is greatly appreciated. </p>
",https://stackoverflow.com/questions/45542903/how-can-we-unit-test-the-sessionstorage-in-angular,"['angular', 'unit-testing', 'karma-jasmine']",11710,TRUE,0,1
Jest: SVG require causes &quot;SyntaxError: Unexpected token &lt;&quot;,"<p>Not sure where to look for this error.</p>

<p>Using Typescript with React, and Jest and Enzyme for unit testing.</p>

<p>Package.json sample:</p>

<pre><code>""scripts"": {
    ""start"": ""node server.js"",
    ""bundle"": ""cross-env NODE_ENV=production webpack -p"",
    ""test"": ""jest""
  },
  ""jest"": {
    ""transform"": {
      ""^.+\\.tsx?$"": ""&lt;rootDir&gt;/node_modules/ts-jest/preprocessor.js""
    },
    ""testRegex"": ""(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$"",
    ""moduleFileExtensions"": [
      ""ts"",
      ""tsx"",
      ""js"",
      ""json""
    ]
  }
</code></pre>

<p>Running npm test results in:</p>

<pre><code>FAIL src/components/Component.test.tsx

 ({""Object.&lt;anonymous&gt;"":function(module,exports,require,__dirname,__filename,global,jest){&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
                                                                                             ^

    SyntaxError: Unexpected token &lt;
</code></pre>

<p>Edit: It appears to be happening the first place where i use <code>require</code> to load a static <code>.svg</code> file. Why can it not handle that? Is there a way to ignore throwing this error when using require? </p>
",https://stackoverflow.com/questions/46791263/jest-svg-require-causes-syntaxerror-unexpected-token,"['reactjs', 'typescript', 'jestjs']",29949,TRUE,48,5
Unit test error: Cannot call Promise.then from within a sync test,"<p>I started looking into unit testing angular 2 applications, but I'm stuck even in the simplest examples. I just want to run a simple test to see if it even works, basically what I want is to compare a value from the title page to the one in the test.</p>

<p>This is the error I'm getting, but I don't see where the error is coming from since everything looks to be synchronous to me.</p>

<blockquote>
  <p>Error: Error: Cannot call Promise.then from within a sync test.</p>
</blockquote>

<p>Unit test:</p>

<pre><code>import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By }              from '@angular/platform-browser';
import { DebugElement, Input}    from '@angular/core';
import { ToDoComponent } from './todo.component';
import { FormsModule } from '@angular/forms';
describe((""test input ""),() =&gt; {
    let comp:    ToDoComponent;
    let fixture: ComponentFixture&lt;ToDoComponent&gt;;
    let de:      DebugElement;
    let el:      HTMLElement;

    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            declarations: [ ToDoComponent ],
            imports: [ FormsModule ]
        })
        .compileComponents();  
    });

    fixture = TestBed.createComponent(ToDoComponent);
    comp = fixture.componentInstance;
    de = fixture.debugElement.query(By.css(""h1""));
    el = de.nativeElement;

    it('should display a different test title', () =&gt; {
        comp.pageTitle = 'Test Title';
        fixture.detectChanges();
        expect(el.textContent).toBe('Test Title423');
    });
});
</code></pre>

<p>My component:</p>

<pre><code>import {Component} from ""@angular/core"";
import {Note} from ""app/note"";

@Component({
    selector : ""toDoArea"",
    templateUrl : ""todo.component.html""
})

export class ToDoComponent{
    pageTitle : string = ""Test"";
    noteText : string ="""";
    noteArray : Note[] = [];
    counter : number = 1;
    removeCount : number = 1;

    addNote() : void {

        if (this.noteText.length &gt; 0){
            var a = this.noteText;
            var n1 : Note = new Note();
            n1.noteText = a;
            n1.noteId = this.counter;
            this.counter = this.counter + 1;
            this.noteText = """";
            this.noteArray.push(n1);        
        }

    }

    removeNote(selectedNote : Note) :void{
        this.noteArray.splice(this.noteArray.indexOf(selectedNote),this.removeCount);
    }

}
</code></pre>
",https://stackoverflow.com/questions/43186533/unit-test-error-cannot-call-promise-then-from-within-a-sync-test,"['javascript', 'unit-testing', 'angular']",44896,TRUE,72,2
Setting up background work item using MoQ,"<p>I am new to unit testing and I am having some difficulties with unit testing background workers. </p>

<h2>Method being tested</h2>

<pre><code>[HandleExceptions(LoggerName)]
public override IHttpActionResult ValidateToken(string auth_token)
{
    var response = new HttpResponseMessage();
    var userInfo = this._userInfoService.CreateUserInfoModel(auth_token);

    response.StatusCode = HttpStatusCode.BadRequest;

    if (userInfo.Status.IsSuccess)
    {
        //-- I want to test if the following worker is calling RunPlayerDetailsWorkflow method exactly once.
        _taskScheduler.QueueBackgroundWorkItem(task =&gt; 
            this._playerDetailsService.RunPlayerDetailsWorkflow(userInfo.UserID, userInfo.ServerID));

        response.StatusCode = HttpStatusCode.OK;
    }

    response.Content = new StringContent(_userInfoService.ParseUserInfo(userInfo));
    response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(""text/plain"");

    return this.ResponseMessage(response);
 }
</code></pre>

<h2>Test method</h2>

<pre><code>[Test]
public void TestValidateToken_Should_Call_PlayerDetailsService_RunPlayerDetailsWorkflow_Exactly_Once()
{
    // Arrange
    var userInfoModel = AdminControllerHelpers.CreateUserInfoModel();
    userInfoModel.Status = ETIStatus.CreateSuccess();
    _mockUserInfoService
        .Setup(m =&gt; m.CreateUserInfoModel(It.IsAny&lt;string&gt;()))
        .Returns(userInfoModel);
    _mockUserInfoService
        .Setup(s =&gt; s.ParseUserInfo(userInfoModel))
        .Returns(_randomString);
    _mockPlayerService
        .Setup(m =&gt; m.RunPlayerDetailsWorkflow(userInfoModel.UserID, userInfoModel.ServerID));
    //-- this is where I got the error.
    _mockTaskScheduler
        .Setup(t =&gt; t.QueueBackgroundWorkItem(
            obj =&gt; _mockPlayerService.Object.RunPlayerDetailsWorkflow(userInfoModel.UserID,
                userInfoModel.ServerID)));

    // Act
    _controller.ValidateToken(It.IsAny&lt;string&gt;());

    // Assert
    _mockPlayerService
        .Verify(m =&gt; m.RunPlayerDetailsWorkflow(userInfoModel.UserID, userInfoModel.ServerID), Times.Exactly(1));
}
</code></pre>

<p>Even though I am setting up everything correctly (at least to me) I get following error:</p>

<blockquote>
  <p>An exception of type 'System.ArgumentException' occurred in System.Core.dll but was not handled in user code. Additional information: <strong>Argument types do not match</strong></p>
</blockquote>

<h2>Task Scheduler interface which I am mocking</h2>

<pre><code>public interface ITaskScheduler
{
    /// &lt;summary&gt;
    ///   Schedules a task which can run in the background, independent of any request.
    /// &lt;/summary&gt;
    /// &lt;param name=""workItem""&gt; A unit of execution.&lt;/param&gt;
    void QueueBackgroundWorkItem(Action&lt;CancellationToken&gt; workItem);
}
</code></pre>
",https://stackoverflow.com/questions/44243881/setting-up-background-work-item-using-moq,"['c#', 'unit-testing', 'asp.net-web-api', 'moq']",502,TRUE,1,1
C# How to unit test an interface method without implementation,"<p>I am new to unit testing and to stackoverflow.</p>

<p>I have to test <code>RefreshAmount</code> in the following interface:</p>

<pre><code>public interface IAccountService
{
    double GetAccountAmount(int accountId);
}
</code></pre>

<p>And here is a class that depends on this interface:</p>

<pre><code>public class AccountObj
{
    private readonly int _Id;
    private readonly IService _service;
    public AccountObj(int Id, IService service)
    {
        _Id = Id;
        _service = service;
    }
    public double Amount { get; private set; }
    public void RefreshAmount()
    {
        Amount = _service.GetAmount(_Id);
    }
}
</code></pre>

<p>How can I unit test the behavior of <code>RefreshAmount</code>? </p>

<p><code>RefreshAmount</code> calls <code>IService.GetAmount</code> which may make a call to a back-end office but I do not have its implementation. Any suggestion on the way to go would be appreciated.
(I have read about moq and dependency injection, but I am quiet new to unit testing)</p>
",https://stackoverflow.com/questions/42274647/c-how-to-unit-test-an-interface-method-without-implementation,"['c#', 'unit-testing', 'dependency-injection', 'moq']",28172,TRUE,7,5
How to unit test angular material md datepicker?,"<p>How can I test how to manually open an angular material directive for unit testing?</p>

<pre><code>          &lt;div layout-gt-xs=""row""&gt;
                &lt;div class=""col-md-12""&gt;
                    &lt;md-input-container&gt;
                        &lt;label class=""input-label""&gt;{{ 'policyform.DOB' | translate }}&lt;/label&gt;
                        &lt;md-datepicker ng-model=""vm.data.dob"" name=""policyHolderDob""
                            ng-required=""vm.config.dob.required""
                            md-min-date=""vm.minDate""
                            md-max-date=""vm.maxDate""
                            min-age=""{{vm.config.dob.minage}}""
                            max-age=""{{vm.config.dob.maxage}}""&gt;
                        &lt;/md-datepicker&gt;
                        &lt;uex-form-validation form=""vm.policyForm"" field=""policyHolderDob"" config=""vm.config.dob""&gt;&lt;/uex-form-validation&gt;
                    &lt;/md-input-container&gt;
               &lt;/div&gt;
          &lt;/div&gt;
</code></pre>
",https://stackoverflow.com/questions/43112193/how-to-unit-test-angular-material-md-datepicker,"['angularjs', 'unit-testing', 'angular-material']",1705,FALSE,2,0
How to mock redis connection in Go,"<p>I am using <code>https://github.com/go-redis/redis</code> package to make Redis DB calls.</p>
<p>For unit testing I want to mock these calls, is there any mock library or way to do it?</p>
",https://stackoverflow.com/questions/44727938/how-to-mock-redis-connection-in-go,"['go', 'redis', 'mocking']",13153,TRUE,14,3
How can I test Thunk actions with Jest?,"<p>I'm new to unit testing Redux-Thunk async actions using Jest.</p>
<p>Here is my code:</p>
<pre class=""lang-js prettyprint-override""><code>export const functionA = (a, b) =&gt; (dispatch) =&gt; {
    dispatch({ type: CONSTANT_A, payload: a });
    dispatch({ type: CONSTANT_B, payload: b });
} 
</code></pre>
<p>How can I test this function using Jest?</p>
",https://stackoverflow.com/questions/45081717/how-can-i-test-thunk-actions-with-jest,"['unit-testing', 'redux', 'jestjs', 'redux-thunk']",13467,TRUE,9,3
Mock Response returns undefined for async testing in Angular 2,"<p>I am trying to get the a mock response for my HTTP call, but for some reason the mock response returns as undefined.</p>

<p>Here is my unit testing code in Jasmine:</p>

<pre><code>  it('should fetch a single user by an id key',
   async(inject([UserService], (userService) =&gt; {

    const mockResponse = {
      id: 1,
      username: ""dtrinh100""
    };

     mockBackend.connections.subscribe(
       (connection: MockConnection) =&gt; {

         // make sure the URL is correct
         expect(connection.request.url).toEqual(""http://localhost:3000/api/users/1"");
         connection.mockRespond(
           new Response(
             new ResponseOptions({
               body: JSON.stringify(mockResponse)
             }))
         );
       }
     );

     userService.getUser(1).then((user) =&gt; {
         console.log(user); // user is undefined
         //expect(user[""id""]).toBe(1);

       });

})));
</code></pre>

<p>Here is my original userService code for UserService:</p>

<pre><code>private usersUrl = 'http://localhost:3000/api/users';
getUser(id: number): Promise&lt;User&gt; {
    const url = `${this.usersUrl}/${id}`;
    return this.http.get(url)
      .toPromise()
      .then(response =&gt; response.json().data as User)
      .catch(this.handleError);
  }
</code></pre>

<p>I think the userService code is correct and the issue seems to be with my unit testing mock response. How do I get the mock response to return the proper object?</p>
",https://stackoverflow.com/questions/44706756/mock-response-returns-undefined-for-async-testing-in-angular-2,"['javascript', 'angular', 'unit-testing']",178,FALSE,1,0
why dependency injection pattern in unit test is best when compared to other patterns in c# mstest?,"<p>I am new to unit testing and i need to use dependency injection pattern.</p>
",https://stackoverflow.com/questions/42362383/why-dependency-injection-pattern-in-unit-test-is-best-when-compared-to-other-pat,['c#'],428,TRUE,-4,1
Disable Spring Security config class for @WebMvcTest in Spring Boot,"<p>Recently I have added <strong>Spring Security</strong> to my Spring Boot project using the following class:</p>

<pre><code>@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MySecurityConfig {
}
</code></pre>

<p>as result, by default all my URLs are now protected with authentication and a self-generated password.</p>

<p>The problem is that all tests in a @WebMvcTest class that I used for unit-testing a controller:</p>

<pre><code>@RunWith(SpringRunner.class)
@WebMvcTest(SomeController.class)
public class SomeControllerTest {...}
</code></pre>

<p>are now failing everywhere because of lack of authorization.</p>

<p><strong>Question</strong>: can I tell @Test methods to ignore authorization so they keep succeeding as before?</p>

<p>How can I prevent the  <em>@EnableWebSecurity</em> config class from being picked on a specific <em>@WebMvcTest</em> unit testing class?</p>

<p>I would like the tests already in place to be able to still go through and to test the authentication features separately later on.</p>

<p>So far I have tried to use a nested config class in the testing class in order to exclude security configs:</p>

<pre><code>@RunWith(SpringRunner.class)
@WebMvcTest(SomeController.class)
public class SomeControllerTest {

    @Configuration
    @EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class})
    static class ContextConfiguration { }

 ....}
</code></pre>

<p>but it seems not to work.</p>

<p><strong>NOTE</strong> : I am using Spring Boot 1.5.8</p>
",https://stackoverflow.com/questions/47593537/disable-spring-security-config-class-for-webmvctest-in-spring-boot,"['java', 'spring', 'spring-mvc', 'spring-boot', 'spring-security']",48913,TRUE,38,11
N Unit Test Debugger not stepping inside a static method,"<p>My unit testing method is as follows </p>

<pre><code>[Test]
public void TrackPublicationChangesOnCDSTest()
{
    //Arrange
    // objDiskDeliveryBO = new DiskDeliveryBO();            

    //Act
    var actualResult = objDiskDeliveryBO.TrackPublicationChangesOnCDS();

    //Assert 
    var expectedZipName = 0;
    Assert.AreEqual(expectedZipName, actualResult);
}
</code></pre>

<p>The Actual method <code>TrackPublicationChangesOnCDS</code> in BO is as follows </p>

<pre><code>public int TrackPublicationChangesOnCDS()
{

    var resultFlag = -1;

    try
    {

        string pubUpdateFileCDSPath = CommonCalls.PubUpdateFileCDSPath;
        string pubUpdateFileLocalPath = CommonCalls.PubUpdateFileLocalPath;


        if (File.Exists(pubUpdateFileCDSPath))
            File.Copy(pubUpdateFileCDSPath, pubUpdateFileLocalPath, true);

        if (File.Exists(pubUpdateFileLocalPath))
        {

            string[] pubRecords = File.ReadAllLines(pubUpdateFileLocalPath);

            var pubRecordsExceptToday = pubRecords.Where(p =&gt; !p.Trim().EndsWith(DateTime.Now.ToString(""dd/MM/yy""))).ToList();

            resultFlag = new DiskDeliveryDAO().TrackPublicationChangesOnCDS(pubRecordsExceptToday);

            File.WriteAllText(pubUpdateFileLocalPath, string.Empty);

            string[] pubRecordsCDS = File.ReadAllLines(pubUpdateFileCDSPath);
            var pubRecordsTodayCDS = pubRecordsCDS.Where(p =&gt; p.Trim().EndsWith(DateTime.Now.ToString(""dd/MM/yy""))).ToList();
            File.WriteAllLines(pubUpdateFileCDSPath, pubRecordsTodayCDS);

        }

        return resultFlag;
    }
    catch (Exception)
    {

        return -1;
    }

}
</code></pre>

<p>While debugging Debugger comes till 
<code>string pubUpdateFileCDSPath = CommonCalls.PubUpdateFileCDSPath;</code></p>

<p>But <code>CommonCalls.PubUpdateFileCDSPath;</code> return empty string . It should return a file path . when the method is called directly it works fine . It doesn't work when it is called inside a unit testing method. </p>

<p><code>CommonCalls.PubUpdateFileCDSPath</code> is a static property defined as below .</p>

<pre><code>public static string PubUpdateFileCDSPath
{
    get { return GetXmlConfigValue(""PubUpdateFileCDSPath""); }
}

public static string GetXmlConfigValue(string nodeName)
{
    var xml = new XmlDocument();
    xml.Load(ConfigValuesXml);
    var node = xml.SelectSingleNode(""JanesOfflineDeliveryService/"" + nodeName);
    return node != null ? node.InnerText : string.Empty;
}
</code></pre>

<p><code>Configvaluesxml</code> is a xml file path . Contents of the file is </p>

  <pre class=""lang-xml prettyprint-override""><code>&lt;JanesOfflineDeliveryService&gt; 
  &lt;PubUpdateFileCDSPath&gt;D:\OfflineDelivery\CDS\pub_update.txt&lt;/PubUpdateFileCDSPath&gt;
  &lt;PubUpdateFileLocalPath&gt;D:\pub_update.txt&lt;/PubUpdateFileLocalPath&gt;
&lt;/JanesOfflineDeliveryService&gt;
</code></pre>
",https://stackoverflow.com/questions/43629347/n-unit-test-debugger-not-stepping-inside-a-static-method,"['c#', 'unit-testing', 'nunit']",60,FALSE,1,2
Mocking Guice provided objects,"<p>I have an application specific module which is configure <code>DynamoDBMapper</code> and another class of application which relies on that mapper</p>

<pre><code>public class ProjectAppServiceModule extends AbstractModule {

  @Override protected void configure() {
  }

  @Provides
  @Singleton
  public AmazonDynamoDB getAmazonDynamoDBClient() {
    return AmazonDynamoDBClientBuilder
            .standard()
            .withCredentials(new EnvironmentVariableCredentialsProvider())
            .build();
  }

  @Provides
  @Singleton
  public DynamoDBMapper getDynamoDBMapper() {
    return new DynamoDBMapper(getAmazonDynamoDBClient());
  }

  @Provides
  @Singleton
  public OrdersManager getOrdersManager() {
    return new OrdersManager(getDynamoDBMapper());
  }
</code></pre>

<p>}</p>

<p>Now, I want to do unit testing and in unit testing, I want to get a <strong>mocked</strong> object <code>OrderManager</code>. </p>

<p>I tried doing</p>

<pre><code>@Mock
private DynamoDBMapper mockDynamoDBMapper;

Injector injector = createInjector(new AbstractModule() {
    @Override
    protected void configure() {
        bind(DynamoDBMapper.class).toInstance(mockDynamoDBMapper)
       bind(OrdersManager.class).toInstance(mockOrdersManager);
    }
});
</code></pre>

<p>and I got error that i can't instantiate with null objects. What would be better way to get around this problem? I guess to be approaching it wrong way. </p>
",https://stackoverflow.com/questions/43896987/mocking-guice-provided-objects,"['java', 'unit-testing', 'mockito', 'amazon-dynamodb']",1119,FALSE,1,1
Setting up a Test Bed in Ionic Provider,"<p>I am really new into Ionic and Unit Testing. Current version is 3.12.0. I am using Karma and Jasmine for unit testing.</p>

<p>I have a provider called <strong>test-service.ts</strong></p>

<pre><code>import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

/*
  Generated class for the TestServiceProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class TestServiceProvider {

  constructor(public http: Http) {
    console.log('Hello TestServiceProvider Provider');
  }

}
</code></pre>

<p>Then I have a test spec in the same folder as follows contains a simple test with a test bed.</p>

<pre><code>import { TestServiceProvider } from './test-service';
import { TestBed, TestModuleMetadata, async, ComponentFixture } from '@angular/core/testing';

describe('Test Service', () =&gt; {
  let component: TestServiceProvider;
  let fixture: ComponentFixture&lt;TestServiceProvider&gt;;

  beforeEach(async( () =&gt; {
    TestBed.configureTestingModule({
      imports: [TestServiceProvider]
    }).compileComponents;
  }));

  beforeEach( () =&gt; {
    fixture = TestBed.createComponent(TestServiceProvider);
    component = fixture.componentInstance;
  });

  it('should add numbers', () =&gt; {
    expect(1+1).toBe(2);
  });
});
</code></pre>

<p>But when I run <code>npm test</code> it gives me an error  </p>

<pre><code>Unexpected value 'TestServiceProvider' imported by the module 'DynamicTestModule'. Please add a @NgModule annotation.
</code></pre>

<p>What am I doing wrong here and how do I fix this? </p>
",https://stackoverflow.com/questions/46876851/setting-up-a-test-bed-in-ionic-provider,"['unit-testing', 'ionic-framework', 'karma-jasmine']",732,FALSE,1,1
Error: No provider for TranslateStore,"<p>""Error: No provider for TranslateStore!"" while UI Unit testing translation service in Angular 4.
After I run ng test command I get the test cases failed error along with the above error message.</p>
",https://stackoverflow.com/questions/47672667/error-no-provider-for-translatestore,"['javascript', 'angular', 'jasmine']",16792,TRUE,18,3
How to Unit Test Startup.cs in .NET Core,"<p>How do people go about Unit Testing their Startup.cs classes in a .NET Core 2 application? All of the functionality seems to be provided by Static extensions methods which aren't mockable?</p>
<p>If you take this <code>ConfigureServices</code> method for example:</p>
<pre><code>public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext&lt;BlogContext&gt;(options =&gt; options.UseSqlServer(Configuration.GetConnectionString(&quot;DefaultConnection&quot;)));

    services.AddMvc();
}
</code></pre>
<p>How can I write tests to ensure that <code>AddDbContext(...)</code> &amp; <code>AddMvc()</code> are called - the choice of implementing all of this functionality via extension methods seems to have made it untestable?</p>
",https://stackoverflow.com/questions/47482256/how-to-unit-test-startup-cs-in-net-core,"['c#', 'unit-testing', 'asp.net-core', 'mocking']",54757,TRUE,47,6
Karma + Mocha + React + Webpack Unexpected token import on line 1,"<p>Hey Great people of SO.</p>

<p>I'm using create-react-app for my project setup to skip the hassle with webpack.
Development went fine, but things gets complicated when I was going for Unit Testing. I'm trying to make a Unit Testing environment using Mocha via Karma and Reactjs. When I start my karma test runner it yields an error</p>

<pre><code>  Chrome 57.0.2987 (Windows 10 0.0.0) ERROR
  Uncaught SyntaxError: Unexpected token import
  at src/UnitTesting/index.test.js:1
</code></pre>

<p>I've been googling for hours, installing so many npm modules which I've never heard of or maybe modules that's already installed to the point where my npm start yields an error in compilation as well and to no avail...</p>

<p>Unit Testing is very new to me, so I'm really thankful if anyone can help me, 
here is some of my stuff </p>

<p><strong>karma.conf.js</strong></p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>// Karma configuration
// Generated on Fri Apr 21 2017 23:21:18 GMT+0700 (SE Asia Standard Time)
var webpack = require('webpack');
var path = require('path');

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',


    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['mocha'],


    // list of files / patterns to load in the browser
    files: [
      './src/UnitTesting/*test.js'
    ],


    // list of files to exclude
    exclude: [
      '**/*.png',
      '**/*.jpg',
      '**/*.jpeg',
      '**/*.css',
      '**/*.svg',
    ],


    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      '../src/**/*.test.js' : ['webpack']
    },

    //CUSTOM PREPROCESSORS
    customPreprocessors:{
      babelSourceMap:{
        base: 'babel',
        options:{
          presets: ['react', 'babel-preset-es2015'],
          sourceMap: 'inline'
        },
        filename: function(file){
          return file.originalPath.replace(/\.js$/, '.es5.js');
        },
        sourceFileName: function(file){
          return file.originalPath;
        }
      },
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    //webpack config
    webpack:{
      module:{
        loaders:[
          {test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader',
         include:[
           path.join(__dirname, 'src'),
           path.join(__dirname, 'UnitTesting')
         ],
         query:{
           presets:['react', 'es2015']
         }}
        ]
      },
      watch: true,
      resolve:{
        extensions:['.js', '.jsx']
      }
    },
    webpackServer:{
      noInfo: true
    },

    // web server port
    port: 9876,


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


    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,


    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,


    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],


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

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}</code></pre>
</div>
</div>
</p>

<p><strong>.babelrc</strong></p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>{
  ""presets"":[""react"", ""babel-preset-es2015""]
}</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/43534993/karma-mocha-react-webpack-unexpected-token-import-on-line-1,"['reactjs', 'webpack', 'mocha.js', 'karma-mocha', 'create-react-app']",437,FALSE,0,0
How can I unit-test this class in Android(it has static final variable)?,"<p>How can I test both methods if they work properly or not using unit-testing?</p>

<pre><code>public class UserSession {

   public static final String SESSION_KEY = ""sessionKey"";

   @Nullable
   public String getSessionKey() {
      return Settings.getSharedPreferences().getString(SESSION_KEY, null);
   }

   private void setSessionKey(String key) {
      Settings.putString(SESSION_KEY, key);
   }
}
</code></pre>
",https://stackoverflow.com/questions/45119262/how-can-i-unit-test-this-class-in-androidit-has-static-final-variable,"['java', 'android', 'unit-testing', 'junit', 'mocking']",94,FALSE,-1,1
PyCharm not detecting tests in Unit Test files named __init__.py?,"<p>I have noticed that when using Python's unittest.TestCase unit testing package, PyCharm's Unit Testing tool is able to recognize the tests when the files are named anything other than <code>__init__.py</code>. However, when I name them <code>__init__.py</code>, PyCharm doesn't pick them up. This is the error I get: </p>

<pre><code>ImportError: '__init__' module incorrectly imported from 'C:\\Users\\morrij14\\AppData\\Roaming\\JetBrains\\PyCharm Community Edition 2017.1.2\\helpers\\pycharm'. Expected 'C:\\Users\\morrij14\\ivy\\Unit_Test3\\lib\\pt_hil\\utilities\\PT_HIL_Report_Utils\\html_utility\\tests'. Is this module globally installed?
</code></pre>

<p>I am guessing it has to be something with the PyCharm settings. Or maybe Unit Test files are not supposed to be named <strong>init</strong>.py</p>
",https://stackoverflow.com/questions/45983148/pycharm-not-detecting-tests-in-unit-test-files-named-init-py,"['python', 'python-2.7', 'unit-testing', 'pycharm', 'python-unittest']",378,FALSE,0,0
Can Jest be used as browser based testing tool?,"<p>I understand that Jest is a unit testing tool for developers used for JavaScript. Is Jest a browser based testing tool similar to Selenium or a functional testing tool?</p>
",https://stackoverflow.com/questions/45171809/can-jest-be-used-as-browser-based-testing-tool,['jestjs'],22898,TRUE,13,3
Mock Microsoft Application Insights API,"<p>I  have an application which writes to App INsights using <a href=""https://learn.microsoft.com/en-us/azure/application-insights/app-insights-api-custom-events-metrics"" rel=""nofollow noreferrer"">custom traces/metrics</a> and also using <a href=""https://dev.applicationinsights.io/"" rel=""nofollow noreferrer"">REST API</a> for reading data on to dashboard. 
<strong>My questions is for my unit testing can I mock both custom traces(TelemetryClient) and REST API?</strong> </p>

<p>I see REST API has a DEMO version but provides random information. It would be helpful if i could setup  a DEMO instrumentation key to write to and read from it for unit testing. Let me know.</p>
",https://stackoverflow.com/questions/43224143/mock-microsoft-application-insights-api,"['unit-testing', 'azure', 'mocking', 'azure-application-insights']",4111,TRUE,4,3
RestTemplate for local file testing,"<p>Since I want to use the RestTemplate from Spring I want to use the same class as well for Unit-Testing. The idea would be to download a JSON-File and save it locally for the purpose of testing. Therefore I would like to change the URI from a HTTP to a File address. When it as File-address I get an Excpetion</p>

<p><code>Exception in thread ""main"" java.lang.IllegalArgumentException: Object of class [sun.net.www.protocol.file.FileURLConnection] must be an instance of class java.net.HttpURLConnection</code> </p>

<pre><code>urlGETList = ""http://api.geonames.org/countryInfoJSON?username=volodiaL"";
RestTemplate restTemplate = new RestTemplate();
CountryInfoResponse results = restTemplate.getForObject(urlGETList, CountryInfoResponse.class);
</code></pre>

<p>Any ideas how I can use the same classes for Unit-Testing?</p>
",https://stackoverflow.com/questions/42020993/resttemplate-for-local-file-testing,"['java', 'spring', 'rest', 'spring-mvc']",1501,TRUE,1,1
Catch fails on simple example,"<p>I am trying to integrate <code>Catch</code> unit testing to my project but it fails for the currently available </p>

<pre class=""lang-none prettyprint-override""><code>Catch v1.10.0
Generated: 2017-08-26 15:16:46.676990
</code></pre>

<p>Example: </p>

<p><code>test.cpp</code></p>

<pre><code>#include ""catch.hpp""

#define CATCH_CONFIG_MAIN


TEST_CASE(""CATCH TEST""){
    REQUIRE(1 == 1);
}
</code></pre>

<pre class=""lang-none prettyprint-override""><code>g++ test.cpp -o test.exe -std=c++11
</code></pre>

<p>Error:</p>

<pre class=""lang-none prettyprint-override""><code>Undefined symbols for architecture x86_64:
  ""Catch::ResultBuilder::endExpression(Catch::DecomposedExpression const&amp;)"", referenced from:
      Catch::BinaryExpression&lt;int const&amp;, (Catch::Internal::Operator)0, int const&amp;&gt;::endExpression() const in test-b77427.o
  ""Catch::ResultBuilder::setResultType(bool)"", referenced from:
      Catch::BinaryExpression&lt;int const&amp;, (Catch::Internal::Operator)0, int const&amp;&gt;::endExpression() const in test-b77427.o
  ""Catch::ResultBuilder::useActiveException(Catch::ResultDisposition::Flags)"", referenced from:
      ____C_A_T_C_H____T_E_S_T____0() in test-b77427.o
  ""Catch::ResultBuilder::react()"", referenced from:
      ____C_A_T_C_H____T_E_S_T____0() in test-b77427.o
  ""Catch::ResultBuilder::ResultBuilder(char const*, Catch::SourceLineInfo const&amp;, char const*, Catch::ResultDisposition::Flags, char const*)"", referenced from:
      ____C_A_T_C_H____T_E_S_T____0() in test-b77427.o
  ""Catch::ResultBuilder::~ResultBuilder()"", referenced from:
      ____C_A_T_C_H____T_E_S_T____0() in test-b77427.o
  ""Catch::SourceLineInfo::SourceLineInfo(char const*, unsigned long)"", referenced from:
      ____C_A_T_C_H____T_E_S_T____0() in test-b77427.o
      ___cxx_global_var_init in test-b77427.o
  ""Catch::isDebuggerActive()"", referenced from:
      ____C_A_T_C_H____T_E_S_T____0() in test-b77427.o
  ""Catch::AutoReg::AutoReg(void (*)(), Catch::SourceLineInfo const&amp;, Catch::NameAndDesc const&amp;)"", referenced from:
      ___cxx_global_var_init in test-b77427.o
  ""Catch::AutoReg::~AutoReg()"", referenced from:
      ___cxx_global_var_init in test-b77427.o
  ""Catch::toString(int)"", referenced from:
      Catch::ExpressionLhs&lt;int const&amp;&gt;::reconstructExpression(std::__1::basic_string&lt;char, std::__1::char_traits&lt;char&gt;, std::__1::allocator&lt;char&gt; &gt;&amp;) const in test-b77427.o
      Catch::BinaryExpression&lt;int const&amp;, (Catch::Internal::Operator)0, int const&amp;&gt;::reconstructExpression(std::__1::basic_string&lt;char, std::__1::char_traits&lt;char&gt;, std::__1::allocator&lt;char&gt; &gt;&amp;) const in test-b77427.o
  ""Catch::ResultBuilder::shouldDebugBreak() const"", referenced from:
      ____C_A_T_C_H____T_E_S_T____0() in test-b77427.o
  ""_main"", referenced from:
     implicit entry/start for main executable
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit
</code></pre>

<pre class=""lang-none prettyprint-override""><code>g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/usr/include/c++/4.2.1
Apple LLVM version 8.1.0 (clang-802.0.42)
Target: x86_64-apple-darwin16.7.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
</code></pre>
",https://stackoverflow.com/questions/45911237/catch-fails-on-simple-example,"['c++', 'c++11', 'catch-unit-test']",2389,TRUE,3,1
How to test a decorator?,"<p>I am new to unit testing. can anyone guide me to test this decorator with mock and patch</p>

<pre><code> def fetch_entity_from_ES(self,func):
    @wraps(func)
    def ES_wrapper(*args):
        entity_type = args[0]
        entity_id = args[1]
        search_service_utility = ElasticSearchUtilities(self.config)
        entity = search_service_utility.fetch_entity_from_ES(entity_type, entity_id)
        if not entity:
            return func(*args)
        return entity
    return ES_wrapper
</code></pre>
",https://stackoverflow.com/questions/46941509/how-to-test-a-decorator,['python'],58,TRUE,1,1
How can I test Page reference in salesforce,"<p>Please I am newbie to salesforce and I want to make unit testing forthis method:</p>

<pre><code>public PageReference method1(){
        PageReference p = new PageReference ('/hello');
        p.setRedirect(true);
        p.getParameters().put('id',id);
         if(code!=null){
            p.getParameters().put('ld',ld);
            p.getParameters().put('ph',ph);
         }
        return p;
    }
</code></pre>

<p>Thank you</p>
",https://stackoverflow.com/questions/46241878/how-can-i-test-page-reference-in-salesforce,"['salesforce', 'apex-code', 'apex']",944,FALSE,-1,1
How to write my first Unit-test for Email-function,"<p>This is just a smaller part of an email sending application, but I'm trying to implement unit-testing for the application. And I've read up a bit on unit testing so far, and I understand you should only test single functions instead of entire classes. How do I test this code?</p>

<pre><code>private void Send(IEnumerable&lt;Customer&gt; customers, string body)
        {
            string titleOfEmail = ""Welcome as a new customer at Company!"";
            string ourEmailAddress = ""info@company.com"";
            int NumberOfRetriesOnError = 2;
            int DelayOnError = 10;

            foreach (var customer in customers)
            {


              for (int i = 0; i &lt;= NumberOfRetriesOnError; ++i)
                {
                    try
                    {
                        Sender.Send(ourEmailAddress, customer.Email, titleOfEmail);
                        return;
                    }
                    catch (SmtpException e)
                    {
                        if (i &lt; NumberOfRetriesOnError)
                            Thread.Sleep((i + 1) * DelayOnError);
                        else
                            Errors.Add(e.Message + customer); // Include customeremail
                    }
                }
}
</code></pre>

<p>Edit: Rest of the information probably not needed for the rest</p>

<pre><code>public interface IMailSender
{
    void Send(string from, string to, string body);
}
sealed class NullMailSender : IMailSender
{
    void IMailSender.Send(string from, string to, string body)
    {

    }
}

sealed class SmtpMailSender : IMailSender
{
    void IMailSender.Send(string from, string to, string body)
    {
        System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
        mail.From = new System.Net.Mail.MailAddress(from);
        System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(""yoursmtphost"");
        mail.To.Add(to);
        mail.Body = body;
        smtp.Send(mail);

    }
}     
</code></pre>

<p>And this part is the rest of the top function, the whole class</p>

<pre><code>public class SendingMail
{
    public List&lt;string&gt; Errors { get; } = new List&lt;string&gt;();

    public IEnumerable&lt;Customer&gt; Customers { get; set; }

    public IEnumerable&lt;Order&gt; Orders { get; set; }

    public IMailSender Sender { get; set; }

    public void SendWelcomeEmails()
    {
        var template = Resources.WelcomeEmailTemplate;
        Send(GetNewCustomers(), Resources.WelcomeEmailTemplate);
    }

    public void SendComeBackEmail()
    {
        var template = Resources.WelcomeEmailTemplate;
        var emailContent = String.Format(template);
        Send(GetCustomersWithoutRecentOrders(), Resources.ComeBackEmailTemplate);
    }

    private IEnumerable&lt;Customer&gt; GetNewCustomers()
    {
        var yesterday = DateTime.Now.Date.AddDays(-1);
        return Customers.Where(x =&gt; x.CreatedDateTime &gt;= yesterday);
    }
    private IEnumerable&lt;Customer&gt; GetCustomersWithoutRecentOrders()
    {
        var oneMonthAgo = DateTime.Now.Date.AddMonths(-1);

        return Customers.Where(c =&gt; {
            var latestOrder = Orders
                .Where(o =&gt; o.CustomerEmail == c.Email)
                .OrderByDescending(o =&gt; o.OrderDatetime)
                .FirstOrDefault();

            return latestOrder != null
                &amp;&amp; latestOrder.OrderDatetime &lt; oneMonthAgo;
        });
    }
</code></pre>
",https://stackoverflow.com/questions/45699191/how-to-write-my-first-unit-test-for-email-function,"['c#', '.net', 'unit-testing', 'email']",2080,TRUE,-1,1
H2 database with Oracle mode failing for row_number() over ( order by cust.id ),"<p>I am using H2 in-memory database for unit testing of Oracle queries. I have written <code>SET MODE Oracle</code> statement.</p>

<p>But, it is failing for below part of oracle query:</p>

<pre><code>row_number() over ( order by cust.id ) as CustCount
</code></pre>

<p>I know this is not allowed in H2 db, but we have set the mode to Oracle. Also, I cannot change the query as prod database is Oracle and H2 db is only for unit testing. So, how to write unit test for this?</p>

<p><strong>Edit</strong></p>

<p>The exception:</p>

<pre><code>org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement ""SELECT RESULTS.* FROM (SELECT ROW_NUMBER() OVER ( ORDER[*] BY CUST.ID ) AS CUSTCOUNT,   CUST.ADDRESS1 FROM CUSTOMER) RESULTS WHERE CUSTCOUNT BETWEEN 1 AND 50  ""; expected "")""; SQL statement:
SELECT RESULTS.* FROM (SELECT ROW_NUMBER() OVER ( ORDER[*] BY CUST.ID ) AS CUSTCOUNT,   CUST.ADDRESS1 FROM CUSTOMER) RESULTS WHERE CUSTCOUNT BETWEEN 1 AND 50  [42001-193]
</code></pre>
",https://stackoverflow.com/questions/42297452/h2-database-with-oracle-mode-failing-for-row-number-over-order-by-cust-id,"['oracle', 'unit-testing', 'h2']",514,FALSE,0,0
Configuring Dbcontext as Transient,"<p>In ASP.NET Core / EntityFramework Core, the services.AddDbContext&lt;> method will add the specified context as a scoped service.  It's my understanding that that is the suggested lifetime management for the dbcontext by Microsoft.</p>

<p>However, there is much debate in our engineer department over this and many feel that the context needs to be disposed of ASAP.  So, what is the best way to configure the dbcontext as Transient that still maintains the same Repository pattern typically used (i.e. injecting the context directly into the repository's constructor) as well as supporting flexible unit testing?</p>
",https://stackoverflow.com/questions/41923804/configuring-dbcontext-as-transient,"['c#', 'asp.net-core', 'entity-framework-core']",56763,TRUE,65,3
Jasmine Cannot read property &#39;length&#39; of undefined,"<p>Hi am a newbie to Unit Testing I have written a program which takes 3 arguments two romanletters and one operator(+,-,/,*) it should perform operations and it should return the value in romanLetters am trying to write a unit testing for that problem it says cannot read property length of undefined i dont know why is happening my code runs fine though. Am attaching my code here</p>

<p>Mainjs File</p>

<pre><code>var main=function(operand1,operand2,operator) {
    var concat,number;
    var operand1=romantonumerals(operand1);
    var operand2=romantonumerals(operand2);
    //var operator=operatorconversion(operator);
    console.log(""operand1 ""+operand1);
    console.log(""operand2 ""+operand2);
    if(operand1&gt;operand2) {
      concat=operand1+operator+operand2;
    }
    else {
      concat=operand2+operator+operand1;
    }
    number=Math.round(eval(concat));
    console.log(number);
    if(number&lt;500) {
      result=numeralstoroman(number)
    }
    else if(number===0) {
      result=""Make sure its greater than 0"";
    }
    else {
      result=""Make sure your number gets less than 500 try with some other romans"";
    }
    console.log(result);
    return result;
  };
  var numeralstoroman=function(number) {
    var roman="""",temp;
    var ones=function(number) {
      switch (number) {
        case 1:
          roman+=""I"";
          break;
        case 2:
          roman+=""II"";
          break;
        case 3:
          roman+=""III"";
          break;
        case 4:
          roman+=""IV"";
          break;
        case 5:
          roman+=""V"";
          break;
        case 6:
          roman+=""VI"";
          break;
        case 7:
          roman+=""VII"";
          break;
        case 8:
          roman+=""VIII"";
          break;
        case 9:
          roman+=""IX"";
          break;
      }
    };
    var twos=function(number) {
      if(number&gt;=10 &amp;&amp; number&lt;20) {
        roman+=""X"";
        ones(number%10);
      }
      else if(number&gt;=20 &amp;&amp; number30) {
        roman+=""XX"";
        ones(number%10);
      }
      else if(number&gt;=30 &amp;&amp; number&lt;40) {
        roman+=""XXX"";
        ones(number%10);
      }
      else if(number&gt;=40 &amp;&amp; number&lt;50) {
        roman+=""XL"";
        ones(number%10);
      }
      else if(number&gt;=50 &amp;&amp; number&lt;60) {
        roman+=""L"";
        ones(number%10);
      }
      else if(number&gt;=60 &amp;&amp; number&lt;70) {
        roman+=""LX"";
        ones(number%10);
      }
      else if(number&gt;=70 &amp;&amp; number&lt;80) {
        roman+=""LXX"";
        ones(number%10);
      }
      else if(number&gt;=80 &amp;&amp; number&lt;90) {
        roman+=""LXXX"";
        ones(number%10);
      }
      else if(number&gt;=90 &amp;&amp; number&lt;100) {
        roman+=""XC"";
        ones(number%10);
      }
    };
    var threes=function(number) {
      if(number&gt;=100 &amp;&amp; number&lt;200) {
          roman+=""C"";
          if(number%100&lt;10) {
            ones(number%10);
          }
          else {
            twos(number%100);
          }
      }
      else if(number&gt;=200 &amp;&amp; number&lt;300) {
          roman+=""CC"";
          if(number%100&lt;10) {
            ones(number%10);
          }
          else {
            twos(number%100);
          }
      }
      else if(number&gt;=300 &amp;&amp; number&lt;400) {
          roman+=""CCC"";
          if(number%100&lt;10) {
            ones(number%10);
          }
          else {
            twos(number%100);
          }
      }
      else if(number&gt;=400 &amp;&amp; number&lt;500) {
          roman+=""CD"";
          if(number%100&lt;10) {
            ones(number%10);
          }
          else {
            twos(number%100);
          }
      }
    }
    if(number&lt;10) {
      ones(number);
    }
    else if(number&gt;=10 &amp;&amp; number&lt;100) {
      twos(number);
    }
    else if(number&gt;=100 &amp;&amp; number&lt;500) {
      threes(number);
    }
    console.log(roman);
    return roman;
  };
  var character=function(str) {
    switch(str) {
      case ""I"":
        return 1
      case ""V"":
        return 5
      case ""X"":
        return 10
      case ""L"":
        return 50
      case ""C"":
        return 100
      case ""D"":
        return 500
      default:
        return -1;
    }
  }
  var romantonumerals=function(operand) {
    var no=0,i=0,char1="""",char2="""";
    while(i&lt;operand.length) {
      char1=character(operand[i]);
      if(i+1&lt;operand.length) {
        char2=character(operand[i+1]);
        if(char1&gt;=char2) {
          no+=char1;
          i++;
        }
        else {
          no=no+(char2-char1);
          i+=2;
        }
      }
      else {
        no+=char1;
        i++;
      }
    }
    return no;
  };
  var ans=main(""V"",""I"",""+"");
  console.log(ans);
</code></pre>

<p>JasmineHTML FIle</p>

<pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
    &lt;meta charset=""utf-8""&gt;
    &lt;title&gt;Jasmine Spec Runner v2.2.0&lt;/title&gt;

    &lt;link rel=""shortcut icon"" type=""image/png"" href=""lib/jasmine-2.2.0/jasmine_favicon.png""&gt;
    &lt;link rel=""stylesheet"" href=""lib/jasmine-2.2.0/jasmine.css""&gt;

    &lt;script src=""lib/jasmine-2.2.0/jasmine.js""&gt;&lt;/script&gt;
    &lt;script src=""lib/jasmine-2.2.0/jasmine-html.js""&gt;&lt;/script&gt;
    &lt;script src=""lib/jasmine-2.2.0/boot.js""&gt;&lt;/script&gt;

    &lt;!-- include source files here... --&gt;
    &lt;script src=""romtantonumeralstoroman.js""&gt;&lt;/script&gt;
    &lt;!-- include spec files here... --&gt;
    &lt;script src=""spec.js""&gt;&lt;/script&gt;


  &lt;/head&gt;

  &lt;body&gt;
  &lt;/body&gt;
  &lt;/html&gt;
</code></pre>

<p>Jasmine Testing File</p>

<pre><code>describe(""A suite"", function() {
it(""contains spec with an expectation"", function() {
    main();
    expect(main(""V"",""I"",""+"").toBe(""VI""));
});
});
</code></pre>

<p>JSFIDDLE Link</p>

<p><a href=""https://jsfiddle.net/pLecneto/"" rel=""nofollow noreferrer"">https://jsfiddle.net/pLecneto/</a></p>
",https://stackoverflow.com/questions/44177659/jasmine-cannot-read-property-length-of-undefined,"['javascript', 'unit-testing', 'testing', 'jasmine']",4386,TRUE,0,1
Jest tests for redux-observable,"<p>I have the following epic, the variable SampleStores has some sample data.  How do I perform unit testing on this with jest?</p>

<pre><code>export const incrementalSearchEpic = action$ =&gt; {
    return action$.ofType('SEARCH_STORES').mergeMap(action =&gt; {
        const incrementalSearchResults =
            // eslint-disable-next-line max-len
            SampleStores.filter(sampleStore =&gt;
                (sampleStore.Name.toLowerCase().includes(action.SearchText.toLowerCase().trim())) ||
                // eslint-disable-next-line max-len
                (sampleStore.Location.toLowerCase().includes(action.SearchText.toLowerCase().trim()))
            ).map(sampleStore =&gt; ({                
                type: 'FILTERED_STORE',
                searchText: action.SearchText.toLowerCase().trim(),
                store: sampleStore
            }));

        //Create the interval to emit an item every second
        return Observable.interval(1000)
            .take(incrementalSearchResults.length).map(t =&gt; incrementalSearchResults[t]);
    });
};
</code></pre>
",https://stackoverflow.com/questions/44623073/jest-tests-for-redux-observable,"['jestjs', 'redux-observable']",152,FALSE,2,0
Properly stubbing request/response with Sinon/Mocha,"<p>I'm relatively new to unit-testing on the backend and need some guidance as to how to unit-test the following. I'm using Mocha/Should/Sinon.</p>

<pre><code>exports.get = function(req, res) {
   if (req.query.example) {
      return res.status(200).json({ success: true });
   } else {
      return res.status(400).json({error: true});
   } 
}
</code></pre>
",https://stackoverflow.com/questions/43739460/properly-stubbing-request-response-with-sinon-mocha,"['javascript', 'node.js', 'unit-testing', 'mocha.js', 'sinon']",5290,TRUE,6,1
Code coverage for angular 2,"<p>How do you find the code coverage for angular 2 code? Is there any plugin for vs code editor or webstorm that I can use? I am using Jasmine and Karma for unit testing of my code.</p>
",https://stackoverflow.com/questions/44463706/code-coverage-for-angular-2,"['angular', 'unit-testing', 'typescript', 'code-coverage']",34724,TRUE,16,4
What&#39;s the best approach to testing private Stateless components functions?,"<p>Let's say we have this stateless component</p>

<pre><code>import React from ‘react’;

const HelloWorld = ({name}) =&gt; (

  const sayHi = event =&gt; {
    alert(`Hi ${name}`);
  }

  return (
    &lt;div&gt;
      &lt;a 
        href=""#""
        onClick={sayHi}&gt;Say Hi&lt;/a&gt;
    &lt;/div&gt;
  );
);

export default HelloWorld;
</code></pre>

<p>What's the best approach to testing <code>sayHi</code> function?<br>
Knowing that I to do unit testing for it.</p>
",https://stackoverflow.com/questions/41587188/whats-the-best-approach-to-testing-private-stateless-components-functions,"['javascript', 'reactjs']",1027,TRUE,2,1
Test Cases for Integration Testing for Instant Messaging Chat App,"<p>I have created a Instant Messaging Chat App using Telegram Open Source Code for my College Project. Most of the functionality are similar to WhatsApp. I have created Test Cases for Unit Testing. But stuck in writing test cases for Integration Testing because exactly I don't know what to write in test case for integration testing.
Here I have attached test cases Format/Template for Unit testing. </p>

<p><a href=""https://i.stack.imgur.com/aJNKw.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/aJNKw.png"" alt=""Test Cases for Unit Testing""></a></p>

<p>Please suggest test cases with Expected Input and Expected result for Integration testing-</p>
",https://stackoverflow.com/questions/44033914/test-cases-for-integration-testing-for-instant-messaging-chat-app,"['android', 'unit-testing', 'testing', 'integration-testing']",3499,FALSE,0,1
Angular2 / Jasmine: Testing Service with another Service as a dependency,"<p>Setup: an APP_INITIALIZER service <code>ConfigurationService</code>, which loads config data, is being used across app components and services. When unit testing components, it reads the config file and evaluates correctly. When unit testing services, which use configuration, it fails.</p>

<p>It is set up as follows:</p>

<p><strong>app.module.ts</strong></p>

<pre><code>export function ConfigurationFactory( config: ConfigurationService ): any {
  // this line actually triggers the loading of the config file  
  return () =&gt; config.load(); 
}

@NgModule({
  bootrstrap: {},
  ...,
  providers : [
    ConfigurationService,
    {
      deps: [ ConfigurationService ],
      multi: true,
      provide: APP_INITIALIZER,
      useFactory: ConfigurationFactory,   
    }
  ]
})
</code></pre>

<p><strong>ConfigurationService.ts</strong></p>

<pre><code>@Injectable()
export class ConfigurationService {

  // error holder
  public error: boolean = false;
  // data holder
  public data: any = {};
  // config file url
  private configUrl: string = './assets/config/config.json';

  constructor( private http: Http ) {
  }
  /**
   * reads config file
   */
  public load(): Promise&lt;any&gt; {
    return this.http.get( this.configUrl )
      .map( ( response: any ) =&gt; response.json() )
      .toPromise()
      .then( ( data: any ) =&gt; this.data = data )
      .catch( ( err: any ) =&gt; Promise.resolve() );
  }

}
</code></pre>

<p>Here is the <strong>TestableService.service.ts</strong> which uses the config service, too</p>

<pre><code>@Injectable()
export class TestableService extends SomeAbstractHttpService {
  constructor( http: Http,
               private config: ConfigurationService ) {
    super( http );
  }

  public setRequest( sessionId: string, isIdent: boolean ): void {
    if ( isIdent ) {
      this.resourceUrl = `${ this.config.data.contextRootRest}/documents/ident/${sessionId}`;
    } else {
      this.resourceUrl = `${ this.config.data.contextRootRest}/documents/noident/${sessionId}`;
    }
    this.headers = new Headers();
    this.headers.append( 'Content-Type', 'application/json' );
    this.headers.append( 'Accept', 'application/json, application/pdf' );
    this.requestOptions = new RequestOptions( {
      headers: this.headers,
      responseType: ResponseContentType.Blob
    } );
  }
}
</code></pre>

<p>Now to spec file, <strong>TestableService.service.spec.ts</strong></p>

<pre><code>export function ConfigurationFactory( config: ConfigurationService ): any {
  return () =&gt; config.load();
}

describe( 'TestableService', () =&gt; {

  // not ideal to hardcode it here, I would prefer using the same config file, which is used across the app!
  let mockConfig: any = {contextRootRest: 'rest/'};
  let theService: TestableService; 

  beforeEach( async(() =&gt; {
    TestBed.configureTestingModule( {
      imports: [
        HttpModule,
      ],
      providers: [
        TestableService,
        MockDataService,
        { provide: XHRBackend, useClass: MockBackend },
        ConfigurationService,
        {
          // Provider for APP_INITIALIZER
          deps: [ ConfigurationService ],
          multi: true,
          provide: APP_INITIALIZER,
          useFactory: ConfigurationFactory,
        },
      ]
    } );
  } ) );

  // I suspect, that using APP_INITIALIZER at this stage is goofy, 
  // as I do not in fact instantiate the app, only the service. 
  // What would be the correct way to do it here?

  beforeEach( inject( [ TestableService, XHRBackend ], ( service: TestableService, backend: MockBackend ) =&gt; {
    theService = service;
    mockBackend = backend;
  } ) );  

  it( 'should set request correctly', ( ) =&gt; {
    theService.setRequest( '1234567890', true );
    expect( theService.resourceUrl )
        .toEqual( `${ mockConfig.contextRootRest }/documents/ident/1234567890` );
  });
});
</code></pre>

<p>And it fails with <code>Expected 'undefined/documents/ident/1234567890' to equal 'rest/documents/ident/1234567890'</code> - which means, that the Config service has not been loaded at the TestableService at all. Any ideas?</p>
",https://stackoverflow.com/questions/46173834/angular2-jasmine-testing-service-with-another-service-as-a-dependency,"['angular', 'unit-testing', 'dependency-injection', 'jasmine']",1529,TRUE,0,1
scala play framework how to unit test async controllers,"<p>Using Scala play version 2.5 and trying to follow the guidelines for unit testing controllers as per documentation at: <a href=""https://www.playframework.com/documentation/2.5.x/ScalaTestingWithScalaTest"" rel=""nofollow noreferrer"">https://www.playframework.com/documentation/2.5.x/ScalaTestingWithScalaTest</a></p>

<p>there's no example for unit testing an async controller.</p>

<p>I'm trying to create a unit test for my controller which has an async action method, I ended up mocking some objects</p>

<pre><code>class ProductController @Inject()(
    action: ProductAction,
    handler: ProductResourceHandler)(implicit ec: ExecutionContext)
    extends Controller {

  /**
   * Fetch a list of products
   */
  def index: Action[AnyContent] = {
    action.async { implicit request =&gt;
      handler.find.map { list =&gt;                                
        Ok(Json.toJson(list))
      }
    }
  }
// ...
}
</code></pre>

<p>My unit test:</p>

<pre><code>import scala.concurrent.Future
import org.scalatestplus.play._
import play.api.mvc._
import play.api.test._
import play.api.test.Helpers._
import org.scalatest.mockito.MockitoSugar
import product.ProductAction
import product.ProductController
import product.services.maps.GeolocationService
import product.ProductResourceHandler
import play.api.libs.concurrent.Execution.Implicits._
import scala.io.Source
import play.api.libs.json.Json
import product.model.OfferList
import product.model.OfferDetail
import org.mockito.Mockito._

class ProductControllerSpec extends PlaySpec with Results with MockitoSugar {

  private val productList = Json.parse(Source.fromFile(""conf/app/sample_products.json"").getLines.mkString).as[ProductList]

  ""Example Page#index"" should {
    ""should be valid"" in {
      val action = new ProductAction()
      val handler = mock[ProductResourceHandler]      
      when(handler.find) thenReturn Future.successful(productList)      
      val controller = new ProductController(action, handler)
      val result: Future[Result] = controller.index().apply(FakeRequest())      
      val bodyText: String = contentAsString(result)                                
      bodyText != null mustBe true
    }
  }
}
</code></pre>

<p>up till now it's working but I'm wondering if this follows the best practices or guidelines for this type of test. Is this the right way to unit test an async controller in Scala play framework?</p>
",https://stackoverflow.com/questions/44509708/scala-play-framework-how-to-unit-test-async-controllers,"['scala', 'unit-testing', 'asynchronous', 'playframework']",2121,TRUE,3,2
Unable to cast object of type &#39;System.Linq.EnumerableQuery to type &#39;Microsoft.Azure.Documents.Linq.IDocumentQuery,"<p>I have a class with the following Method and am using Moq as a Unit Testing Framework. How can I mock the following:</p>

<pre><code>FeedOptions feedOptions = new FeedOptions
        {
            MaxItemCount = 1000
        };

        var query = await _storeAccessClient.CreateDocumentQueryAsync&lt;CustomEntity&gt;(_collectionLink, feedOptions)
            .Where(c =&gt; c.DataType == _dataType)
            .OrderBy(c =&gt; c.StartTime, sortOrder)
            .AsDocumentQuery()
        .ExecuteNextAsync&lt;CustomEntity&gt;();

        List&lt;CustomEntity&gt; result = query.ToList&lt;CustomEntity&gt;();
</code></pre>

<p>Any Help is greatly Appreciated !!</p>
",https://stackoverflow.com/questions/43563690/unable-to-cast-object-of-type-system-linq-enumerablequery-to-type-microsoft-az,"['linq', 'azure', 'azure-cosmosdb']",2593,TRUE,6,1
Spring MVC Mock Error,"<p>I want to use spring mvc test for unit testing, but occur the following error, anyone help?</p>

<blockquote>
  <p>Java.lang.NoSuchMethodError:
  org.springframework.beans.factory.support.RootBeanDefinition.setTargetType(Lorg/springframework/core/ResolvableType;)V</p>

<pre><code>  at org.springframework.boot.test.mock.mockito.MockitoPostProcessor.createBeanDefinition(MockitoPostProcessor.java:208)
  at org.springframework.boot.test.mock.mockito.MockitoPostProcessor.registerMock(MockitoPostProcessor.java:187)
  at org.springframework.boot.test.mock.mockito.MockitoPostProcessor.register(MockitoPostProcessor.java:178)
  at org.springframework.boot.test.mock.mockito.MockitoPostProcessor.postProcessBeanFactory(MockitoPostProcessor.java:148)
  at org.springframework.boot.test.mock.mockito.MockitoPostProcessor.postProcessBeanFactory(MockitoPostProcessor.java:135)
  at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:284)
  at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:174)
  at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:681)
  at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:523)
  at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761)
  at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371)
  at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
  at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:111)
  at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
  at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
  at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
  at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189)
  at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131)
  at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
  at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
  at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
  at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
  at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
  at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
  at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
  at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
  at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
  at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
  at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
  at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
  at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
  at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
  at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:498)
  at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)


Process finished with exit code 255
</code></pre>
</blockquote>

<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = WebAPIController.class)
@AutoConfigureMockMvc
public class WebAPIControllerTest {

    @Autowired
    private WebApplicationContext ctx;

    private MockMvc mockMvc;

    @MockBean(classes = NotifyTaskService.class)
    private NotifyTaskService notifyTaskService;

    @Autowired
    private WebAPIController webAPIController;

    @Before
    public void before() throws Exception {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.ctx).build();
    }

    @After
    public void after() throws Exception {
    }

    /**
     * Method: sendNotifyAPI(String systemKey, String user, String type, String mechanism, String defaultMethod, String msgContent)
     */
    @Test
    public void testSendNotifyAPI() throws Exception {

    }
</code></pre>
",https://stackoverflow.com/questions/44548795/spring-mvc-mock-error,"['testing', 'model-view-controller', 'spring-test', 'spring-test-mvc']",805,FALSE,1,2
Testing my DevelopmentPod from Example Project not working,"<p>I'm writing my own Pod and wanted to start unit Testing. But I can't figure out where in my Project to test. 
I thought the Example Project was the right place to write my Tests, but from there I don't have internal Access to my DevelopmentPod.</p>

<p>I have to say it's the first XCode Project in which I want to unit test. So I'm not very familiar with it. </p>

<p>Any help on how unit Testing in Cocoapods should be set up is really appreciated.</p>
",https://stackoverflow.com/questions/42971964/testing-my-developmentpod-from-example-project-not-working,"['ios', 'swift', 'unit-testing', 'cocoapods', 'xctest']",37,FALSE,0,0
How to do tests AngularJS with Jasmine and Chutzpah?,"<p>I'm new to AngularJS testing with Jasmine. I'm little bit lost with following things.</p>

<ol>
<li>I know Jasmine is used for unit testing. But can someone elaborate that more? </li>
<li>And I also want to know how Jasmine and chutzpah work?</li>
</ol>

<p>I found several tutorials online. But those are little bit hard to understand.
These are the links I followed.</p>

<p><a href=""https://www.google.lk/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=1&amp;cad=rja&amp;uact=8&amp;ved=0ahUKEwi78K3E4prYAhWJtY8KHYtMBkAQFgglMAA&amp;url=https%3A%2F%2Fscotch.io%2Ftutorials%2Ftesting-angularjs-with-jasmine-and-karma-part-1&amp;usg=AOvVaw0ypXx4DwGvCn-ZfN2z1-CJ"" rel=""nofollow noreferrer"">Testing AngularJS with Jasmine and Karma (Part 1) ― Scotch</a> </p>

<p><a href=""https://ciphertrick.com/2015/08/03/angularjs-unit-testing-tutorial-karma-jasmine/"" rel=""nofollow noreferrer"">AngularJS unit testing tutorial with karma-jasmine</a></p>

<p>If someone can direct me to good tutorials, that'll be great. 
Thank You.</p>
",https://stackoverflow.com/questions/47921821/how-to-do-tests-angularjs-with-jasmine-and-chutzpah,"['javascript', 'angularjs', 'unit-testing', 'jasmine', 'chutzpah']",95,FALSE,0,0
Apache Camel Mock ProducerTemplate Endpoint,"<p>I want to mock the mail sending not to send mail in unit testing.</p>

<p>My code is below:</p>

<pre><code>@Component(""utilityRoutes"")
public class UtilityRoutes extends RouteBuilder {

  @Override
  public void configure() throws Exception {
    from(""seda:sendEmail"")
    .routeId(""utilityRoutes"")   
    .setHeader(""from"", simple(""{{email.from}}""))        
    .setHeader(""contentType"", constant(""text/plain;charset=UTF-8""))

    .choice()
        .when(header(Constants.HEADER_EMAIL_TARGET).isEqualTo(""AAA""))
            .setHeader(""to"", simple(""{{recipients-a}}""))
        .when(header(Constants.HEADER_EMAIL_TARGET).isEqualTo(""BBB""))
            .setHeader(""to"", simple(""{{recipients-b}}""))
    .end()

    .to(""{{email.url}}"")
    .id(""emailUrl"");

  }

}
</code></pre>

<p>My Test Case is:</p>

<pre><code>@RunWith(CamelSpringBootRunner.class)
@SpringBootTest
@TestPropertySource(locations = ""classpath:application.properties"")
@ContextConfiguration(classes = { RailMLExport.class })
@DirtiesContext
public class UtilityRoutesTest extends CamelTestSupport {

  @Autowired
  CamelContext camelContext;

  @Produce(uri = ""seda:sendEmail"")
  ProducerTemplate producerTemplate;

  @EndpointInject(uri=""mock:emailEndpoint"")
  MockEndpoint mailEndpoint;

  @Override
  public boolean isUseAdviceWith() {
    return true;
  }

  @Override
  public String isMockEndpoints() {
    return ""*"";
  }

  @Test
  public void testSendAndReceiveMail() throws Exception {

    camelContext.getRouteDefinition(""utilityRoutes"").adviceWith(camelContext, new AdviceWithRouteBuilder() {
        @Override
        public void configure() throws Exception {
            weaveById(""emailUrl"").after().to(""mock:emailEndpoint"");
        }
    }

    );
    camelContext.start();
    Collection&lt;Endpoint&gt; endpoints = camelContext.getEndpoints();
    for (Endpoint endpoint : endpoints) {
        System.err.println(endpoint.getEndpointUri());
    }

    mailEndpoint.expectedMessageCount(1);
    mailEndpoint.expectedBodyReceived();

    Map&lt;String,Object&gt; headers = new HashMap&lt;&gt;();
    headers.put(Constants.HEADER_EMAIL_TARGET,""AAA"");
    headers.put(Constants.HEADER_EMAIL_SUBJECT, ""CCC"");

    producerTemplate.requestBodyAndHeaders(""seda:sendEmail"", ""test"", headers);
    mailEndpoint.assertIsSatisfied();

  }
}
</code></pre>

<p>I give error as follows.</p>

<pre><code>java.lang.IllegalStateException: ProducerTemplate has not been started
  at org.apache.camel.impl.DefaultProducerTemplate.getProducerCache(DefaultProducerTemplate.java:689)
  at org.apache.camel.impl.DefaultProducerTemplate.send(DefaultProducerTemplate.java:148)
  at org.apache.camel.impl.DefaultProducerTemplate.sendBodyAndHeaders(DefaultProducerTemplate.java:267)
  at org.apache.camel.impl.DefaultProducerTemplate.requestBodyAndHeaders(DefaultProducerTemplate.java:317)
  at org.apache.camel.impl.DefaultProducerTemplate.requestBodyAndHeaders(DefaultProducerTemplate.java:313)
  at fi.vr.h.ivu.integration.railmlexport.routes.UtilityRoutesTest.testSendAndReceiveMail(UtilityRoutesTest.java:89)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
  at java.lang.reflect.Method.invoke(Unknown Source)
  at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
  at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
  at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
  at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
  at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
  at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
  at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
  at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
  at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
  at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
  at org.junit.rules.RunRules.evaluate(RunRules.java:20)
  at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
  at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
  at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
  at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
  at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
  at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
  at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
  at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
  at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
  at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
  at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
  at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
  at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
  at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
  at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
  at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
  at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
</code></pre>
",https://stackoverflow.com/questions/46602796/apache-camel-mock-producertemplate-endpoint,"['unit-testing', 'apache-camel']",5139,TRUE,3,1
mock xmlrpc.client method python,"<p>I am in the process of learning unit testing, however I am struggling to understand how to mock functions for unit testing.  I have reviewed many how-to's and examples but the concept is not transferring enough for me to use it on my code.  I am hoping getting this to work on a actual code example I have will help.</p>

<p>In this case I am trying to mock isTokenValid.</p>

<p>Here is example code of what I want to mock.</p>

<pre><code>&lt;in library file&gt;

import xmlrpc.client as xmlrpclib   

class Library(object):
    def function:
        #...
        AuthURL = 'https://example.com/xmlrpc/Auth'
        auth_server = xmlrpclib.ServerProxy(AuthURL)
        socket.setdefaulttimeout(20)
        try:
            if pull == 0:
                valid = auth_server.isTokenValid(token)
        #...
</code></pre>

<p>in my unit test file I have </p>

<pre><code>import library

class Tester(unittest.TestCase):
    @patch('library.xmlrpclib.ServerProxy')
    def test_xmlrpclib(self, fake_xmlrpclib):
        assert 'something'
</code></pre>

<p>How would I mock the code listed in 'function'?   Token can be any number as a string and valid would be a int(1)</p>
",https://stackoverflow.com/questions/41457068/mock-xmlrpc-client-method-python,"['python', 'unit-testing', 'mocking']",1532,TRUE,9,2
Jest es6 modules: unexpected module import,"<p>I'm trying to test a file which needs to import an es6 module like this:</p>

<p><a href=""https://repl.it/HG9t/0"" rel=""noreferrer"">https://repl.it/HG9t/0</a></p>

<p>It seems I'm missing some configurations to make it work properly.</p>

<p>If you can achieve this with another unit testing framework easily, I'm interested too.</p>

<p>Thank you in advance for your help.</p>
",https://stackoverflow.com/questions/43366382/jest-es6-modules-unexpected-module-import,"['javascript', 'unit-testing', 'jestjs']",30188,TRUE,24,3
JUnit testing with hard coded database queries,"<p>Can I use JUnit for unit testing when the function I want to test contains hard coded database queries (these are written in Java). </p>
",https://stackoverflow.com/questions/47508737/junit-testing-with-hard-coded-database-queries,['junit'],52,FALSE,0,1
How to unit test HttpContext.SignInAsync()?,"<p><a href=""https://github.com/aspnet/HttpAbstractions/blob/3e3772eecd4cc57399c28a3f899e6b0406ef2e1b/src/Microsoft.AspNetCore.Authentication.Abstractions/AuthenticationHttpContextExtensions.cs#L143"" rel=""noreferrer"">SignInAsync() Source Code</a></p>

<p>I ran into some problems with unit testing.</p>

<ol>
<li><code>DefaultHttpContext.RequestServices</code> is <em>null</em></li>
<li>I tried to create the <code>AuthenticationService</code> object, but I do not know what parameters to pass</li>
</ol>

<p>What should I do? How to unit test <code>HttpContext.SignInAsync()</code>?</p>

<p>Method under test</p>

<pre><code>public async Task&lt;IActionResult&gt; Login(LoginViewModel vm, [FromQuery]string returnUrl)
{
    if (ModelState.IsValid)
    {
        var user = await context.Users.FirstOrDefaultAsync(u =&gt; u.UserName == vm.UserName &amp;&amp; u.Password == vm.Password);
        if (user != null)
        {
            var claims = new List&lt;Claim&gt;
            {
                new Claim(ClaimTypes.Name, user.UserName)
            };
            var identity = new ClaimsIdentity(claims, ""HappyDog"");

            // here
            await HttpContext.SignInAsync(new ClaimsPrincipal(identity));
            return Redirect(returnUrl ?? Url.Action(""Index"", ""Goods""));
        }
    }
    return View(vm);
}
</code></pre>

<p>What I have tried so far.</p>

<pre><code>[TestMethod]
public async Task LoginTest()
{
    using (var context = new HappyDogContext(_happyDogOptions))
    {
        await context.Users.AddAsync(new User { Id = 1, UserName = ""test"", Password = ""password"", FacePicture = ""FacePicture"" });
        await context.SaveChangesAsync();

        var controller = new UserController(svc, null)
        {
            ControllerContext = new ControllerContext
            {
                HttpContext = new DefaultHttpContext
                {
                    // How mock RequestServices?
                    // RequestServices = new AuthenticationService()?
                }
            }
        };
        var vm = new LoginViewModel { UserName = ""test"", Password = ""password"" };
        var result = await controller.Login(vm, null) as RedirectResult;
        Assert.AreEqual(""/Goods"", result.Url);
    }
}
</code></pre>
",https://stackoverflow.com/questions/47198341/how-to-unit-test-httpcontext-signinasync,"['c#', 'unit-testing', 'asp.net-core', 'asp.net-core-mvc', 'asp.net-core-2.0']",9847,TRUE,18,3
How do I include testing in an existing project created with vue cli?,"<p>When I do <code>vue init webpack my-project</code> according to <a href=""https://v2.vuejs.org/v2/guide/installation.html#CLI"" rel=""nofollow noreferrer"">these instructions</a>, I'm given a questionaire where I'm asked if I want to include linting and testing. If I say yes, the project is set up with testing in place.</p>
<p>However in one of my vue projects, I started it out without saying yes.
But now, I want to include unit testing.</p>
<p>Traditional methods of installing Karma and Jasmine seems too cumbersome and I don't know which files I need to modify in order to wire up all the dependencies correctly.</p>
<p>Is there a CLI command that I can run, that asks me those questions again so that it wires up unit testing for me, automatically?</p>
",https://stackoverflow.com/questions/41899695/how-do-i-include-testing-in-an-existing-project-created-with-vue-cli,"['webpack', 'jasmine', 'vue.js', 'karma-jasmine']",2310,TRUE,8,2
How to set up Mockito for Kotlin and Android,"<p>I want to use Mockito for unit testing, so I added the Mockito library into my gradle dependencies.</p>

<pre><code>testImplementation 'junit:junit:4.12'
testCompile 'org.mockito:mockito-core:2.12.0' 
</code></pre>

<p>But still, I can not use any Mockito annotations.</p>

<p><strong>/androidTest/ExampleTest.kt</strong></p>

<pre><code>@RunWith(MockitoJUnitRunner::class) // Unresolved reference MockitoJUnitRunner
@Mock // Unresolved reference Mock
</code></pre>

<p>What I'm missing it?</p>
",https://stackoverflow.com/questions/47282198/how-to-set-up-mockito-for-kotlin-and-android,"['android', 'kotlin', 'mockito']",10084,TRUE,8,4
How do we add Unit Tests for Javascript hasOwnProperty() function,"<p>I'm trying to add Unit Testing for this function:</p>

<pre><code>var advance = function (des, source) {
        for (var p in source) {
            if (source.hasOwnProperty(p)) {
                des[p] = source[p];
            }
        }
        return des;
};
</code></pre>

<p>How do we check <code>hasOwnProperty()</code> method in Jasmine? </p>

<p>Edit:
<strong>Possible solution</strong></p>

<pre><code>var des;
var source;
beforeEach(function () {
    des = {};
    source = {
        p: 'value',
        p1: 'value1'
    };
});

beforeAll(function () {
    advance(des, source);
});

it('should has a property with the name of the argument', function () {
    expect(source).toEqual(jasmine.objectContaining({
        p: 'value'
    }));
    expect(source).not.toEqual(jasmine.objectContaining({
        p2: 'value2'
    }));
});
</code></pre>

<p>Someone, please suggest any better solution.</p>
",https://stackoverflow.com/questions/45726736/how-do-we-add-unit-tests-for-javascript-hasownproperty-function,"['javascript', 'unit-testing', 'jasmine', 'karma-jasmine']",1659,TRUE,0,1
Post-fork connection to Cassandra under gunicorn,"<p>I'm developing a Flask microservice to expose some data from a Cassandra database. It is served with <code>gunicorn</code> being called from the command line.  I'm confused regarding as to where and how to connect to the database under <code>gunicorn</code>, particularly when considering how to mock or bypass the need of the database when doing unit testing.</p>
<p>My first attempt was to connect at app creation time, as follows:</p>
<pre><code>def create_app():
    app = Flask(__name__)

    app.debug = True

    cluster = Cluster([os.environ['CASSANDRA_HOST']])
    app.cassandra = cluster.connect(os.environ['CASSANDRA_KEYSPACE'])

    return app
</code></pre>
<p>thinking that it will make a single &quot;global&quot; connection reducing overhead for each individual request. This clearly fails unit testing as it'll try to connect which is not the point of a unit testing in an isolated environment of a CI pipeline.</p>
<p>Then, checking some <a href=""https://image.slidesharecdn.com/pythonandcassandra-150319091009-conversion-gate01/95/python-and-cassandra-26-638.jpg?cb=1426774311"" rel=""nofollow noreferrer"">slides</a> from Cassandra people it says that for Flask under <code>gunicorn</code> we should use <code>@app.before_first_request</code> and that as a general rule should connect &quot;post-fork&quot;. I'm not sure what &quot;post-fork&quot; means in this context.</p>
<p>Anyhow, doing:</p>
<pre><code>@app.before_first_request
def before_request():
    app.cluster = Cluster([os.environ['CASSANDRA_HOST']])
    app.cassandra = app.cluster.connect(os.environ['CASSANDRA_KEYSPACE'])
</code></pre>
<p>also works, but still have the same problem with the isolated unit testing.</p>
<p>By reading through this <a href=""https://stackoverflow.com/questions/43554355/why-is-cassandra-hanging-when-i-connect-to-it-via-gunicorn-and-flask"">post</a>, I guess that I'm not having issues with the connection itself as I'm creating one Cassandra session per Flask instance that is spawned by <code>gunicorn</code> <em>post-fork</em>.</p>
<p>Then my question would reduce to which strategy to follow to be able to unit test the endpoints without having to explicitly reach for the database.</p>
",https://stackoverflow.com/questions/46683662/post-fork-connection-to-cassandra-under-gunicorn,"['python', 'python-3.x', 'flask', 'cassandra', 'gunicorn']",1115,TRUE,1,1
What is the use of beforeEach method in Kiwi/Quick test frameworks?,"<p>Why is <code>beforeEach</code> used in test frameworks like Kiwi and Quick?</p>

<pre><code>beforeEach {
            let storyboard = UIStoryboard(name: ""Main"",
                bundle: NSBundle(forClass: self.dynamicType))
            let navigationController = storyboard.instantiateInitialViewController() as UINavigationController
            viewController = navigationController.topViewController as ViewController

            UIApplication.sharedApplication().keyWindow!.rootViewController = navigationController
            let _ = navigationController.view
            let _ = viewController.view
        }
</code></pre>

<p>Example code taken from: <a href=""https://www.natashatherobot.com/unit-testing-in-swift-a-quick-look-at-quick/"" rel=""nofollow noreferrer"">https://www.natashatherobot.com/unit-testing-in-swift-a-quick-look-at-quick/</a> </p>
",https://stackoverflow.com/questions/46928783/what-is-the-use-of-beforeeach-method-in-kiwi-quick-test-frameworks,"['swift', 'unit-testing']",501,TRUE,0,1
How can I get @JsonProperty annotation values specified for Jackson for use in unit tests?,"<p>I've specified <code>@JsonProperty</code> annotations values for deserializing JSON to Android POJOs using Jackson 2.0.</p>

<p>How can I get back the <code>@JsonProperty</code> values for use during unit testing?</p>
",https://stackoverflow.com/questions/44223764/how-can-i-get-jsonproperty-annotation-values-specified-for-jackson-for-use-in-u,"['android', 'jackson']",928,FALSE,-1,1
Does running unit test need to run the Main method in the code to be tested?,"<p>In C#, for unit testing only, do I need to write a Main method in the code to be tested? </p>

<p>I found that without Main method, rebuilding the code to be tested and the testing code will fail. </p>

<p>Is it correct that running unit test doesn't run Main method in the code to be tested? If yes, why does it fail to build without Main method?</p>

<p>Note that I am experimenting inside Visual Studio IDE, and the unit testing uses Visual Studio's unittest library. If without using Visual Studio IDE, will the rebuilding succeed?</p>
",https://stackoverflow.com/questions/41971080/does-running-unit-test-need-to-run-the-main-method-in-the-code-to-be-tested,"['c#', 'visual-studio', 'unit-testing']",1492,TRUE,0,1
Json.net deserialization is returning an empty object,"<p>I'm using the code below for serialization.</p>

<pre><code>var json = JsonConvert.SerializeObject(new { summary = summary });
</code></pre>

<p><code>summary</code> is a custom object of type <code>SplunkDataModel</code>:</p>

<pre><code>public class SplunkDataModel
{
    public SplunkDataModel() {}

    public string Category { get; set; }
    public int FailureCount { get; set; }
    public Dictionary&lt;string, SplunkError&gt; FailureEntity { get; set; }
    public Dictionary&lt;string, string&gt; JobInfo { get; set; }
    public string JobStatus { get; set; }
    public int SuccessCount { get; set; }
    public List&lt;string&gt; SuccessEntity { get; set; }
    public int TotalCount { get; set; }
}
</code></pre>

<p>Serialization results in the JSON below:</p>

<pre><code>{
  ""summary"": {
    ""Category"": ""category"",
    ""JobStatus"": ""Failure"",
    ""JobInfo"": {
      ""Course processing failed"": """" 
    },
    ""TotalCount"": 0,
    ""SuccessCount"": 0,
    ""FailureCount"": 0,
    ""FailureEntity"": {},
    ""SuccessEntity"": []
  }
}
</code></pre>

<p>Now, for unit testing purposes, I need to deserialize it, but the code below is returning an object with empty values.  Where am I going wrong?</p>

<pre><code>var deserialized = JsonConvert.DeserializeObject&lt;SplunkDataModel&gt;(contents);
</code></pre>
",https://stackoverflow.com/questions/43399475/json-net-deserialization-is-returning-an-empty-object,"['c#', 'json', 'json.net']",17567,TRUE,17,2
How to Unit Test a GlassController Action which Uses Sitecore.Context.Item,"<p>I'm a sitecore developer and I want to create a sample sitecore helix unit testing project for testing out the logic you see in our ""ArticleController"" controller's Index() action method:</p>

<pre><code>public class ArticleController : GlassController
{
    public override ActionResult Index()
    {
        // If a redirect has been configured for this Article, then redirect to new location.
        if (Sitecore.Context.Item.Fields[SitecoreFieldIds.WTW_REDIRECT_TO] != null &amp;&amp; !string.IsNullOrEmpty(Sitecore.Context.Item.Fields[SitecoreFieldIds.WTW_REDIRECT_TO].Value))
        {
            var link = (LinkField)Sitecore.Context.Item.Fields[SitecoreFieldIds.WTW_REDIRECT_TO];
            if (link != null)
            {
                if (link.IsInternal)
                {
                    return Redirect(Sitecore.Links.LinkManager.GetItemUrl(link.TargetItem));
                }
                else
                {
                    return Redirect(link.Url);
                }
            }
        }

        var model = new ArticleBusiness().FetchPopulatedModel;

        return View(""~/Views/Article/Article.cshtml"", model);
    }

    //below is alternative code I wrote for mocking and unit testing the logic in above Index() function
    private readonly IArticleBusiness _businessLogic;
    public ArticleController(IArticleBusiness businessLogic)
    {
        _businessLogic = businessLogic;
    }
    public ActionResult Index(int try_businessLogic)
    {
        // How do we replicate the logic in the big if-statement in above ""override ActionResult Index()"" method?

        var model = _businessLogic.FetchPopulatedModel;

        return View(""~/Views/EmailCampaign/EmailArticle.cshtml"", model);
    }
}
</code></pre>

<p>This is what I have in my unit testing class:</p>

<pre><code>[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void Test_ArticleController_With_SitecoreItem()
    {
        //Arrange
        var businessLogicFake = new Mock&lt;IArticleBusiness&gt;();

        var model = new ArticleViewModel()
        {
            ArticleType = ""Newsletter"",
            ShowDownloadButton = true
        };

        businessLogicFake.Setup(x =&gt; x.FetchPopulatedModel).Returns(model);
        //How do I also mock the Sitecore.Context.Item and send it into the constructor, if that's the right approach?

        ArticleController controllerUnderTest = new ArticleController(businessLogicFake.Object);

        //Act
        var result = controllerUnderTest.Index(3) as ViewResult;

        //Assert
        Assert.IsNotNull(result);
        Assert.IsNotNull(result.Model);
    }
}
</code></pre>

<p>Basically I want to mock a Sitecore.Context.Item, which has a ""LinkField"" value (referred to as ""SitecoreFieldIds.WTW_REDIRECT_TO"" above), somehow send it into the controller, and perform the same exact logic as the big if-statement in our original ""public override ActionResult Index()"" method.  </p>

<p>What's the exact code for doing all of this?  Thanks!</p>
",https://stackoverflow.com/questions/46247255/how-to-unit-test-a-glasscontroller-action-which-uses-sitecore-context-item,"['c#', 'moq', 'sitecore8', 'sitecore-mvc', 'glass-mapper']",1330,TRUE,0,2
React.js and Jasmine Spies,"<p>Using basic test-utils and jasmine for unit testing.</p>

<p>How do you spy on a function inside a react component?</p>

<p>test.js:</p>

<pre><code>class Test extends React.Component {
  handleClick() {
    // Do something
  }

  render() {
    return (
      &lt;div className=""test-class"" onClick={this.handleClick}&gt;Test&lt;/div&gt;
    );
  }
}

const React = require('react-with-addons');
const RequireJsTest = require('requirejs-test');
const Utils = React.addons.TestUtils;
const Test = require('./test');

describe('test', () =&gt; {
  it('should test', function() {
    const test = Utils.renderIntoDocument(&lt;Test/&gt;);
    const el = Utils.findRenderedDOMComponentWithClass(test, 'test-class');
    spyOn(test, 'handleClick');
    Utils.Simulate.click(el);

    expect(test.handleClick).toHaveBeenCalled();
  });
});
</code></pre>

<p>I'm getting the following error:</p>

<pre><code>Expected spy handleClick to have been called. (1)
</code></pre>

<p>Any ideas? Thanks!</p>
",https://stackoverflow.com/questions/43687251/react-js-and-jasmine-spies,"['unit-testing', 'reactjs', 'jasmine', 'reactjs-testutils']",1484,TRUE,3,1
Existing constant variables are getting &quot;TypeError: Cannot read property of undefined&quot; error in unit testing,"<p>I have a constant.js file in my Angular project. The existing constant.js variables are getting ""TypeError: Cannot read property of undefined"" error in Jasmine unit testing.</p>
",https://stackoverflow.com/questions/46946873/existing-constant-variables-are-getting-typeerror-cannot-read-property-of-unde,"['angularjs', 'unit-testing']",75,FALSE,0,0
Can we automate a sequence of API calls for functional testing using karate framework?,"<p>I am currently performing unit testing of rest APIs using karate-framework. Can we automate functional test cases through a sequence of different API calls using karate framework?</p>
",https://stackoverflow.com/questions/47950071/can-we-automate-a-sequence-of-api-calls-for-functional-testing-using-karate-fram,"['automation', 'automated-tests', 'cucumber', 'web-api-testing', 'karate']",859,TRUE,2,1
unit testing a component which is injected by a service which is using angular2-jwt AuthHttp call instead of http call,"<p>I have been using HTTP to call API to do my stuff, later introduced angular2-jwt to intercept the http calls and pass the jwt tockens. Unit testing was working fine until AuthHttp was used. I have created 'mockuserdata' model to return the mock values</p>

<p>Every unit test cases where failing until I added the providers for http and AuthHttp as follows</p>

<pre><code>    {provide: Http, useFactory: (backendInstance: MockBackend, defaultOptions: BaseRequestOptions) =&gt; 
    { return new Http(backendInstance, defaultOptions);},
       deps: [MockBackend, BaseRequestOptions] },
 { provide: AuthHttp, useExisting: Http, deps: [Http] }
</code></pre>

<p>After introducing above providers '<strong><em>should instantiate UsersComponent</em></strong>' got passed but '<strong><em>It checks loadUserList() is binding datasource</em></strong>' ís failing</p>

<p>/* User Operations Service*/</p>

<pre><code>import {Headers,RequestOptionsArgs,Response,URLSearchParams, RequestMethod,RequestOptions }from '@angular/http';
import { Injectable, Optional }from '@angular/core';
import { Observable}from 'rxjs/Observable';
import * as models from '../models';
import { AuthHttp }from 'angular2-jwt';
import 'rxjs/Rx';

 @ Injectable()
export class UserOperationsApi {
    protected basePath = '/api';
    public defaultHeaders: Headers = new Headers();
    constructor(protected http: AuthHttp,  @ Optional()basePath: string) {
        if (basePath) {
            this.basePath = basePath;
        }
    }
/**
     * Returns all users
     * Returns list of all users
     */
    public getAllUsers(extraHttpRequestParams ?  : any): Observable &lt; Array &lt; models.User &gt;&gt; {
        const path = this.basePath + '/users';
        let queryParameters = new URLSearchParams();
        let headerParams = this.defaultHeaders;
        let requestOptions: RequestOptionsArgs = {
            method: 'GET',
            headers: headerParams,
            search: queryParameters
        };

        return this.http.request(path, requestOptions)
        .map((response: Response) =&gt; {
            if (response.status === 204) {
                return undefined;
            } else {
                return response.json();
            }
        });
    }
}
</code></pre>

<p>/* User List  Component*/</p>

<pre><code>import {Component,OnInit}from '@angular/core';
import {Router } from '@angular/router';
import {UserOperationsApi }from '../services';
import {DialogService }from '../services';
import { Subscription }from 'rxjs';
 @ Component({
    selector: 'my-app',
    templateUrl: './list-users.component.html',
    providers: [UserOperationsApi]
})
export class UsersComponent implements OnInit {
    public userData: any;
    constructor(private api: UserOperationsApi, private router: Router) {
        this.loadUserList();
    }
    // loading user list
    loadUserList() {
        // To get data from api
        this.busy = this.api.getAllUsers()
            .subscribe(
                data =&gt; this.handleConfiguredUsers(data),
                error =&gt; {
                throw ({
                    message: 'Error occured! while retreiving data from server.'
                });
            });
    }
    // users list to be loaded
    handleConfiguredUsers(data) {
        this.userData = data;
    }
}
</code></pre>

<p>**  * User component unit testing **  **  **</p>

<pre><code>import {async,TestBed,inject}from '@angular/core/testing';
import {Response,ResponseOptions, XHRBackend } from '@angular/http';
import {    MockBackend,    MockConnection}from '@angular/http/testing';
import {    HttpModule}from '@angular/http';
import {    Router, ActivatedRoute}from '@angular/router';
import {    MockRouter}from '../mock/router.mock';
import {    usersData}from '../data/mockData/users';
import {    UsersComponent}from './list-users.component';
describe('list-users.component.ts', () =&gt; {
beforeEach(() =&gt; {
        TestBed.configureTestingModule(
            {
                declarations: [UsersComponent],
                imports: [HttpModule, DevExtremeModule],
                providers: [MockBackend, BaseRequestOptions,
                    { provide: XHRBackend, useClass: MockBackend },
                    { provide: Router, useClass: MockRouter },
                    { provide: ActivatedRoute, useClass: MockRouter },
                    {
                        provide: Http, useFactory: (backendInstance: MockBackend, defaultOptions: BaseRequestOptions) =&gt; {
                            return new Http(backendInstance, defaultOptions);
                        },
                        deps: [MockBackend, BaseRequestOptions]
                    },
                    { provide: AuthHttp, useExisting: Http, deps: [Http] }
                ]
            });
    });

    it('should instantiate UsersComponent', () =&gt; {
        const fixture = TestBed.createComponent(UsersComponent);
        let compInstance: UsersComponent = fixture.componentInstance;
        expect(compInstance instanceof UsersComponent).toBe(true, 'should create UsersComponent');
    });

    it('It checks loadUserList() is binding datasource',
        async(inject([XHRBackend],
                (mockBackend: MockBackend) =&gt; {
                mockBackend.connections.subscribe(
                    (connection: MockConnection) =&gt; {
                    connection.mockRespond(new Response(
                            new ResponseOptions({
                                body: usersData
                            })));
                });

                const fixture = TestBed.createComponent(UsersComponent);
                let instance: UsersComponent = fixture.componentInstance;
                instance.instance.loadUserList();;
                expect(instance.userData.length).toEqual(usersData.length);
                expect(instance.userData).toBe(usersData);
            })));
}
</code></pre>

<p>1) Whats wrong with the unit test which is returning null values.</p>
",https://stackoverflow.com/questions/42691819/unit-testing-a-component-which-is-injected-by-a-service-which-is-using-angular2,"['unit-testing', 'angular', 'typescript', 'angular2-jwt']",731,TRUE,3,1
Best practice for modifiers of constructor in Guice,"<p>Now, I'm reading <a href=""https://github.com/google/guice/wiki/KeepConstructorsHidden"" rel=""nofollow noreferrer"">Guice's official document.</a>  And they say</p>
<blockquote>
<p>As a correction, simply limit the visibility of both your
implementation classes, and their constructors. Typically package
private is preferred for both, as this facilitates:</p>
<p>binding the class within a Module in the same package</p>
<p>unit testing the class through means of direct instantiation</p>
<p>As a simple, mnemonic
remember that public and @Inject are like Elves and Dwarfs: they can
work together, but in an ideal world, they would coexist
independently.</p>
</blockquote>
<p>I know how dangerous <code>public constructor</code> is by reading the document.
And the quoted sentence appears to be the solution, but I am not sure of the exact meaning.
So, could you check whether my thought is right or not.</p>
<p>First, they say <strong>binding the class within a Module in the same package</strong>.
This means for example you have a package in a system.  And it is good to use a <code>Module</code> corresponding with the package?  So, basically you have the same number of <code>Module</code>s and same number of packages?</p>
<p>Second, you can see <strong>unit testing the class through means of direct instantiation</strong>.
This means we should do unit testing a class using direct instantiation, not <code>Guice</code>'s <code>Module</code>?
I think <code>Guice</code> is also useful for a testing, especially unit testing as they said.</p>
<p>I am confused a little bit, could anyone make me clear?</p>
",https://stackoverflow.com/questions/42221990/best-practice-for-modifiers-of-constructor-in-guice,"['java', 'dependency-injection', 'guice']",341,TRUE,0,1
How to mock redux actions with Jest,"<p>I've got a React.Component which use a redux actions <code>this.props.setFacebookToken(accessToken)</code> to set a variable. How would you test this kind of behaviour ?</p>

<p>Here is my Component :</p>

<pre><code>export default class FacebookButtonConnect extends Component {
  constructor(props) {
    ...
  }

  async _onFacebookButtonPress() {
    try {
      ... // fetching credentials from Facebook
      this.props.setFacebookToken(accessToken);
    } catch (err) {
       throw err;
    }
  }
}
</code></pre>

<p>I'm using Jest for unit testing.</p>
",https://stackoverflow.com/questions/43326379/how-to-mock-redux-actions-with-jest,"['javascript', 'reactjs', 'unit-testing', 'redux', 'jestjs']",17816,TRUE,4,1
Which approach is best practice?,"<p>Which One of the Bean definition is best practice and why?</p>

<p>For an example Type 1 can be for Unit testing without creating a context.</p>

<p><strong>Type 1</strong></p>

<pre><code>public class MovieRecommender {

    private final CustomerPreferenceDao customerPreferenceDao;

    @Autowired
    public MovieRecommender(CustomerPreferenceDao customerPreferenceDao) {
        this.customerPreferenceDao = customerPreferenceDao;
    }

    // ...

}
</code></pre>

<p><strong>Type 2</strong></p>

<pre><code>public class MovieRecommender {

    @Autowired
    public CustomerPreferenceDao customerPreferenceDao;


    // ...

}
</code></pre>
",https://stackoverflow.com/questions/46300324/which-approach-is-best-practice,"['java', 'spring', 'dependency-injection']",734,TRUE,2,5
AngularJS - Controller not registered,"<p>I am starting out on AngularJS Unit Testing and I am getting an error like Controller with name ""SiteCtrl"" is not registered.</p>

<p>What I am doing wrong here?</p>

<pre><code>describe('#hasFormError', function () {

    var $rootScope,form, templateHtml, ctrl,$scope,scope;

    angular.module(""TestApp"");
    beforeEach(function () {
        angular.module(""TestApp"");
    });

    beforeEach(inject(function ($rootScope, $controller, $compile, $templateCache) {
        $scope = $rootScope.$new();
        ctrl = $controller;
        ctrl('SiteCtrl', { $scope: scope });

        var a1 = angular.element('&lt;div class=""page_container"" ng-controller=""SiteCtrl""&gt;&lt;form name=""shan""&gt;&lt;div class=""zip""&gt;&lt;input ng-if=""max_length == 5"" type=""text"" name=""zipcode"" value="""" ng-model=""Sitezip.zipcode"" ng-pattern=""/^[0-9]*$/"" ng-maxlength=""max_length"" required&gt;&lt;input ng-if=""max_length == 7"" type=""text"" name=""zipcode"" value="""" ng-model=""store_zip.zipcode"" ng-pattern=""/^[a-zA-Z0-9]*$/"" ng-maxlength=""max_length"" required&gt;&lt;/form&gt;&lt;/div&gt;');


        $compile(a1)($scope);
       form = $scope.shan;  
        $scope.$apply()


    }));


    it(""TestCase :controller  defined \n"", function () {
        expect(ctrl).toBeTruthy();
    }); 

    it(""TestZipCode"", function () {
        form.zipcode.$setViewValue(""4535433123123"");
        expect(form.zipcode.$valid).toBeTruthy();
     });


});
</code></pre>
",https://stackoverflow.com/questions/42918514/angularjs-controller-not-registered,"['angularjs', 'unit-testing', 'jasmine', 'chutzpah']",1389,TRUE,1,1
Trigger clipboard.js on(&#39;success&#39;) or on(&#39;error&#39;) to unit test it,"<p>I am using Jasmine Jquery for my unit testing. I have the following code:</p>

<pre><code>(function() {
  $(document).ready(copyToClipboard);

  function copyToClipboard(){
    var clipboard = new Clipboard('#d_clip');

    clipboard.on('success', function(e) {
      $(e.trigger).text(""Copied!"");
      e.clearSelection();
      setTimeout(function() {
        $(e.trigger).text(""Copy"");
      }, 2500);
    });

    clipboard.on('error', function(e) {
      $(e.trigger).text(""Error copying"");
      setTimeout(function() {
        $(e.trigger).text(""Copy"");
      }, 2500);
    });
  }
})();
</code></pre>

<p>I already tried :</p>

<pre><code>  beforeEach(function() {
    setFixtures(""&lt;button type='button' id='d_clip'&gt;Copy&lt;/button&gt;"")
    clipboard = new Clipboard('#d_clip');
  });

  it('should change text to copied', function() {
    spyOn(clipboard,'on');
    $('#d_clip').trigger('click');
    expect($('#d_clip').text()).toEqual('Copied!')
  });
</code></pre>

<p>But I am getting this error:</p>

<blockquote>
  <p>Expected 'Copy' to equal 'Copied!'.</p>
</blockquote>

<p>It works when I manually click on. It also work when I do <code>$('#d_clip').trigger('click');</code> on Chrome Developer Console.</p>

<p>Looks like clipboard is not doing anything for the unit testing. I can't figure out how to do that.</p>

<p><strong>What I want to test ?</strong></p>

<ol>
<li>I want to trigger click and make sure the text is ""Copied!"" when success and ""Error copying"" when error.</li>
</ol>

<p>This is on Ruby on Rails, so I run JS unit tests as:</p>

<p><code>rake jasmine:ci</code></p>
",https://stackoverflow.com/questions/47782028/trigger-clipboard-js-onsuccess-or-onerror-to-unit-test-it,"['javascript', 'jquery', 'unit-testing', 'jasmine', 'jasmine-jquery']",1694,TRUE,2,1
Test post service jasmine karma angular js,"<p>I new to Unit testing and trying to run the test cases but always getting an error <code>Unexpected request POST service</code>
Below is my code</p>

<p>angular service </p>

<pre><code> angular
    .module('testModule')
    .factory('testService', testService)

  testService.$inject = ['$q', '$http'];

  function testService($q, $http){

    return {
      getAll: function(obj){
        let config = {
          headers : {
            'Content-Type':'application/x-www-form-urlencoded'
          }
        };

        let deferred = $q.defer();
        let payload = 'keyQueryParam=' + obj

        $http.post('url', payload, config.headers).then(response =&gt; {
          deferred.resolve(response.contents)
        })

        return deferred.promise;
      }
    }
  }
</code></pre>

<p>Unit test</p>

<pre><code>describe('Test Service', function(){
    let mockTestFactory, httpBackend;

    beforeEach(function(){
        angular.mock.module('testModule');
    });

    beforeEach(inject(function($httpBackend, _testService_){
        httpBackend = $httpBackend;
        mockTestFactory= _testService_;
    }));

    it('Return a POST response from a Service function', function(){
        var url = ""http://localhost:3000/"";
        var obj = ['ret-2','ret-5','ret-6'];
        let payload = 'keyQueryParam=' + obj

        let config = {
          headers : {
            'Content-Type':'application/x-www-form-urlencoded'
          }
        };

        httpBackend
            .when('POST','url', payload, function(config.headers) {
                expect(config.headers['Content-Type']).toBe('application/x-www-form-urlencoded');
                return config.headers['Content-Type'] === 'application/x-www-form-urlencoded';
            })
            .respond(200, { status : ""success""});

        mockTestFactory.getAll(obj).then(function(response) {
            console.log(response);
        });

        httpBackend.flush();
        expect(true).toBe(true);
    });
});
</code></pre>

<p>thanks in advance</p>
",https://stackoverflow.com/questions/43127302/test-post-service-jasmine-karma-angular-js,"['javascript', 'angularjs', 'unit-testing', 'karma-jasmine']",577,FALSE,0,1
React test with enzyme TypeError: Cannot read property &#39;state&#39; of undefined,"<p>I'm trying to do unit testing to a component using enzyme <strong>shallow rendering</strong>. Trying to test state activeTab of the component and it throws <code>TypeError: Cannot read property state</code>. my component Accordion. Accordion component jsx code</p>

<pre><code> class Accordion extends Component {
    constructor(props) {
        super(props)
        this.state = {
            activeTab: 0
        }
    }

    static defaultProps = {
        tabs: [{title: 'Status'}, {title: 'Movement'}]
    }

    render() {
        const { tabs } = this.props
            , { activeTab } = this.state
        return (
            &lt;div className={`accordion`}&gt;
                {tabs.map((t, i) =&gt; {
                    const activeClass = activeTab === i ? `accordion--tab__active` : ''
                    return(
                        &lt;section key={i} className={`accordion--tab ${activeClass}`}&gt;
                            &lt;header className={`accordion--header`}&gt;
                                &lt;h4 className={`accordion--title`}&gt;
                                    &lt;button onClick={() =&gt; {this._selectAccordion(i)}}&gt;{t.title}&lt;/button&gt;
                                &lt;/h4&gt;
                            &lt;/header&gt;
                            &lt;div className=""accordion--content""&gt;
                                {t.title}
                                Content
                            &lt;/div&gt;
                        &lt;/section&gt;
                    )
                })}
            &lt;/div&gt;
        )
    }
    _selectAccordion = activeTab =&gt; {this.setState({activeTab})}
}

export default Accordion
</code></pre>

<p>and <strong>Accordion.react.test.js</strong></p>

<pre><code>import { shallow } from 'enzyme'
import Accordion from './components/Accordion'

test('Accordion component', () =&gt; {
    const component = shallow(&lt;Accordion name={`Main`}/&gt;)
    expect(component.state('activeTab')).equals(0)
})
</code></pre>
",https://stackoverflow.com/questions/46402943/react-test-with-enzyme-typeerror-cannot-read-property-state-of-undefined,"['javascript', 'reactjs', 'enzyme', 'jestjs']",6108,TRUE,5,2
How to unit test conditional statements in jasmine,"<p>Can any one help me with testing conditional statement within a function in jasmine </p>

<pre><code>vm.onDisciplineCodeChange = function() {
                if ('other' === vm.selectedDisciplineCode) {
                    vm.selectedDiscipline.code = null;
                    vm.selectedDiscipline.userDefined = true;
                } else if('' === vm.selectedDisciplineCode) {
                    vm.selectedDiscipline = {
                        code: null,
                        userDefined: false,
                        userDefinedDiscipline: null
                    }
                } else {
                    vm.selectedDiscipline = {
                        code: vm.selectedDisciplineCode,
                        userDefined: false,
                        userDefinedDiscipline: null
                    }
                }
                vm.onDisciplineUpdated({discipline: vm.selectedDiscipline});
            };
</code></pre>

<p>I'm quite new to unit testing and following is the output i'm getting in generated report.</p>

<p><a href=""https://i.stack.imgur.com/rLTk9.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/rLTk9.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/45049902/how-to-unit-test-conditional-statements-in-jasmine,"['angularjs', 'unit-testing', 'jasmine', 'karma-jasmine']",7240,TRUE,2,1
Test PubsubIO read with local emulator,"<p>I was able to setup <code>TestPipeline</code> and <code>PubsubIO</code> to work with <code>Pubsub</code> emulator:</p>

<pre><code>  options = TestPipeline.testingPipelineOptions().as(PubsubOptions.class);
  options.setPubsubRootUrl(pubsubUrl);
</code></pre>

<p>but the problem is how to bound <code>PubsubIO.readMessages()</code> when unit testing, to actually have a finite test:</p>

<pre><code>  final PCollection&lt;PubsubMessage&gt; pCollection =
      pipeline.apply(PubsubIO.readMessagesWithAttributes().fromTopic(""some-topic""));

  PAssert.that(pCollection).satisfies(pubsubMessages -&gt; {
    pubsubMessages.forEach(System.out::println);
    return null;
  });

  pipeline.run();
</code></pre>

<p>I'm using <code>google-cloud-dataflow-java-sdk-all</code> version <code>2.1.0</code>.</p>
",https://stackoverflow.com/questions/46771653/test-pubsubio-read-with-local-emulator,"['java', 'unit-testing', 'google-cloud-dataflow', 'google-cloud-pubsub']",796,FALSE,1,1
How to test a service that get data from a database using JUnit and Mockito,"<p>i write a java service that get a data from database  :</p>

<pre><code>public List&lt;Operation&gt; listOperations(String code){

//some business logic...

}
</code></pre>

<p>i tested the service manually with the a code from my database <code>listOperations(""CEA1"");</code> and it works fine and it return to me a List with 3 Operation Objects(the same result in my database).</p>

<p>now i want to test my service using Mockito and JUnit but i'm beginner in unit testing (but i know what is the concepts of unit testing,mocking...),</p>

<p>this is my uncompleted test class :</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)
public class MyserviceTest {

    @Mock
    private OperationRepository  operationRepositoryMock;


    @InjectMocks
    private BanqueServiceImpl banqueServiceImpl;

    @Before
    public void setup() {
      MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testListOfOperation(){

        String code = ""CEA1"";

        //to check if my service is working good ,the code 'CEA1' should return a list with 3 Operation object
        when(operationRepositoryMock.listOperations(code)). // i dont know how to mock the result


boolean result = banqueServiceImpl.listOperations(code); // i don't know how to assert that the service return a list that contains 3 Operation object

        //assertTrue(result);
    }
</code></pre>

<p>please can anyone help me to complete my test code , note i'm working in a spring boot project.</p>

<p>Regards!</p>
",https://stackoverflow.com/questions/45826001/how-to-test-a-service-that-get-data-from-a-database-using-junit-and-mockito,"['java', 'spring-boot', 'junit', 'mockito']",6873,TRUE,1,1
how to write test case using rspec of this method,"<p>I want to write test case for below method. I'm new to unit testing. Please let me know the correct way to write test case for below method.</p>

<pre><code>def create_new_user
    self.password_salt = BCrypt::Engine.generate_salt
    self.password_hash = BCrypt::Engine.hash_secret(self.password, password_salt)
    user = User.new(email: self.email, username:self.username, password_hash: password_hash, password_salt: password_salt)
    if user.valid?
      user.save ? {is_created: true, err:''} : {is_created: false, err:'Something went wrong,please try later...'}
    else
      {is_created: false, err: 'Please enter all mandetory fields..'}
    end
  end
</code></pre>
",https://stackoverflow.com/questions/46605817/how-to-write-test-case-using-rspec-of-this-method,"['ruby-on-rails', 'ruby', 'rspec']",171,TRUE,0,1
Java Based Mockito Testing,"<p><a href=""https://i.stack.imgur.com/mAdMb.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/mAdMb.png"" alt=""enter image description here""></a></p>

<p>I am trying to install <strong>mockito QuickFix Tools</strong> for <strong>Eclipse IDE Kepler</strong>.  I am getting this error.I have just started learning the Unit Testing using <code>Mockito</code>.
Thanks in advance.</p>
",https://stackoverflow.com/questions/44601538/java-based-mockito-testing,"['java', 'eclipse', 'eclipse-plugin', 'mockito']",178,FALSE,0,0
Cloud Functions for Firebase - test with real database?,"<p>Cloud Functions for Firebase unit testing docs states that :</p>

<blockquote>
  <p>""If you mock functions.config() with a test app's real Firebase
  configuration values, any writes to the database that your function
  makes actually get executed against the real database. This may be
  useful for debugging. ""</p>
</blockquote>

<p><a href=""https://firebase.google.com/docs/functions/unit-testing#mocking_database_writes"" rel=""nofollow noreferrer"">https://firebase.google.com/docs/functions/unit-testing#mocking_database_writes</a></p>

<ul>
<li>i tried using the real config values in the test sample but the tests failed &amp; no data was written to the database</li>
</ul>

<p>sample code: <a href=""https://github.com/firebase/functions-samples/blob/master/quickstarts/uppercase/functions/test/test.js"" rel=""nofollow noreferrer"">https://github.com/firebase/functions-samples/blob/master/quickstarts/uppercase/functions/test/test.js</a> </p>

<ul>
<li>any idea how to achieve testing on the real database ?</li>
</ul>

<p>Thanks.</p>
",https://stackoverflow.com/questions/43296131/cloud-functions-for-firebase-test-with-real-database,"['unit-testing', 'firebase', 'firebase-realtime-database', 'google-cloud-functions']",666,FALSE,1,1
Android :cannot unit test android functions receiving NPE,"<p>I have just started unit testing in android. I cannot unit test android internal method to notify that data is changed (notifyDataSetChanged)and I am getting null pointer exception on this point. I am using mockito and power moockito to mock different objects.</p>

<pre><code> public void RecyclerView(String value,Bitmap image) {
  RecyclerViewAdapter adapter = new RecyclerViewAdapter(MainActivity.this);
    recyclerView.setAdapter(adapter);// set adapter on recyclerview
    adapter.notifyDataSetChanged();// Notify the adapter

    }
</code></pre>

<p>My unit test is:</p>

<pre><code>@RunWith(PowerMockRunner.class)
@PrepareForTest({MainActivity.class})
public class MainActivityTest {

    @Mock
    Bitmap bitmap;

    @Mock
    RecyclerView recycleview;
    @InjectMocks
    Activity activity;
    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        mainactivity = new MainActivity();

    }

    @Test
    public void PopulateRecyleViewTest() {
        try {
            final RecyclerViewAdapter abc = PowerMockito.mock(RecyclerViewAdapter.class);


            PowerMockito.whenNew(RecyclerViewAdapter.class).withArguments(mainactivity).thenReturn(abc);
            doNothing().when(abc).notifyDataSetChanged(); //do nothing getting exception here
            mainactivity.recyclerView = recycleview;

            mainactivity.PopulateRecyleView("""", bitmap);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
}
</code></pre>

<p>Is there any way to unit test this method so that notifydatasetchanged() do not give NPE(Null Pointer Exception)? I have read that power mockito is used to unit test final method but it does not seem to be unit testing notifyDataSetChanged which is final method. Any help would be appreciated.</p>
",https://stackoverflow.com/questions/44474994/android-cannot-unit-test-android-functions-receiving-npe,"['android', 'unit-testing', 'mockito', 'powermockito']",753,FALSE,1,2
Cannot read property &#39;params&#39; of undefined in angular 2,"<p><strong>We have used route param in our code. But while performing unit testing in jasmine karma we are getting following error.</strong></p>

<pre><code>TypeError: Cannot read property 'params' of undefined
TypeError: Cannot read property 'params' of undefined
    at Object.&lt;anonymous&gt; (http://localhost:9876/base/src/test.ts:38586:20)
    at ZoneDelegate.713.ZoneDelegate.invoke (http://localhost:9876/base/src/polyfills.ts:1599:26)
    at ProxyZoneSpec.onInvoke (http://localhost:9876/base/src/test.ts:82238:39)
    at ZoneDelegate.713.ZoneDelegate.invoke (http://localhost:9876/base/src/polyfills.ts:1598:32)
    at Zone.713.Zone.run (http://localhost:9876/base/src/polyfills.ts:1359:43)
    at Object.&lt;anonymous&gt; (http://localhost:9876/base/src/test.ts:81952:34)
    at attemptSync (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:1950:24)
    at ZoneQueueRunner.QueueRunner.run (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:1938:9)
    at http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:1962:16
    at http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:1905:9
    at http://localhost:9876/base/src/test.ts:14790:17
    at ZoneDelegate.713.ZoneDelegate.invoke (http://localhost:9876/base/src/polyfills.ts:1599:26)
    at AsyncTestZoneSpec.onInvoke (http://localhost:9876/base/src/test.ts:81547:39)
    at ProxyZoneSpec.onInvoke (http://localhost:9876/base/src/test.ts:82235:39)
    at ZoneDelegate.713.ZoneDelegate.invoke (http://localhost:9876/base/src/polyfills.ts:1598:32)
</code></pre>

<p>Please find our ts file below:</p>

<pre><code>import { Component, OnInit, AfterViewInit, EventEmitter, Output } from '@angular/core';

export class MyComponent implements OnInit, AfterViewInit {


    constructor(private route: ActivatedRoute) {

  }

    ngOnInit(){
        this.route.params.subscribe(params =&gt; {
      this.instanceNumber = params['instanceNumber'];
      // console.log(`this.instanceNumber--- QS`, this.instanceNumber);
    });
    }

}
</code></pre>

<p>Please find our spec file below:</p>

<pre><code>import { MyComponent } from './MyComponent.component';
import { DebugElement, NO_ERRORS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ActivatedRoute, Route, ActivatedRouteSnapshot, UrlSegment, Params, Data } from '@angular/router';

describe('MyComponent', () =&gt; {
    let id: string[] = ['123', '456'];
    let component: MyComponent;
    let fixture: ComponentFixture&lt;MyComponent&gt;;


     beforeEach(async(() =&gt; {
        // let route: any = new MockActivatedRoute();
        // route.parent = new MockActivatedRoute();
        // route.parent.params = Observable.of({ id: 'testId' });

        TestBed.configureTestingModule({
            imports: [],
            providers: [{ provide: ActivatedRoute }],
            declarations: [MyComponent],
            schemas: [NO_ERRORS_SCHEMA],
        })
            .compileComponents();
    }));

    beforeEach(() =&gt; {
        fixture = TestBed.createComponent(MyComponent);
        component = fixture.componentInstance;

        this.route.params.subscribe((params) =&gt; {
            this.instanceNumber = params['12345'];
        });
        fixture.detectChanges();
    });

}
</code></pre>
",https://stackoverflow.com/questions/43233641/cannot-read-property-params-of-undefined-in-angular-2,"['unit-testing', 'angular', 'karma-jasmine', 'karma-coverage', 'routeparams']",12860,TRUE,4,2
Logger not working inside AsyncCallback,"<p>I have a problem with logging with GWT Unit testing:</p>

<pre><code>logInfo(""Creating Stuff: "" + stuffAutoBeanSerializer.encodeData(stuff)); // Logging works and showing in the IntelliJ console

myService.createStuff(stuff, new AsyncCallback&lt;Stuff&gt;() {
            @Override
            public void onFailure(Throwable throwable) {
                logSevere(throwable.getMessage()); // Not showing in the console
            }
            @Override
            public void onSuccess(Stuff stuff) {
                logInfo(""Created Stuff: "" + stuffAutoBeanSerializer.encodeData(stuff)); // not showing in the console
            }
});
</code></pre>

<p>Even though the request is an <code>onSuccess</code> since data is stored in the database. What could be the problem here?</p>
",https://stackoverflow.com/questions/43394849/logger-not-working-inside-asynccallback,"['gwt', 'junit']",20,TRUE,0,1
"How do I properly unit test a repository-pattern method, that has coupling to Entity Framework / DbContext?","<p>I'm new to unit testing and wish to write an application that is N-tier, so my ORM is abstracted away from BLL with a repository-pattern inbetween. How would I go about unit testing a repository-pattern method that has coupling to EF (DbContext)?</p>

<p><strong>My SUT method is here:</strong></p>

<pre><code>public IList&lt;Volunteer&gt; GetAllVolunteers() {
    return dbctx.Volunteer.ToList();
}
</code></pre>

<p><strong>My unit test so far:</strong></p>

<pre><code>[Fact]
public void GetAllVolunteersMethodWorks() {
    // Arrange
    var fakeVolunteer = new Volunteer { Id = 0, Name = ""Dummy"" };
    var expected = new List&lt;Volunteer&gt;(new Volunteer[] { fakeVolunteer });

    var mockedCtxVolunteer = new Mock&lt;DbSet&lt;Volunteer&gt;&gt;();
    mockedCtxVolunteer.Setup(m =&gt; m.ToList()).Returns(expected);

    var mockedctx = new Mock&lt;RSMContext&gt;();
    mockedctx.Setup(m =&gt; m.Volunteer).Returns(mockedCtxVolunteer.Object);

    // Act
    var volunteerRepo = new VolunteerRepository(mockedctx.Object);
    var result = volunteerRepo.GetAllVolunteers();

    // Assert
    Assert.Equal(expected, result);
}
</code></pre>

<p>I get an error that System.NotSupportedException: 'Expression references a method that does not belong to the mocked object: m => m.ToList() 
So how do I properly mock the DbSet so my fake data resides there to properly test my VolunteerRepository.GetAllVolunteers() method works?</p>

<p><strong>edit (solution):</strong> </p>

<pre><code>var mockedDbCtxVolunteer = new Mock&lt;DbSet&lt;Volunteer&gt;&gt;();
mockedDbCtxVolunteer.As&lt;IQueryable&lt;Volunteer&gt;&gt;().Setup(m =&gt; m.GetEnumerator()).Returns(expected.GetEnumerator());
</code></pre>
",https://stackoverflow.com/questions/42906752/how-do-i-properly-unit-test-a-repository-pattern-method-that-has-coupling-to-en,"['c#', 'entity-framework', 'unit-testing', 'moq']",1619,TRUE,0,2
Replacing new lines with &quot;\n&quot; and have it be unit testable?,"<p>I have a block of code which looks like this : </p>

<pre><code> String myJsonString = mapper.writeValueAsString(object).replaceAll(""(\\r|\\n|\\r\\n)+"", ""\\\\n"") + ""\n"";
</code></pre>

<p>Now, that code lives inside a ""callable"" block - and as such, is useless when it comes to unit testing.</p>

<p>I know I could do something along the lines of pulling the regex into a Pattern class... and then matching against it that way - but I wanted to get some input regarding the best practice here - I don't have as much unit testing under my belt as I would like to have, and I know there are always better ways to do these things.</p>

<p>The actual block of code, for better reference</p>

<pre><code>    Callable&lt;Boolean&gt; doStuff = new Callable&lt;Boolean&gt;() {
        public Boolean call() throws Exception {
            String json = mapper.writeValueAsString(object).replaceAll(""(\\r|\\n|\\r\\n)+"", ""\\\\n"") + ""\n"";
            // TODO : Add functionality which adds this string to a list.
            return true;
        }
    };
</code></pre>
",https://stackoverflow.com/questions/46534218/replacing-new-lines-with-n-and-have-it-be-unit-testable,"['java', 'unit-testing', 'junit']",65,TRUE,0,1
Where does Selenium gets its data to test the units?,"<p>When using Selenium where is the data generated for unit testing? </p>

<p>Could it use the same database instance of the project it is working on or new database should be created?</p>
",https://stackoverflow.com/questions/45368770/where-does-selenium-gets-its-data-to-test-the-units,"['database', 'selenium']",142,TRUE,1,2
Mock data for client calling to spring web service,"<p>I need to get mock data for client calling to spring restful web services. I know unit testing purpose we can use mock. but my case is not the testing.</p>
",https://stackoverflow.com/questions/46276104/mock-data-for-client-calling-to-spring-web-service,"['java', 'web-services', 'spring-mvc', 'restful-architecture', 'spring-web']",51,FALSE,0,1
Cannot find contract attachment for Cash when using NodeDriver,"<p>I just started using Corda. I know that in unit testing, I'm supposed to add the line</p>

<pre><code>setCordappPackages(""net.corda.finance"")
</code></pre>

<p>But when I debug using NodeDriver, I just receive the message. </p>

<pre><code>net.corda.core.transactions.MissingContractAttachments: Cannot find contract attachments for [net.corda.finance.contracts.asset.Cash]
</code></pre>

<p>What's missing?</p>
",https://stackoverflow.com/questions/47264863/cannot-find-contract-attachment-for-cash-when-using-nodedriver,['corda'],967,TRUE,0,1
Unit test for text parser,"<p>I'm new at unit testing and I try to test my parser:</p>

<pre><code>public static List&lt;tranche&gt; Parse22(string record)
{
    List &lt;tranche&gt; Tranche = new List&lt;tranche&gt;();
    foreach (var i in record)
    {
        var ts = new tranche();
        ts.dealer_name = line.Substring(2, 5);
        ts.invoice = line.Substring(7, 7);
        ts.amount = Decimal.Parse(line.Substring(14, 13));
        ts.vin = line.Substring(46, 17);
        ts.model = line.Substring(63, 4);
        ts.registration = line.Substring(72, 10);
        ts.brutto = Decimal.Parse(line.Substring(95, 13));
        Tranche.Add(ts);
    }
    return Tranche;
}
</code></pre>

<p>I want to test dealer_name and VIN are correct. But I don't understand what should be at ""Assert.""</p>

<pre><code>[TestClass]
public class ParserTest
{
    [TestMethod]
    public void Parse_LineStarts22_ReturnsVINandDealerNameCorrect()
    {
        string record = testString;
        var res = myParser.Parse22(record);

        Assert.AreEqual() //???
    }
}
</code></pre>
",https://stackoverflow.com/questions/45632298/unit-test-for-text-parser,"['c#', 'unit-testing', 'parsing', 'testing']",306,TRUE,0,1
Karma Unit test does not works well for the component function?,"<p>This is my component function </p>

<pre><code> this.cocmenuitems=[];
  LoadMenus() {
        this.cocmenuitems.push({ label: 'Search'});
    }
</code></pre>

<p>Unit testing method </p>

<pre><code>   beforeEach(() =&gt; {
        this.modalNota = new AppComponent();
    });
   it('Should test LoadMenus method', () =&gt; {
        this.modalNota.LoadMenus();//component method executed well
        alert(12);// but this alert does not fire and the result is shown failed status
        expect(this.modalNota.cocmenuitems[0].label).toBe('Search');
    });
</code></pre>

<p>This <code>this.modalNota.LoadMenus()</code> execution is working good, because <code>this.cocmenuitems</code> having value while am check it in console window. But the next line <code>alert(12)</code> does not executed. Why?</p>
",https://stackoverflow.com/questions/43799151/karma-unit-test-does-not-works-well-for-the-component-function,"['angular', 'unit-testing', 'typescript', 'karma-runner', 'karma-jasmine']",39,FALSE,0,0
What do unit tests not test?,"<p>I was asked this in an interview, I have always read about what unit tests do, but what do they not do?</p>

<p><a href=""https://stackoverflow.com/questions/67299/is-unit-testing-worth-the-effort"">Is Unit Testing worth the effort?</a></p>

<p>Any insights? Thanks!</p>
",https://stackoverflow.com/questions/45609645/what-do-unit-tests-not-test,"['java', 'c++', 'unit-testing']",80,TRUE,-4,1
Ambiguous occurrence ‘stdout’,"<p>I've been trying to put on unit testing via <code>doctest</code>. Getting error:</p>

<pre><code>hs-procr-0.1.0.0: test (suite: hs-procr-test)

Progress: 1/2
&lt;interactive&gt;:5:14: error:
Ambiguous occurrence ‘stdout’
It could refer to either ‘Turtle.stdout’,
                         imported from ‘Turtle’ at app/Main.hs:7:1-13
                         (and originally defined in ‘Turtle.Prelude’)
                      or ‘System.IO.stdout’,
                         imported from ‘System.IO’
                         (and originally defined in ‘GHC.IO.Handle.FD’)
</code></pre>

<p>I've got no idea why; all my <code>*.hs</code> files got</p>

<pre><code>import System.IO hiding (FilePath, stdout, stderr)
</code></pre>

<p><code>package.yaml</code>:</p>

<pre><code>...
tests:
  hs-procr-test:
    main:                Spec.hs
    source-dirs:         test
    ghc-options:
    - -threaded
    - -rtsopts
    - -with-rtsopts=-N
    dependencies:
    - hs-procr
</code></pre>

<p><code>Spec.hs</code>:</p>

<pre><code>module Main (main) where

import Test.DocTest
import System.IO hiding (FilePath, stdout, stderr)

main :: IO ()
main = doctest [ ""app/Main.hs""
               ]
</code></pre>

<p>I use <code>stack</code>, there is no *.cabal file. What have I missed?</p>

<p><code>Main.hs</code>:</p>

<pre><code>{-# LANGUAGE OverloadedStrings #-}
module Main ( main
            , strStripNumbers
            ) where

import Lib
import Turtle
import Prelude hiding (FilePath)
import System.IO hiding (FilePath, stdout, stderr)
import Text.Regex.TDFA
...
</code></pre>
",https://stackoverflow.com/questions/47730105/ambiguous-occurrence-stdout,"['haskell', 'testing', 'haskell-stack', 'ambiguous', 'doctest']",121,FALSE,0,0
ReferenceError: window is not defined. I got this error when I run npm test to unit testing by jest,"<p>ReferenceError: window is not defined. I got this error when I run npm test to unit testing by jest. Error come from following code export function. Any one met this type of error and solved it?</p>

<pre><code>import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
import thunk from 'redux-thunk';

import rootReducer from '../modules/rootReducer';

    export function injectAsyncReducers(asyncReducers) {
  const injectReducers = Object.keys(asyncReducers).reduce((all, item) =&gt; {
    if (store.asyncReducers[item]) {
      delete all[item];
    }

    return all;
  }, asyncReducers);

  store.asyncReducers = Object.assign({}, store.asyncReducers, injectReducers);
  replaceReducers(rootReducer);
}
</code></pre>
",https://stackoverflow.com/questions/47407101/referenceerror-window-is-not-defined-i-got-this-error-when-i-run-npm-test-to-u,"['reactjs', 'react-native', 'react-redux', 'jestjs']",8534,TRUE,4,2
Mock HttpClient using Moq,"<p>I would like to unit test a class that uses <code>HttpClient</code>. We injected the <code>HttpClient</code> object in the class constructor.</p>
<pre><code>public class ClassA : IClassA
{
    private readonly HttpClient _httpClient;

    public ClassA(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task&lt;HttpResponseMessage&gt; SendRequest(SomeObject someObject)
    {
        //Do some stuff

        var request = new HttpRequestMessage(HttpMethod.Post, &quot;http://some-domain.in&quot;);

        //Build the request

        var response = await _httpClient.SendAsync(request);

        return response;
    }
}
</code></pre>
<p>Now we would like to unit test the <code>ClassA.SendRequest</code> method. We are using <code>Ms Test</code> for unit testing framework and <code>Moq</code> for mocking.</p>
<p>When we tried to mock the <code>HttpClient</code>, it throws <code>NotSupportedException</code>.</p>
<pre><code>[TestMethod]
public async Task SendRequestAsync_Test()
{
    var mockHttpClient = new Mock&lt;HttpClient&gt;();

    mockHttpClient.Setup(
        m =&gt; m.SendAsync(It.IsAny&lt;HttpRequestMessage&gt;()))
    .Returns(() =&gt; Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));
}
</code></pre>
<p>How can we solve this issue?</p>
",https://stackoverflow.com/questions/44715602/mock-httpclient-using-moq,"['c#', 'unit-testing', 'moq', 'mstest', 'dotnet-httpclient']",33878,TRUE,16,4
Mockito. How to return a boolean value based on mocked object as parameter?,"<pre><code>Class A
{
public B makeB(int q)
    {
        return new B(q);
    }
    public boolean evaluate(int q)
    {
        B b = makeB(q);
        boolean result = b.get();
        return result;
    }
}

Class B
{
    int e;
    public B(int w)
    {
        e=w;
    }
    public boolean get()
    {
        //return boolean based on object B
    } 
}

Class ATest
{
    A a = spy(A.class);
    B b1 = mock(B.class);
    B b2 = mock(B.class);

    doReturn(b1).when(a).makeB(5);
    doReturn(b2).when(a).makeB(10);

    when(b1.get()).thenReturn(true);
    when(b2.get()).thenReturn(false);

    a.evaluate();
}
</code></pre>

<p>=======================</p>

<p>Here I would like to return true from method evaluate when object B contains value 5 and false if it contains value 10.</p>

<p>Class B is from an external Library.</p>

<p>New to unit testing and mockito.</p>
",https://stackoverflow.com/questions/46083732/mockito-how-to-return-a-boolean-value-based-on-mocked-object-as-parameter,"['java', 'spring-boot', 'junit', 'mockito']",20756,TRUE,3,3
Unit test then build project? Or? What order for Java,"<p>I have to make some Java classes within a package using Netbeans.
I have a question about the order I am supposed to do the following tasks:
We are supposed to create unit tests, Javadoc things, and build the project (to make a JAR file that contains our class library). We will need to clean and build the project when we make changes.
Can I start unit testing and documenting my code now before I have explicitly built the project? Or do I need to run the build first to pull things all together and then start unit testing and document with JavaDoc?
Thank you for any help! Googling and searching here was getting me no where.</p>
",https://stackoverflow.com/questions/42099553/unit-test-then-build-project-or-what-order-for-java,"['java', 'unit-testing', 'building']",3841,FALSE,4,2
Mock testing dependency injection object reference,"<p>First time to create unit testing using mock. I'm having problem as I'm having error on object reference.</p>

<pre><code>Mock&lt;IAccount&gt; mock = new Mock&lt;IAccount&gt;();
var testController = new AccountController(mock.Object);

IActionResult result = testController.Withdraw(1,100,""sample"");
Assert.IsInstanceOfType(result, typeof(RedirectToActionResult));
</code></pre>

<p>under my <code>AccountController</code> class on deposit method</p>

<pre><code>var _account = _Iaccount.GetAccountById(id);
if (_account.Password != password)
{
    ModelState.AddModelError(""Password"", ""Invalid Password!"");
}
</code></pre>

<p>having error on <code>_Iaccount</code> as it was on the constructor.</p>

<p>thanks!</p>
",https://stackoverflow.com/questions/44667229/mock-testing-dependency-injection-object-reference,"['c#', 'unit-testing', 'mocking', 'visual-studio-2017']",3091,TRUE,1,1
How do I test the function call made by the method to other methods,"<p>I am using Karma and jasmine for unit testing. How do I test the function call made by the method to other methods? Do I use Spies in jasmine?</p>

<p><strong>Ticket.controller.controller.js</strong></p>

<pre><code>function hello()
 {
    test();
    test1();
}
</code></pre>

<p><strong>Ticketcontroller.controller.test.js(test file)</strong></p>

<pre><code>describe('checks hello',function(){

 beforeEach(inject(_$controller_){
  var controller=_$controller_;
    };

 it('the spec',function(){

   spyOn(controller,'test')l
   expect(controller.test).toHaveBeenCalled();

    })
})
</code></pre>
",https://stackoverflow.com/questions/42344093/how-do-i-test-the-function-call-made-by-the-method-to-other-methods,"['angularjs', 'unit-testing', 'karma-jasmine']",43,FALSE,0,1
How to rename a unit test suite in Xcode 8,"<p>I created the test suite using:</p>

<ol>
<li><p>File -> New -> Target.</p></li>
<li><p>Select ""iOS Unit Testing Bundle""</p></li>
</ol>

<p>The test suite is named CalculatorTest3, and I would like to rename it to CalculatorTest. What's the easiest way to do this?</p>
",https://stackoverflow.com/questions/44691598/how-to-rename-a-unit-test-suite-in-xcode-8,"['ios', 'swift', 'xcode']",1252,TRUE,2,2
Angular 2 Unit Test for IF condition,"<p>I am new to unit testing. I am trying to unit test the if condition for the code below:</p>

<pre><code>hide() {
        this.count --;
        if (this.count === 0) {
            this.loaderIs = false;
        }
    }
</code></pre>

<p>I am trying to use spy function on <code>loaderIs</code> variable.</p>

<pre><code>it('hide function check', () =&gt; {
        expect(loaderService.hide).toBeDefined();
        spyOn(loaderService, 'loaderIs');
        loaderService.hide();
        expect(loaderService.loaderIs).toHaveBeenCalled();
    });
</code></pre>

<p>Any input and guides are highly appreciated.</p>
",https://stackoverflow.com/questions/45500826/angular-2-unit-test-for-if-condition,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",14879,TRUE,1,1
js-cookie enzyme testing fails on testing cookie.set function,"<p>I am trying to unit test js-cookie
My code is like this</p>

<pre><code>import Cookie from 'js-cookie'

onChange (e) {
    Cookie.set('locale', e.target.value)
    window.location.reload()
  }
</code></pre>

<p>and for unit testing I am doing this</p>

<pre><code>describe('LocaleDropDown', () =&gt; {
  const handleLocaleChange = sinon.spy()
  const Cookie = sinon.spy(Cookie,'set')

  it(""when simulating a change, Cookie.set should be called"", () =&gt; {
    const wrapper = shallow(&lt;LocaleDropDown onChange = {handleLocaleChange}/&gt;)
    wrapper.find('select').simulate('change', { target: { value: 'en'}})
    expect(Cookie.set.calledOnce).toBe(true)
  });
</code></pre>

<p>})</p>

<p>It fails saying ReferenceError: Cookie is not defined</p>

<p>How should I be testing js-cookie</p>
",https://stackoverflow.com/questions/47821058/js-cookie-enzyme-testing-fails-on-testing-cookie-set-function,"['reactjs', 'js-cookie']",1702,TRUE,2,1
Hook function call in node.js,"<p>is there a way to hook function call or redefine a function before a call in node.js? I need this for unit testing, may be Proxy or some testing libary is and option?</p>

<p>Example:</p>

<pre><code>//some js file
function a(){
 b()// need to be hooked
} 

function b(){
  //do some stuff
}
</code></pre>
",https://stackoverflow.com/questions/42906601/hook-function-call-in-node-js,"['javascript', 'node.js', 'unit-testing', 'ecmascript-6']",1570,FALSE,0,2
Karma Jasmine testing inject not working,"<p>I am new to karma unit testing and I have encountered this problem to a simple Ionic Application. </p>

<p>This is my controller:</p>

<pre><code>  angular.module('starter').controller('AccountCtrl', function ($scope) {

    $scope.settings = {
      enableFriends: true
    };

    $scope.dummyFunction = function () {
      console.log(""Just do nothing!"");
    }
  });
</code></pre>

<p>This is my unit testing file:</p>

<pre><code>describe('AccountCtrl', function () {
  var scope, createController;
  beforeEach(module('starter'));
  console.log(""0"");

  beforeEach(function () {
    console.log(""1"");
  })

  beforeEach(inject(function ($rootScope, $controller) {
    console.log(""2"");
    scope = $rootScope.$new();
    controller = $controller('AccountCtrl', {
      '$scope': scope
    });
  }));

  it('should do stuff', function () {
    console.log(""3"");
    expect(""Hello!"").toBeDefined();
  });

});
</code></pre>

<p>At this point, when I run the test I get this:</p>

<pre><code>PhantomJS 2.1.1 (Mac OS X 0.0.0) LOG: 'WARNING: Tried to load angular more than once.'

PhantomJS 2.1.1 (Mac OS X 0.0.0) LOG: '0'

LOG: '1'
LOG: '3'
PhantomJS 2.1.1 (Mac OS X 0.0.0) AccountCtrl should do stuff FAILED
    forEach@/Users/eduard.lache/Documents/dummyProjects/unitTestingAPP/www/lib/ionic/js/ionic.bundle.js:13696:24
    loadModules@/Users/eduard.lache/Documents/dummyProjects/unitTestingAPP/www/lib/ionic/js/ionic.bundle.js:17883:12
    createInjector@/Users/eduard.lache/Documents/dummyProjects/unitTestingAPP/www/lib/ionic/js/ionic.bundle.js:17805:30
    workFn@/Users/eduard.lache/Documents/dummyProjects/unitTestingAPP/www/lib/angular-mocks/angular-mocks.js:2353:60
    /Users/eduard.lache/Documents/dummyProjects/unitTestingAPP/www/lib/ionic/js/ionic.bundle.js:17923:53
PhantomJS 2.1.1 (Mac OS X 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.004 secs / 0.011 secs)
</code></pre>

<p>As you can see from the console.log messages, the inject function is not getting called and the problem is that I don't know why is that and why is this making my test fail as the test expects the string ""Hello!"" to be defined, which it is.</p>

<p>If I remove the beforeEach that contains the injection the test is successfull.</p>

<p>My goal is to make a test that verifies that $scope.dummyFunction() has been called and that $scope.settings is defined.
i.e.:</p>

<pre><code>  it('should do stuff', function () {
    var ctrl = controller();
    ctrl.dummyFunction();
    expect(ctrl.dummyFunction).toHaveBeenCalled();
    expect(ctrl.settings).toBeDefined();    
});
</code></pre>
",https://stackoverflow.com/questions/43591239/karma-jasmine-testing-inject-not-working,"['unit-testing', 'angular', 'ionic-framework', 'karma-jasmine', 'inject']",1120,FALSE,3,1
Avoid run part of code when use Unit test,"<p>I want that don't execute part of my code when I run the app for Unit testing, the problem is one my functions is save one object in BD and I want avoid this.</p>

<pre><code>api.getUsers(completion:{(objects)
//In this response I save the object in BD
})
</code></pre>
",https://stackoverflow.com/questions/47514664/avoid-run-part-of-code-when-use-unit-test,"['ios', 'swift', 'xcode', 'unit-testing', 'xctest']",592,FALSE,0,3
How to start all files of unit tests from one file using Rspec?,"<p>I have written unit testing of models of a Ruby on Rails app. I have tested all the spec files individually. Now I want to start all files from one file. Kindly guide me.</p>
",https://stackoverflow.com/questions/44242008/how-to-start-all-files-of-unit-tests-from-one-file-using-rspec,"['ruby-on-rails', 'rspec']",35,TRUE,-1,1
Failed to resolve: org.roboelectric:roboelectric:3.2.2,"<p>I am learning unit testing for my android apps. I am using <code>roboelectric</code> framework to achieve this. </p>

<p>build.gradle</p>

<pre><code>apply plugin: 'com.android.application'
apply plugin: 'realm-android'

android {
    compileSdkVersion 25
    buildToolsVersion ""25.0.2""
    defaultConfig {
        applicationId ""com.xyz.helloworld""
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName ""1.0""
        testInstrumentationRunner ""android.support.test.runner.AndroidJUnitRunner""
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    dataBinding {
        enabled = true
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.1'
    testCompile 'junit:junit:4.12'
    testCompile 'org.robolectric:robolectric:3.2.2'
}
</code></pre>

<p>I am getting an error <code>Failed to resolve: org.roboelectric:roboelectric:3.2.2</code> &amp; synced with Gradle multiple times.</p>

<p><a href=""https://i.stack.imgur.com/AelyW.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/AelyW.png"" alt=""enter image description here""></a>
How can I resolve this issue? Thanks in advance</p>
",https://stackoverflow.com/questions/42408898/failed-to-resolve-org-roboelectricroboelectric3-2-2,"['android', 'robolectric']",897,TRUE,2,1
"TypeError: jit__object_Object_38 is not a constructor, NgRedux, Angular 2","<p>Please forgive me just trying on things in Unit testing in Angular 2. This weird error comes on executing <code>npm run test</code>. Might be a small mistake, but unabel to figure out with this weird error:</p>

<pre><code>import { TestBed, async, inject } from '@angular/core/testing';
import { TestModule } from '../../test/test.module';
import { DevExtremeModule } from 'devextreme-angular';
import { RouterTestingModule } from '@angular/router/testing';
import { HttpModule, XHRBackend, RequestOptions } from '@angular/http';
import { Templates } from './templates.component';
import { CommandButton } from '../../common/tool/command-button.component';
import { NgReduxModule, NgRedux } from '@angular-redux/store/lib';
import { MockBackend } from ""@angular/http/testing/mock_backend"";
import { HttpService } from ""../../services/http.service"";
import { AppState } from '../../redux/index';


// Mock out the NgRedux class with just enough to test what we want.
class MockRedux extends NgRedux&lt;AppState&gt; {
  constructor(private state: AppState) {
    super(null);
  }
  dispatch = () =&gt; undefined;
  getState = () =&gt; this.state;
}


describe('Component : Templates', () =&gt; {

  let fixture;
  let mockRedux: NgRedux&lt;AppState&gt;;
  let mockState : AppState = {
    session : { token: '', user: { firstName : 'Test User' }, isError: null }
  };

  beforeEach(done =&gt; {
    mockRedux = new MockRedux(mockState);

    const configure = (testBed: TestBed) =&gt; {
      testBed.configureTestingModule({
        imports: [ TestModule, DevExtremeModule, 
            RouterTestingModule, HttpModule ],
        declarations : [ Templates ],
        providers: [
          { provide: XHRBackend, useClass: MockBackend },
          {
            provide: HttpService,
            useFactory: (backend: XHRBackend, options: RequestOptions, redux: NgRedux&lt;AppState&gt; ) =&gt; {
              return new HttpService(backend, options, mockRedux );
            },
            deps: [XHRBackend, RequestOptions]
          },
          { provide: NgRedux, useClass : mockRedux }
        ]
      });
    };

    TestModule.configureTests(configure).then(testBed =&gt; {
      fixture = testBed.createComponent(RegTemplates);
      fixture.detectChanges();
      done();
    });

  });

  it('should instantiate Templates Component', async(inject([], () =&gt; {
    fixture.whenStable().then(() =&gt; {
      fixture.autoDetectChanges();
      expect(fixture.componentInstance).toBeDefined();
    });
  })));

  // To do 
});
</code></pre>

<p>Error says:</p>

<pre><code>TypeError: jit__object_Object_38 is not a constructor
</code></pre>

<p><a href=""https://i.stack.imgur.com/ndqvA.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ndqvA.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/46461324/typeerror-jit-object-object-38-is-not-a-constructor-ngredux-angular-2,"['angular', 'unit-testing', 'compiler-errors', 'angular-redux']",263,TRUE,0,1
How can I extract the regular expression from a RegularExpressionAttribute?,"<p>I have a class like </p>

<pre><code>public class Foo
{
    [RegularExpression(@""([A-Za-z0-9\-_ ]+){1,100}"")]
    public string Bar { get; set; }
}
</code></pre>

<p>and for the purpose of unit testing I want to be able to extract out the <code>""@""([A-Za-z0-9\-_ ]+){1,100}""</code>.</p>

<p>I know it's something like </p>

<pre><code>string expr = typeof(Foo).GetProperty(""Bar"").....
</code></pre>

<p>but I don't quite know how to finish it.</p>
",https://stackoverflow.com/questions/42285848/how-can-i-extract-the-regular-expression-from-a-regularexpressionattribute,"['c#', '.net', 'unit-testing', 'reflection', 'custom-attributes']",190,TRUE,0,1
karma init there is no file matching pattern *Spec.ts,"<p>I try to config unit test in Ionic 2 app,
I follow <a href=""http://lathonez.github.io/2017/ionic-2-unit-testing/"" rel=""nofollow noreferrer"">http://lathonez.github.io/2017/ionic-2-unit-testing/</a></p>

<p>when I try to lunch my unit test with karma</p>

<pre><code>karma init karma.conf.js
</code></pre>

<p>and follow the steps, I have error: <code>There is no file matching this pattern</code>
Pattern : *spec.ts</p>
",https://stackoverflow.com/questions/41939422/karma-init-there-is-no-file-matching-pattern-spec-ts,"['unit-testing', 'typescript', 'ionic2', 'karma-jasmine']",325,FALSE,2,0
Default url and credentials for H2DB?,"<p>I have added H2DB in my springBoot application for unit testing purpose.</p>

<p>In application-test.properties I just added:</p>

<p>spring.datasource.name = h2db</p>

<p>spring.h2.console.enabled = true</p>

<p>Its working fine, saving the values.</p>

<p>But how it is working and how can I browse this DB?</p>
",https://stackoverflow.com/questions/45925770/default-url-and-credentials-for-h2db,"['spring-boot', 'spring-data-jpa', 'h2', 'h2db']",7871,TRUE,4,1
how to test handler.postDelayed with mockito?,"<p>I am new to unit testing and I am stuck with testing following method:</p>

<pre><code>    fun freeze(view: View) {
        view.isClickable = false
        handler.postDelayed({
             view.isClickable = true
        }, CLICK_TIMEOUT)
    }
</code></pre>

<p>Here is what I am already have:</p>

<pre><code>    @Test
    fun freeze() {
        var view = mock&lt;View&gt;()
        viewUtil.freeze(view)
        assertFalse(view.isClickable)
    }
</code></pre>

<p>But now I need to test that view will be clickable after <code>CLICK_TIMEOUT</code>.</p>

<p>How can I implement this kind of test?</p>
",https://stackoverflow.com/questions/43866430/how-to-test-handler-postdelayed-with-mockito,"['android', 'unit-testing', 'mockito']",11737,TRUE,4,4
How to initialise the nested structure in go?,"<p>My structure is like this</p>

<pre><code>type A struct{
        B struct{
           C interface{} `json:""c""`
     }
}
type C struct{
        D  string  `json:""d""`
        E  string  `json:""e""`
}
</code></pre>

<p>use of this struct is like this way,</p>

<pre><code>func someFunc(){
  var x A
  anotherFunc(&amp;x)
}

func anotherFunc(obj interface{}){
// resp.Body has this {D: ""123"", E: ""xyx""} 
 return json.NewDecoder(resp.Body).Decode(obj)
}
</code></pre>

<p>and i have to initialise it for the unit testing and i am doing this,</p>

<pre><code>x := &amp;A{
        B: {
             C : map[string]interface{}{
                 D: 123,
                 E: xyx,
             },
        },
} 
</code></pre>

<p>but getting error <code>missing type in composite literal</code>, what am i doing wrong?</p>
",https://stackoverflow.com/questions/45508189/how-to-initialise-the-nested-structure-in-go,"['go', 'struct', 'nested']",390,FALSE,-2,1
How to mock GSSManager correctly?,"<p>I want to mock GSSManager for unit testing using Powermock. It failed when I did mockStatic(GSSManager.class) because of this error:</p>

<pre><code>java.lang.VerifyError: Bad return type
Exception Details:
  Location:
    org/ietf/jgss/GSSManager.getInstance()Lorg/ietf/jgss/GSSManager; @157: areturn
  Reason:
    Type 'sun/security/jgss/GSSManagerImpl' (current frame, stack[0]) is not assignable to 'org/ietf/jgss/GSSManager' (from method signature)
  Current Frame:
    bci: @157
    flags: { }
    locals: { 'java/lang/Object', null, 'sun/security/jgss/GSSManagerImpl', 'java/lang/Object' }
    stack: { 'sun/security/jgss/GSSManagerImpl' }
</code></pre>

<p>I cant understand why. The getInstance in GSSManager return new GSSManagerImpl</p>

<p>I think it might be linkage error:</p>

<pre><code>java.lang.LinkageError: loader constraint violation: when resolving overridden method ""sun.security.jgss.GSSManagerImpl$$EnhancerByCGLIB$$3bcb7afc.getMechs()[Lorg/ietf/jgss/Oid;"" the class loader (instance of org/powermock/core/classloader/MockClassLoader) of the current class, sun/security/jgss/GSSManagerImpl$$EnhancerByCGLIB$$3bcb7afc, and its superclass loader (instance of &lt;bootloader&gt;), have different Class objects for the type [Lorg/ietf/jgss/Oid; used in the signature
</code></pre>
",https://stackoverflow.com/questions/45649905/how-to-mock-gssmanager-correctly,"['java', 'kerberos', 'powermock', 'gssapi', 'jgss']",292,FALSE,3,0
Call a endpoint which return a HashMap with RestTemplate,"<p>I have a endpoint with the below signature </p>

<pre><code>@RequestMapping(method = RequestMethod.GET, value = ""/{id}"", produces = {""application/json; charset=UTF-8""})
@Transactional(readOnly = true)
@ResponseBody
public HashMap&lt;String, Object&gt; myMethod(@PathVariable(""id"") Long id) {...}` 
</code></pre>

<p>And I want to make a call with RestTemplate for unit testing. How I can do that because in method <code>getForObject</code> I can't put a collection as a responseType.</p>

<p>Any ideea?</p>
",https://stackoverflow.com/questions/45171185/call-a-endpoint-which-return-a-hashmap-with-resttemplate,"['java', 'spring', 'resttemplate', 'endpoint']",11720,TRUE,2,2
Live Unit testing is not working &quot;Failed to initialize client proxy: could not connect to test process.&quot;,"<p>When Trying to activate live unit testing on VS 2017 I get this error:</p>

<pre><code> [TestRunner 1] Failed to initialize client proxy: could not connect to test process.
FatalError - System.AggregateException: One or more errors occurred. ---&gt; Microsoft.VisualStudio.TestPlatform.ObjectModel.TestPlatformException: Failed to initialize client proxy: could not connect to test process.
   at Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Client.ProxyOperationManager.SetupChannel(IEnumerable`1 sources)
   at Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Client.ProxyExecutionManager.InitializeExtensions(IEnumerable`1 sources)
   at Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Client.ProxyExecutionManager.StartTestRun(TestRunCriteria testRunCriteria, ITestRunEventsHandler eventHandler)
</code></pre>

<p>Other similar solutions to this error say it might be permissions so I've already tried running VS2017 as administrator, but that didn't work. and other solutions say tat I need to run the test in a different way but this is for live unit testing so I don't think they a viable options. I've even created a new unit test project from the one that already existed but I still get this error.</p>

<p>Update:
The Tests are located in a MsTest V2 test project running on a VS2017 enterprise Edition and it is testing an MVC webpage project under .Net framework 4.5.2 using Git version controls.</p>
",https://stackoverflow.com/questions/46549676/live-unit-testing-is-not-working-failed-to-initialize-client-proxy-could-not-c,"['unit-testing', 'visual-studio-2017', 'live-unit-tests']",597,TRUE,5,1
When Unit Testing HostingEnvironment.MapPath() is fails beacuse of mappath expecting a file should reside on that path,"<p>I'm using  HostingEnvironment.MapPath() on my webapplication get the path of the location to save the file. I used MockHost for populate fake values in Unit testing. When running on visual studio or IIS it works fine. But when running unit test HostingEnvironment.MapPath() fails when that map path does not have a file. But it works fine if that location has a file. Could some one tell me how to run unit test successfully HostingEnvironment.MapPath() without a file reside in MapPath location.</p>

<p>///Code///           </p>

<pre><code>public static Tuple&lt;string, string GetFilePathForSave(SampleVWModel model, int uploadId)             
{             
    if (model == null)            
    {                  
         return null;                
    }               
    ConfigurationDto configurationDto = new ConfigurationDto();                    
    configurationDto = facade.RetrieveConfiguration();                
    var fileName = string.Format(""[{0}]-{1}"", uploadId.ToString(),Path.GetFileName(model.Uplodedfile.FileName));                       
    var path=HostingEnvironment.MapPath(configurationDto.UploadFolderPath + fileName);                        
    var tuple = new Tuple&lt;string, string&gt;(fileName, path);                      
    return tuple;                        
}     
</code></pre>

<p>///UnitTest Code///                      </p>

<pre><code>[TestMethod()]  
public void GetFilePathForSaveTest()               
{                                  
    string path = new DirectoryInfo(Environment.CurrentDirectory).Parent.Parent.Parent.FullName + ""\\MainApplication"";      
    MockHost host = new MockHost(path, ""/"");              
    host.Setup();                           
    SampleVWModel vwModel= new SampleVWModel ();                       
    vwModel.FilePath = path + @""\App_Data\Uploads\excelDoc.xlsx"";                   
    var uploadedFile = new Mock&lt;HttpPostedFileBase&gt;();                    
    uploadedFile.Setup(x =&gt; x.ContentLength).Returns(30);                             
    uploadedFile.Setup(x =&gt; x.ContentType).Returns(""application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"");                               
    uploadedFile.Setup(x =&gt; x.FileName).Returns(""excelDoc.xlsx"");                     
    vwModel.Uplodedfile = uploadedFile.Object;                                  

    Tuple&lt;string, string&gt; result = Helper.GetFilePathForSave(vwModel, 1014);
    Assert.AreEqual(""[1014]-excelDoc.xlsx"", result.Item1);
}
</code></pre>

<p>As in the code UploadFile will save after getting the path from GetFilePathForSave is normal behavior. But when doing the unit testing HostingEnvironment.MapPath() is failing because mappath does not have the file.</p>
",https://stackoverflow.com/questions/46647333/when-unit-testing-hostingenvironment-mappath-is-fails-beacuse-of-mappath-expec,"['c#', 'asp.net-mvc', 'unit-testing', 'visual-studio-2015', 'filepath']",1525,FALSE,1,0
XmlSerializer Issue In Unit Test,"<p>So I'm having an issue that I haven't been able to find a resolution to after searching the internet. The main issue is that when I'm creating a <code>XmlSerializer</code> using a custom defined type it fails with no reason why. This only occurs in the unit test I've created that calls this function. In the application where it is being used the code executes as intended and all is well in the world. Below is some code snippets that show what is going on.</p>

<pre><code>public class ClassA
{
    [XmlAttribute]
    public string Id { get; set; }

    public ClassA()
    {
        Id = string.Empty;
    }
}

public class ClassB
{
    [XmlAttribute]
    public string Id { get; set; }

    public ClassB()
    {
        Id = string.Empty;
    }
}

public class SerializeClass
{
    [XmlElement]
    public string RandomString { get; set; }

    [XmlArray]
    public List&lt;ClassA&gt; ClassAs { get; set; }
    [XmlArray]
    public List&lt;ClassB&gt; ClassBs { get; set; }

    [XmlIgnore]
    public Int32 Count { get; set; }

    public SerializeClass()
    {
        RandomString = string.Empty;
        ClassAs = new List&lt;ClassA&gt;();
        ClassBs = new List&lt;ClassB&gt;();
        Count = 0;
    }
}


public class XmlReaderClass
{
    private SerializeClass _serializeClass;

    public async Task&lt;bool&gt; Initialize()
    {
        bool loaded = false;

        // If the rules are empty create and load them.
        if (_rules == null)
        {
            _rules = new Rules();

            StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(""ms-appx:///FileToReadIn.xml""));
            Stream stream = await file.OpenStreamForReadAsync();

            XmlSerializer serializer = new XmlSerializer(typeof(SerializeClass));
            XDocument document = XDocument.Load(stream);
            _serializeClass = (serializer.Deserialize(document.CreateReader()) as SerializeClass);

            loaded = true;
        }
        else
        {
            loaded = true;
        }

        return loaded;
    }
}
</code></pre>

<p>So only when unit testing does the Initialize function fail on the line with </p>

<pre><code>XmlSerializer serializer = new XmlSerializer(typeof(SerializeClass));.
</code></pre>

<p>I need to read in this XML to perform unit testing on functionality related to the data in the XML file.</p>
",https://stackoverflow.com/questions/45738932/xmlserializer-issue-in-unit-test,"['c#', 'xml', 'serialization', 'uwp']",651,TRUE,1,1
Out of memory exception while running mocha test case in nodejs,"<p>For unit testing I am using <code>mocha</code> &amp; recently I am observing <code>out of memory exception</code> while running test case</p>

<pre><code>--- Last few GCs ---&gt;

  548213 ms: Scavenge 1365.3 (1457.7) -&gt; 1365.3 (1457.7) MB, 1.2 / 0 ms (+ 1.5 ms in 2 steps since last GC) [allocation failure] [incremental marking delaying mark-sweep].
  549442 ms: Mark-sweep 1365.3 (1457.7) -&gt; 1364.3 (1457.7) MB, 1228.6 / 0 ms (+ 2.8 ms in 4 steps since start of marking, biggest step 1.2 ms) [last resort gc].
  550603 ms: Mark-sweep 1364.3 (1457.7) -&gt; 1309.1 (1457.7) MB, 1161.4 / 0 ms [last resort gc].


&lt;--- JS stacktrace ---&gt;

==== JS stack trace =========================================

Security context: 0x30d0b01e3ac1 &lt;JS Object&gt;
    2: _compile [module.js:~380] [pc=0x333b9a368f36] (this=0x29e81578a591 &lt;a Module with map 0x364941617b89&gt;,content=0x4ec389e5fd1 &lt;Very long string[26212]&gt;,filename=0x31a758c32891 &lt;String[92]: /Users/pulkit.sharva/apps/code/node_modules/bluebird/js/release/debuggability.js&gt;)
    3: .js [module.js:~420] [pc=0x333b9869e18b] (this=0x1b3ffe7cfcc9 &lt;an Object with map 0x364941655fb9&gt;,mod...

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory
sh: line 1: 38263 Abort trap: 6           NODE_ENV=test istanbul cover _mocha -- --timeout 3000 -R spec --recursive test
</code></pre>

<p>is there anyway/tool through which I can determine which test case is causing this since I can see my heap size is increasing rapidly</p>

<pre><code>code pulkit.sharva$ node --expose-gc
        &gt; process.memoryUsage();
        { rss: 21069824, heapTotal: 9587488, heapUsed: 4520544 }
        &gt; process.memoryUsage();
        { rss: 22892544, heapTotal: 9587488, heapUsed: 5407376 }
        &gt; process.memoryUsage();
        { rss: 23261184, heapTotal: 10619424, heapUsed: 5785296 }
        &gt; process.memoryUsage();
        { rss: 23560192, heapTotal: 10619424, heapUsed: 6075440 }
        &gt; process.memoryUsage();
        { rss: 23642112, heapTotal: 10619424, heapUsed: 6158888 }
        &gt; process.memoryUsage();
        { rss: 23715840, heapTotal: 10619424, heapUsed: 6231968 }
</code></pre>
",https://stackoverflow.com/questions/41979010/out-of-memory-exception-while-running-mocha-test-case-in-nodejs,"['node.js', 'unit-testing', 'out-of-memory', 'mocha.js']",2100,TRUE,3,2
How to add unit tests in Eclipse for a managed ARM C project?,"<p>I've got a managed Eclipse project that uses the GNU ARM Embedded Toolchain to compile for an ST microcontroller. What I want to do now is, unit test the code in that project. The framework I want to use for unit testing is Google Test.</p>

<p>I tried creating a second Eclipse project for the unit tests, that uses the standard GNU toolchain. Like this:</p>

<p>Project1 (ARM)<br>
|---src   </p>

<p>Project2 (Desktop)<br>
|---test  </p>

<p>The problem with that is twofold:</p>

<ol>
<li>The second project doesn't have access to the source code of the first project (obviously). Therefore I tried creating a static library from the first project for testing purposes, which leads to the second problem.</li>
<li>The Library created from the first project isn't compatible with the second project, because it uses the GNU ARM embedded toolchain instead of the standard GNU toolchain.</li>
</ol>

<p>To solve the second problem I added a build configuration to the first project to try and compile it with the right toolchain. That didn't work out though.</p>

<p>Another path I went was to have the unit tests in the same project as the actual code and use a build configuration to create an executable for unit testing. Something like this:</p>

<p>Project<br>
|---src<br>
|---test  </p>

<p>That didn't work out as well and it kind of seems like it's the same problem as with the first approach anyway.</p>

<p>The problem isn't unit testing in itself. I know how to use Google Test for testing regular C projects in eclipse.</p>

<p>How is unit testing an embedded project usually approached with managed projects in eclipse? Is it possible at all? If so, is it a good way to do it or should I write my own makefile to accompilsh this task?</p>
",https://stackoverflow.com/questions/41808176/how-to-add-unit-tests-in-eclipse-for-a-managed-arm-c-project,"['c', 'eclipse', 'unit-testing', 'embedded']",1204,TRUE,5,1
ASP.NET Core unit test authorization,"<p>I try to create unit testing my authorization logic, but have problem for testing</p>

<pre><code>  await this.HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme)));
</code></pre>

<p>I have error</p>

<blockquote>
  <p>No authentication handler is configured to handle the scheme: Cookies</p>
</blockquote>

<p>Because he need CookieAuthenticationOptions</p>

<p>But how configuration for unit test I don't know</p>

<pre><code>    private static Mock&lt;SignInManager&lt;User&gt;&gt; GetSignInManagerMock(Mock&lt;UserManager&lt;User&gt;&gt; userManagerMock)
    {
        var context = new Mock&lt;HttpContext&gt;();
        var contextAccessor = new Mock&lt;IHttpContextAccessor&gt;();
        contextAccessor.Setup(x =&gt; x.HttpContext).Returns(context.Object);

        return new Mock&lt;SignInManager&lt;User&gt;&gt;(userManagerMock.Object,
            contextAccessor.Object,
            new Mock&lt;IUserClaimsPrincipalFactory&lt;User&gt;&gt;().Object,
            new Mock&lt;IOptions&lt;IdentityOptions&gt;&gt;().Object,
            new Mock&lt;ILogger&lt;SignInManager&lt;User&gt;&gt;&gt;().Object);
    }

    private static Mock&lt;UserManager&lt;User&gt;&gt; GetUserManagerMock()
    {
        return new Mock&lt;UserManager&lt;User&gt;&gt;(new Mock&lt;IUserStore&lt;User&gt;&gt;().Object,
            new Mock&lt;IOptions&lt;IdentityOptions&gt;&gt;().Object,
            new Mock&lt;IPasswordHasher&lt;User&gt;&gt;().Object,
            new IUserValidator&lt;User&gt;[0],
            new IPasswordValidator&lt;User&gt;[0],
            new Mock&lt;ILookupNormalizer&gt;().Object,
            new Mock&lt;IdentityErrorDescriber&gt;().Object,
            new Mock&lt;IServiceProvider&gt;().Object,
            new Mock&lt;ILogger&lt;UserManager&lt;User&gt;&gt;&gt;().Object);
    }

    [Fact]
    public async void Login_Corect_input_login_password_should_return_ok()
    {
        var stamp = Guid.NewGuid().ToString();
        var user = new User
        {
            UserName = _fakeUserModel.UserName,
            Email = _fakeUserModel.Email,
            FirtName = _fakeUserModel.FirstName,
            LastName = _fakeUserModel.LastName,
            UserPicture = _fakeUserModel.UserPicture,
            ConcurrencyStamp = stamp
        };

        var userManagerMock = GetUserManagerMock();
        userManagerMock.Setup(s =&gt; s.FindByNameAsync(FakeData.UserName)).ReturnsAsync(user);

        userManagerMock.Setup(s =&gt; s.GetRolesAsync(user)).ReturnsAsync(FakeData.Roles);

        var signInManagerMock = GetSignInManagerMock(userManagerMock);
        signInManagerMock.Setup(
                s =&gt;
                    s.PasswordSignInAsync(_fakeCorrectloginModel.UserName, _fakeCorrectloginModel.Password, false,
                        false))
            .ReturnsAsync(Microsoft.AspNetCore.Identity.SignInResult.Success);

        var controller = ControllerFactory.CreateFakeController&lt;UserController&gt;(false, userManagerMock.Object,
            signInManagerMock.Object);
        var response = await controller.Login(_fakeCorrectloginModel);
        var result = Assert.IsType&lt;JsonResult&gt;(response);
        var getModel = Assert.IsType&lt;UserViewModel&gt;(result.Value);

        Assert.Equal(_fakeUserModel, getModel);
    }



public static class ControllerFactory
    {
        public static T CreateFakeController&lt;T&gt;(bool isLoggedIn, params object[] arg) where T : Controller
        {
            var fakePrincipal = GetPrincipalMock(isLoggedIn).Object;

            var fakeActionContext = new ActionContext
            {
                HttpContext = new DefaultHttpContext
                {
                    User = fakePrincipal
                },
                ActionDescriptor = new ControllerActionDescriptor(),
                RouteData = new RouteData()
            };

            var controller = (T)Activator.CreateInstance(typeof(T), arg);
            controller.ControllerContext = new ControllerContext(fakeActionContext);

            return controller;
        }

        public static Mock&lt;ClaimsPrincipal&gt; GetPrincipalMock(bool isLoggedIn)
        {
            var principalMock = new Mock&lt;ClaimsPrincipal&gt;();
            principalMock.Setup(sg =&gt; sg.Identity).Returns(GetIdentityMock(isLoggedIn).Object);
            principalMock.Setup(s =&gt; s.IsInRole(It.IsAny&lt;string&gt;())).Returns(false);
            principalMock.Setup(s =&gt; s.Claims).Returns(new List&lt;Claim&gt;
            {
                GetClaim(HelpClaimTypes.Language, ""ua"")
            });
            return principalMock;
        }

        public static Mock&lt;ClaimsIdentity&gt; GetIdentityMock(bool isLoggedIn)
        {
            var identityMock = new Mock&lt;ClaimsIdentity&gt;();
            identityMock.Setup(sg =&gt; sg.AuthenticationType).Returns(isLoggedIn ? FakeData.AuthenticationType : null);
            identityMock.Setup(sg =&gt; sg.IsAuthenticated).Returns(isLoggedIn);
            identityMock.Setup(sg =&gt; sg.Name).Returns(isLoggedIn ? FakeData.UserName : null);
            return identityMock;
        }

        public static ClaimsIdentity GetClaimsIdentity(params Claim[] claims)
        {
            var identityMock = new ClaimsIdentity(claims);
            return identityMock;
        }

        public static Claim GetClaim(string type, string value)
        {
            return new Claim(type, value);
        }
    }
</code></pre>
",https://stackoverflow.com/questions/41731067/asp-net-core-unit-test-authorization,"['unit-testing', 'asp.net-core', 'authorization']",1160,FALSE,3,0
Python mocking global variable declared in another function,"<p>I am unit-testing a function which uses variable declared by other function.</p>

<pre><code>def first_fun():
   global file_path
   file_path = get_file_path()
   .
   .

def second_fun():
   with open(file_path, ""r"") as flz:
   .
   .
</code></pre>

<p>How do I mock file_path while testing second_fun()?
I tried this but doesn't work.</p>

<pre><code>   @patch.object(source_module, 'file_path')
   def test_second_fun(self):
          source_module.second_fun()
</code></pre>

<blockquote>
  <p>I keep on getting ... does not have the attribute 'file_path'</p>
</blockquote>
",https://stackoverflow.com/questions/46603616/python-mocking-global-variable-declared-in-another-function,"['python', 'unit-testing', 'mocking']",193,FALSE,0,1
Writing a JUnit test to check SharedPreferences data,"<p>I am new to unit testing in Android and my attempt is to <code>assertTrue</code> that the data is successfully passed to a method and saved in <code>SharedPreferences</code>. This is my test so far:</p>

<pre><code>public class AuthTest {

    Authorization authorization = new Authorization();

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void test_IfAuthIsSaved() {
        //test if the auth object is saved in the auth object is saved as a.. 
        //..json string in Shared preferences
        Auth auth = mock(Auth.class);
        authorization.saveAuth(auth);

        //test if the auth is received and saved to sharedpreferences
    }

}
</code></pre>

<p><strong>saveAuth method:</strong></p>

<pre><code>public void saveAuth(Auth auth) {
    editor.putString(""USER_AUTH"", new Gson().toJson(auth));
    editor.commit();
}
</code></pre>

<p>What would the assertion look like for this?</p>
",https://stackoverflow.com/questions/46485606/writing-a-junit-test-to-check-sharedpreferences-data,"['java', 'android', 'unit-testing', 'junit', 'mockito']",4961,TRUE,3,3
karma unit test running issue Error $injector:modulerr failed to instantiate module,"<p>I'm new to angularJS unit testing and I have added a new unit test but I'm running into this issue: </p>

<pre><code>Error: [$injector:modulerr] Failed to instantiate module FeeBuddy due to:
Error: [$injector:modulerr] Failed to instantiate module ngMaterial due to:
Error: [$injector:nomod] Module 'ngMaterial' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
</code></pre>

<p>this is my <code>karma.conf.js</code> file dependecies call : </p>

<pre><code>files: [
      'node_modules/angular/angular.js',
      'node_modules/angular-mocks/angular-mocks.js',
      'node_modules/angular-ui-router/release/angular-ui-router.js',
      //'node_modules/angular-material/angular-material.js',
      'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.js',
      'public/js/vendor/materialPreloader.min.js',
      'js/server.config.js',
      'js/main.controller.js',
      'js/controllers/*.js',
      'js/services/*.js',
      'js/directives/*.js',
      'js/factories/*.js',
      'js/components/*.js',
      'js/modules/**/*.js',
      'js/routes.js',
      'js/modules.js',
      'js/module.js',
      'js/filters/*.js',
      'js/modules/**/module.js',
      'js/dependecies.js',
      'test/unit/*.js'
    ],
</code></pre>

<p>Even if I uncomment the <code>node_modules/angular-material/angular-material.js</code> still i have the same issue</p>
",https://stackoverflow.com/questions/45065553/karma-unit-test-running-issue-error-injectormodulerr-failed-to-instantiate-mod,"['angularjs', 'unit-testing', 'karma-runner', 'karma-jasmine']",258,FALSE,0,0
ReferenceError: ok is not defined at QUnitAsserter.assertTrue in Kotlin Javascript,"<p>Kotlin versions 1.0.x-1.1.0 support out of the box unit testing with <a href=""http://qunitjs.com/"" rel=""nofollow noreferrer"">QUnit</a> but when I load tests it throws this exception:</p>

<pre><code>ReferenceError: ok is not defined
    at QUnitAsserter.assertTrue_4mavae$ (file:///D:/neoranga/Mis%20documentos/GitHub/FibonacciCounter/app/build/classes/test/lib/kotlin-test-js.js:50:5)
    at assertTrue (file:///D:/neoranga/Mis%20documentos/GitHub/FibonacciCounter/app/build/classes/test/lib/kotlin-test-js.js:93:27)
    at QUnitAsserter.assertTrue_o10pc4$ (file:///D:/neoranga/Mis%20documentos/GitHub/FibonacciCounter/app/build/classes/test/lib/kotlin-test-js.js:47:5)
    at QUnitAsserter.Asserter.assertEquals_lzc6tz$ (file:///D:/neoranga/Mis%20documentos/GitHub/FibonacciCounter/app/build/classes/test/lib/kotlin-test-js.js:182:10)
    at assertEquals (file:///D:/neoranga/Mis%20documentos/GitHub/FibonacciCounter/app/build/classes/test/lib/kotlin-test-js.js:108:20)
    at AppTest.myFirstTest (file:///D:/neoranga/Mis%20documentos/GitHub/FibonacciCounter/app/build/classes/test/app_test.js:17:5)
    at Object.&lt;anonymous&gt; (file:///D:/neoranga/Mis%20documentos/GitHub/FibonacciCounter/app/build/classes/test/app_test.js:29:21)
</code></pre>

<p>This is my test class:</p>

<pre class=""lang-java prettyprint-override""><code>import org.junit.Test
import kotlin.test.assertEquals

class AppTest {

    @Test fun myFirstTest() {
        assertEquals(1, 1, ""Test in test folder works"")
    }
}
</code></pre>

<p>This is the html code that loads the test:</p>

<pre><code>&lt;!doctype html&gt;
&lt;html lang=""en""&gt;
    &lt;head&gt;
        &lt;meta charset=""utf-8""&gt;
        &lt;title&gt;Fibonacci Counter&lt;/title&gt;
        &lt;link rel=""stylesheet"" href=""css/app.css""&gt;
        &lt;meta name=""viewport"" content=""width=device-width""&gt;
        &lt;link rel=""stylesheet"" href=""https://code.jquery.com/qunit/qunit-2.1.1.css""&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;div id=""qunit""&gt;&lt;/div&gt;
        &lt;div id=""qunit-fixture""&gt;&lt;/div&gt;
        &lt;footer id=""info""&gt;
            &lt;p&gt;Placeholder&lt;/p&gt;
        &lt;/footer&gt;
        &lt;span id=""text""&gt;&lt;/span&gt;
        &lt;script src=""external_libs/jquery-3.1.1.min.js""&gt;&lt;/script&gt;
        &lt;script src=""https://code.jquery.com/qunit/qunit-2.1.1.js""&gt;&lt;/script&gt;
        &lt;script src=""lib/kotlin.js""&gt;&lt;/script&gt;
        &lt;script src=""lib/kotlin-test-js.js""&gt;&lt;/script&gt;
        &lt;script src=""app_main.js""&gt;&lt;/script&gt;
        &lt;script src=""app_test.js""&gt;&lt;/script&gt;
    &lt;/body&gt;
&lt;/html&gt;
</code></pre>
",https://stackoverflow.com/questions/42538010/referenceerror-ok-is-not-defined-at-qunitasserter-asserttrue-in-kotlin-javascri,"['javascript', 'unit-testing', 'kotlin']",281,TRUE,0,1
Retrolambda doesn&#39;t apply to a test build of an Android app,"<p>I have found that my android project isn't transformed by Retrolambda if it compiled to unit testing purposes.</p>

<p>Any submodule transformed correcty instead of the root application.</p>

<p>How can I force a RL trnsformations for a test purposes?</p>
",https://stackoverflow.com/questions/44749591/retrolambda-doesnt-apply-to-a-test-build-of-an-android-app,"['android', 'unit-testing', 'gradle', 'retrolambda']",35,FALSE,1,0
"jest: Test suite failed to run, TypeError: Cannot read property &#39;bind&#39; of undefined","<p>we were using jest from unit testing in react-native. It was working well.
We just deleted npm and installed it again and then when we tried to run unit test(npm test) we are getting following error and we are not able to run test cases.</p>

<p><a href=""https://i.stack.imgur.com/iWcES.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/iWcES.png"" alt=""enter image description here""></a></p>

<p>What might have went wrong. </p>
",https://stackoverflow.com/questions/42692575/jest-test-suite-failed-to-run-typeerror-cannot-read-property-bind-of-undefi,"['react-native', 'jestjs', 'babel-jest']",25320,TRUE,13,7
How do you access the in-memory neo4j driver using the JavaScript implementation?,"<p>The neo4j Java driver has access to an in-memory driver that's handy for unit testing. For example, see <a href=""https://github.com/neo4j-contrib/neo4j-jdbc/blob/master/neo4j-jdbc-bolt/src/test/java/org/neo4j/jdbc/bolt/SampleIT.java"" rel=""nofollow noreferrer"">here</a> and <a href=""https://stackoverflow.com/questions/37628313/neo4j-unit-testing-the-bolt-driver-properly#37640278"">here</a>. Does the official JavaScript driver have a similar tool? If so, how is it accessed?</p>
",https://stackoverflow.com/questions/41537879/how-do-you-access-the-in-memory-neo4j-driver-using-the-javascript-implementation,"['javascript', 'neo4j']",323,TRUE,0,1
How to use Spring WithMockUser annotation with TestNG,"<p>I am using Spring Boot for my web app and TestNG for unit testing. Following is the unit test I'm trying</p>

<pre><code>@ContextConfiguration
public class AuthorizerTest extends AbstractTestNGSpringContextTests {

    @InjectMocks
    private Authorizer authorizer = new Authorizer();

    @Mock
    private PermissionRuleRepository permissionRuleRepository;

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

    @Test
    @WithMockUser
    public void testCheckPermission() throws Exception {
        try {
            authorizer.checkPermission(null, PermissionLevel.Type.ACCOUNT_OTHER);
            fail();
        } catch (AccessDeniedException ade) {
            //
        }
    }
}
</code></pre>

<p><code>authorizer.checkPermission</code> internally using <code>SecurityContext</code> to get the current username. But on debugging, the <code>authentication</code> object is <code>null</code>. Not sure why it is not getting populated when using <code>WithMockUser</code>.</p>
",https://stackoverflow.com/questions/44126701/how-to-use-spring-withmockuser-annotation-with-testng,"['spring', 'mockito', 'testng', 'spring-test', 'springmockito']",388,TRUE,6,1
Jest - Unexpected token import,"<p>I'm trying to learn how to do unit testing with React and jest. I've run into the following error:</p>

<blockquote>
  <p>Unexpected token import</p>
</blockquote>

<p>Here are my babel presets:</p>

<pre><code>{
  ""presets"": [""es2015"", ""stage-0"", ""react""],  
  ""env"": {
    ""test"": {
        ""plugins"": [""transform-es2015-modules-commonjs""]
    }
}
}
</code></pre>

<p>Here is the file i'm trying to test:</p>

<pre><code>import jest from 'jest';
import React from 'react'; 
import { shallow } from 'enzyme';
import Step from '../src/components/step.js';

const wrapper = shallow(&lt;Step /&gt;);
wrapper.find('a').simulate('click', { preventDefault() {} });
</code></pre>

<p>and here is my package.json:</p>

<pre><code>{
  ""name"": ""react-simple-boilerplate"",
  ""version"": ""1.0.0"",
  ""description"": ""Simple and lightweight Boilerplate for ReactJS projects"",
  ""scripts"": {
    ""lint"": ""eslint src"",
    ""start"": ""node server.js"",
    ""test"": ""jest""
  },
  ""devDependencies"": {
    ""babel-core"": ""^6.24.1"",
    ""babel-loader"": ""^7.0.0"",
    ""babel-plugin-transform-es2015-modules-commonjs"": ""^6.26.0"",
    ""babel-preset-es2015"": ""^6.24.1"",
    ""babel-preset-react"": ""^6.24.1"",
    ""babel-preset-stage-0"": ""^6.24.1"",
    ""css-loader"": ""^0.28.0"",
    ""enzyme"": ""^3.2.0"",
    ""enzyme-adapter-react-16"": ""^1.1.0"",
    ""eslint"": ""^3.19.0"",
    ""eslint-plugin-react"": ""^6.10.3"",
    ""jest"": ""^21.2.1"",
    ""node-sass"": ""^4.5.2"",
    ""react-addons-test-utils"": ""^15.6.2"",
    ""sass-loader"": ""^6.0.3"",
    ""style-loader"": ""^0.16.1"",
    ""webpack"": ""^2.4.1"",
    ""webpack-dev-server"": ""^2.4.4""
  },
  ""dependencies"": {
    ""babel-loader"": ""^7.0.0"",
    ""react"": ""^15.5.4"",
    ""react-dom"": ""^15.5.4""
  },
  ""main"": ""server.js""
}
</code></pre>

<p>Have no idea why its giving me this message?</p>
",https://stackoverflow.com/questions/47721091/jest-unexpected-token-import,"['javascript', 'reactjs', 'jestjs']",9965,TRUE,9,2
How to test a PrivateObject in a .net standard test project?,"<p>I am following this tutorial, <a href=""https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-with-mstest"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-with-mstest</a></p>

<p>but I don't have the type PrivateObject available, so I am wondering if it would be possible to test private objects with a .net standard 2.0 project.</p>
",https://stackoverflow.com/questions/44673817/how-to-test-a-privateobject-in-a-net-standard-test-project,"['c#', 'unit-testing', 'mstest', '.net-standard']",1778,TRUE,4,2
grails PagedResultList wrong ordering in UnitTest,"<p>the following controller action return posts in the expected order (decreasing by id) when running the application:</p>

<pre><code>def list() {
   PagedResultList posts = Post.createCriteria().list(max: 5, offset: params.offset) {
    if (params.searchTag) {
            tag {
                eq (""name"", params.searchTag)
            }
        }
        order(""id"", ""desc"")
    }
    [posts: posts, total: posts.totalCount]
}
</code></pre>

<p>But the unit testing test fails because posts are not returned in the expected order:</p>

<pre><code>def “list returns the posts in the correct order”(){
    given:
    def p1 = new Post(title: 'p1', email: 'aaa@aaa.com', content: 'xx').save()
    def p2 = new Post(title: 'p2', email: 'aaa@aaa.com', content: 'xx').save()

    when:
    def model = controller.list()

    then:
    p2.id &gt; p1.id
    model.posts.iterator().next().title == 'p2' //fails: expected p2 got p1
}
</code></pre>

<p>Any reason why the test fails?</p>
",https://stackoverflow.com/questions/43334510/grails-pagedresultlist-wrong-ordering-in-unittest,['grails'],25,FALSE,0,0
Unit test of angularfirestore service,"<p>How would I write unit test for a service using AngularFirestore?</p>

<p>Currently I have the following: </p>

<pre><code>import { AngularFirestore } from 'angularfire2/firestore';
export class AngularFireStoreStub extends AngularFirestore {}

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      providers: [ DataModelService,
        { provide: AngularFirestore, useClass: AngularFireStoreStub },
    ]
    });
  });

  it('should be created', inject([DataModelService], (service: DataModelService) =&gt; {
    expect(service).toBeTruthy();
  }));
});
</code></pre>

<p>However this gives me the following error in Jasmine: </p>

<pre><code>Error: Can't resolve all parameters for AngularFireStoreStub: ([object Object], ?).
</code></pre>

<p>Since I am relatively new to angular unit testing, this don't help me a lot.</p>
",https://stackoverflow.com/questions/47713514/unit-test-of-angularfirestore-service,"['angular', 'angularfire2']",386,FALSE,2,0
Mockito &amp; PowerMock - class size limitations,"<p>To mock data for my unit testing, I am using Mockito. But I see the below exception. Am I missing any setup?</p>

<p>JVM used here is Java HotSpot(TM) 64-Bit Server VM. 1.8</p>

<pre><code>public class TestCreateObj{

  public void getMockData() {       
    TestObj deal = mock(TestObj.class);
    when(deal.getDescription()).thenReturn(""HURRAH!!!"");

    System.out.println(deal.getDescription());      
}

public static void main(String args[]) {
    new TestCreateObj().getMockData();
}
</code></pre>

<p>This exception is thrown at runtime:</p>

<pre><code>Caused by: java.lang.RuntimeException: Class file too large!
    at net.bytebuddy.jar.asm.ClassWriter.toByteArray(Unknown Source)
    at net.bytebuddy.dynamic.scaffold.TypeWriter$Default$ForCreation.create(TypeWriter.java:4108)
    at net.bytebuddy.dynamic.scaffold.TypeWriter$Default.make(TypeWriter.java:1612)
    at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:174)
    at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:155)
    at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase.make(DynamicType.java:2560)
    at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase$Delegator.make(DynamicType.java:2662)
    at org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:94)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:138)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:346)
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:161)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:355)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)
    at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71)
    at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42)
    at org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createMock(ByteBuddyMockMaker.java:26)
    at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)
    at org.mockito.internal.MockitoCore.mock(MockitoCore.java:65)
    at org.mockito.Mockito.mock(Mockito.java:1691)
    at org.mockito.Mockito.mock(Mockito.java:1604)
</code></pre>
",https://stackoverflow.com/questions/42082918/mockito-powermock-class-size-limitations,"['java', 'unit-testing', 'mockito', 'byte-buddy']",1005,TRUE,2,1
Moq verify property when method is called,"<p>I am unit testing a wrapper around WebClient. I want to check at the time calling UploadString, the QueryString property is set to a specific value. I don't need to check the QueryString value after the whole method finish.  </p>

<pre><code>mockedWebClient.Setup(w=&gt;w.UploadString(""url2"",""POST"",""bodyyy"")).Return(""response"");
mockedWebClient.Setup(w=&gt;w.QueryString).Return(new NameValueCollection());

testibject.SomeMethod();

// Verify method was called 
mockedWebClient.Verify(w=&gt;w.UploadString(""url2"",""POST"",""bodyyy"");
// Also verify QueryString is set at the time UploadString is called???
</code></pre>
",https://stackoverflow.com/questions/43811395/moq-verify-property-when-method-is-called,"['c#', 'unit-testing', 'moq']",959,TRUE,1,1
How can I use stub to mock httpclient in C#,"<p>How can I use stub to mock HTTP client while unit testing in c# code?</p>

<p>I don't want to use Moq because I have a method to create http client instance which is static but not virtual.</p>

<p><strong>Code:</strong></p>

<pre><code>public static class HttpClientFactory
{
    public static IHttpClient httpClient;

    public static IHttpClient CreateHttpClient()
    {
        if(httpClient == null)
            httpClient = new HttpClient();
        return httpClient;
    }
}
</code></pre>
",https://stackoverflow.com/questions/44721178/how-can-i-use-stub-to-mock-httpclient-in-c,['c#'],322,TRUE,0,1
Angular Karma Jasmine - test function,"<p>Basically i have to test this below function, where i'm reading from text file</p>

<pre><code>$window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function (dir) {
    var path = 'somefile.txt';                    
    dir.getFile(path, { create: true }, function (file) {
        file.file(function (file) {
            var reader = new FileReader();
            reader.onloadend = function () {                               
                resolve(this.result);
            }
            reader.readAsText(file);
        });
    }, error); 
}, error);
</code></pre>

<p>i'm stuck in writing the unit test cases for reading file</p>

<pre><code>describe('get data from file', function () {            

    it('should read the files from the data', function () {
        var syncFile = 'somefile.txt';

        expect( ).toBe( );
    });
});
</code></pre>

<p>How to write unit test for filereader for reading the file?
PS : i'm new to unit testing using karma</p>
",https://stackoverflow.com/questions/45830994/angular-karma-jasmine-test-function,"['javascript', 'angularjs', 'unit-testing', 'karma-jasmine']",1646,TRUE,5,1
how to mock a method call using moq,"<p>My unit testing method is as follows </p>

<pre><code>[Test]
public void TrackPublicationChangesOnCDSTest()
{
    //Arrange
    // objDiskDeliveryBO = new DiskDeliveryBO();            

    //Act
    var actualResult = objDiskDeliveryBO.TrackPublicationChangesOnCDS();

    //Assert 
    var expectedZipName = 0;
    Assert.AreEqual(expectedZipName, actualResult);
}
</code></pre>

<p>The Actual method <code>TrackPublicationChangesOnCDS</code> in BO is as follows </p>

<pre><code>public int TrackPublicationChangesOnCDS()
{

    var resultFlag = -1;

    try
    {

        string pubUpdateFileCDSPath = CommonCalls.PubUpdateFileCDSPath;
        string pubUpdateFileLocalPath = CommonCalls.PubUpdateFileLocalPath;


        if (File.Exists(pubUpdateFileCDSPath))
            File.Copy(pubUpdateFileCDSPath, pubUpdateFileLocalPath, true);

        if (File.Exists(pubUpdateFileLocalPath))
        {

            string[] pubRecords = File.ReadAllLines(pubUpdateFileLocalPath);

            var pubRecordsExceptToday = pubRecords.Where(p =&gt; !p.Trim().EndsWith(DateTime.Now.ToString(""dd/MM/yy""))).ToList();

            resultFlag = new DiskDeliveryDAO().TrackPublicationChangesOnCDS(pubRecordsExceptToday);

            File.WriteAllText(pubUpdateFileLocalPath, string.Empty);

            string[] pubRecordsCDS = File.ReadAllLines(pubUpdateFileCDSPath);
            var pubRecordsTodayCDS = pubRecordsCDS.Where(p =&gt; p.Trim().EndsWith(DateTime.Now.ToString(""dd/MM/yy""))).ToList();
            File.WriteAllLines(pubUpdateFileCDSPath, pubRecordsTodayCDS);

        }

        return resultFlag;
    }
    catch (Exception)
    {

        return -1;
    }

}
</code></pre>

<p>I want to mock the method call 
 <code>DiskDeliveryDAO().TrackPublicationChangesOnCDS(pubRecordsExceptToday);</code> </p>

<p>How Can I achieve this ? I am not getting enough examples online . I am using Moq library. Can someone help ?</p>
",https://stackoverflow.com/questions/43649228/how-to-mock-a-method-call-using-moq,"['c#', 'mocking', 'nunit', 'moq']",12255,TRUE,3,3
Error: clientWidth is not declared configurable in http://localhost:9877node_modules/jasmine-core/lib/jasmine-core/jasmine.js (line 4410),"<p>I am trying to mock ElementRef properties while unit testing my angular component and it give me the below error</p>

<pre><code>Error: clientWidth is not declared configurable in http://localhost:9877node_modules/jasmine-core/lib/jasmine-core/jasmine.js (line 4410)
</code></pre>

<p>I am getting the error when try to mock the property of native element of an element as below</p>

<pre><code>const div = fixture.debugElement.query(By.css('.ellipsis-overflow'));
div.triggerEventHandler('mouseover', null);
fixture.detectChanges();
expect(component.tooltip.isOpen()).toBeFalsy();
spyOnProperty(div.nativeElement, 'clientWidth', 'get').and.returnValue(1400);
spyOnProperty(div.nativeElement, 'scrollWidth', 'get').and.returnValue(2400);
</code></pre>

<p><code>spyOnProperty</code> is creating that error. </p>
",https://stackoverflow.com/questions/46819077/error-clientwidth-is-not-declared-configurable-in-http-localhost9877node-mod,"['angular', 'karma-jasmine', 'angular-test']",1900,TRUE,3,1
EF InMemory database,"<p>Is there a tool for Entity Framework In Memory database (for unit testing purposes) for standard .NET Framework?</p>

<p>I know there is one for .NET Core that works great, but for this project I need for the standard.NET framework</p>
",https://stackoverflow.com/questions/44073809/ef-inmemory-database,['entity-framework'],882,TRUE,0,1
Fail the entire run at VS unit test even if conitinue after failure is checked,"<p>I have a c# unit testing code at VS in which I like to fail the entire run if a specific [TestMethod] is failed, even though I have checked the ""continue in case of a failure"".</p>

<p>--adding more detail--

<pre><code>[TestMethod] \\should fail the entire run
public void ImportentTest(){}

[TestMethod] \\ should continue to the next testmethode if fail
public void LessImportentTest(){}
</code></pre>
",https://stackoverflow.com/questions/42762627/fail-the-entire-run-at-vs-unit-test-even-if-conitinue-after-failure-is-checked,"['c#', 'unit-testing']",37,FALSE,0,0
Unit Test Symfony Form DateType,"<p>when unit testing a form with a dateType field, my form test will always return null for that field. </p>

<pre><code>    public function testSubmitValidSearchFormData()
{
    // Arrange
    $date = new \DateTime('tomorrow');

    $formData = array(
        'date' =&gt; $date,
    // some other fields
    );

    $object = new SearchModel();
    $object
        -&gt;setDate($formData['date'])
        // set some more fields

    // Act
    $form = $this-&gt;factory-&gt;create(SearchType::class);
    $form-&gt;submit($formData);

    // Assert
    $this-&gt;assertTrue($form-&gt;isSynchronized());
    $this-&gt;assertEquals($object, $form-&gt;getData()); // fails, because of field 'date'

    // some more tests...


}
</code></pre>

<p>SearchType.php:</p>

<pre><code>    public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        // other fields
        // ...
        -&gt;add('date', DateType::class)
        -&gt;add('save', SubmitType::class, [
            'label' =&gt; 'Finden',
            'attr' =&gt; ['formnovalidate' =&gt; true]
        ]);

    return $builder;
}
</code></pre>

<p>Any ideas, why this is the case? My TestClass does not contain any other methods. All other fields do work properly.</p>
",https://stackoverflow.com/questions/47236749/unit-test-symfony-form-datetype,"['php', 'symfony', 'unit-testing']",454,FALSE,1,1
SyntaxError: Use of reserved word &#39;import&#39; running enzyme with karma,"<p>Tried unit testing my React application with Enzyme v3, did not work. PFB the details:</p>

<p>modules installed:</p>

<pre><code>""enzyme"": ""^3.1.1"",
""enzyme-adapter-react-15.4"": ""^1.0.5"",
</code></pre>

<p>Created a file <strong>enzyme.config.js</strong>:</p>

<pre><code>import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-15.4';

Enzyme.configure({ adapter: new Adapter() });
</code></pre>

<p>Included the above file in my karma runner conf:</p>

<pre><code>files: [
        // test setup
        ...........
        'test/unit/testutils/enzyme.config.js',
        ..........
]
</code></pre>

<p>Got following error:</p>

<pre><code>14 11 2017 16:21:48.962:INFO [PhantomJS 2.1.1 (Windows 7 0.0.0)]: Connected on socket GWRhv0qSSmqs4UrpAAAC with id 5625410
PhantomJS 2.1.1 (Windows 7 0.0.0) ERROR
  SyntaxError: Use of reserved word 'import'
  at test/unit/testutils/enzyme.config.js:1
</code></pre>

<p>Is there anything I am missing? </p>
",https://stackoverflow.com/questions/47284074/syntaxerror-use-of-reserved-word-import-running-enzyme-with-karma,"['reactjs', 'gruntjs', 'requirejs', 'karma-runner', 'enzyme']",688,FALSE,0,1
"When doing Moq in webapi, why my contentResult is always null","<p>I was trying to set up my Moq for WebApi unit testing, but Assert.IsNotNull(contentResult) is always failed. Is that becasue I pass my mockList incorrectly?  Please help me, code as belowed</p>

<pre><code> [TestMethod]
  public void GetCEO()
    {

      // setting up the mock framework
      var mockRepository = new Mock&lt;IUsersRepository&gt;();
      List&lt;Users&gt; mockList = new List&lt;Users&gt;();
      {
          new Users
          {
              User = 1,
              FirstName = ""TestFirstName"",
              LastName = ""TestLastName"",
              Group = ""CEO""
          };
      }
      mockRepository
     .Setup(x =&gt; x.GetCEOs())
     .Returns(mockList);

     var controller = new UsersController(mockRepository.Object);

     IHttpActionResult actionResult = controller.Get();
     var contentResult = actionResult as OkNegotiatedContentResult&lt;IEnumerable&lt;Users&gt;&gt;;
     Assert.IsNotNull(mockList);
     Assert.IsNotNull(contentResult);
     Assert.IsNotNull(contentResult.Content);
     var users = contentResult.Content;
     Assert.AreEqual(1, users.Count());
</code></pre>

<p>}</p>

<p>Please check my get action method</p>

<pre><code> [HttpGet]
    [Route(""api/GetCEO"")]
    public IHttpActionResult Get()
    {
        var data=_repository.GetCEOs();
        if (data == null)
            return NotFound();
        else
        return Ok(data);

    }
</code></pre>

<p>My IusersRepositoy</p>

<pre><code>    public interface IUsersRepository
{
    List&lt;Users&gt; GetUsers(int supervisor);

    List&lt;Users&gt; GetCEOs();
}
</code></pre>
",https://stackoverflow.com/questions/43457877/when-doing-moq-in-webapi-why-my-contentresult-is-always-null,"['c#', 'unit-testing', 'asp.net-web-api', 'moq']",748,TRUE,1,1
Setting ref parameters to a private method,"<p>Hello i'm new to coding and especially to unit testing and i'm trying to find a way to set two reference parameters to a private method in order to test it without changing any of my code, for example :</p>

<pre><code>public class A
{

    public string RefPrivateMethod()
    {
        //some code that usually set the strings

        CompareTwoRefStrings(ref largerString, ref smallerString);

        return largerString;
    }

    private void CompareTwoRefStrings(ref string largerString, ref string smallerString)
    {
        int res = largerString.CompareTo(smallerString);
        string temp;

        if (!(res &gt;= 0))
        {
            temp = largerString;
            largerString = smallerString;
            smallerString = temp;
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/42645468/setting-ref-parameters-to-a-private-method,"['c#', 'unit-testing']",547,TRUE,0,3
Check for valid domain name in a string?,"<p>I am using python and would like a simple regex to check for a domain name's validity. I check at least write domain name.</p>

<pre><code>url = 'https://stackoverflow'
        keyword = 'foo'
        with self.assertRaises(ValueError):
            check_keyword(url, keyword)
</code></pre>

<p>I try unit testing on url textfield and there is main.py page where I done the validation 
main.py-</p>

<p>def check_keyword(url, keyword):</p>

<pre><code>if re.match(""^(((([A-Za-z0-9]+){1,63}\.)|(([A-Za-z0-9]+(\-)+[A-Za-z0-9]+){1,63}\.))+){1,255}$"" ,url):
   return ValueError(""Invalid"")
</code></pre>

<p>Example</p>

<ul>
<li><p>www.google (Invalid)</p></li>
<li><p><a href=""https://stackoverflow"" rel=""noreferrer"">https://stackoverflow</a> (Invalid)</p></li>
</ul>
",https://stackoverflow.com/questions/45010810/check-for-valid-domain-name-in-a-string,"['python', 'regex', 'string', 'dns']",24713,TRUE,11,2
How do you mock a function call in chefspec for an object instance extended with another class,"<p>I am new to unit testing and chefspec. I am trying to mock/intercept a function call in a recipe from a dependent library</p>

<ul>
<li><p>Library</p>

<pre><code>module Helper
  def do_something_useful
    return ""http://example.com/file.txt""
  end
end
</code></pre></li>
<li><p>Recipe</p>

<pre><code>remote_file '/save/file/here' do
  extend Helper
  source do_something_useful
end
</code></pre></li>
</ul>

<p>I have tried the following:</p>

<ul>
<li><p>Chefspec</p>

<pre><code>allow_any_instance_of(Chef::Resource::RemoteFile).to receive(:do_something_useful).and_return('foobar')
allow_any_instance_of(Chef::Resource).to receive(:do_something_useful).and_return('foobar')
</code></pre>

<p>I have also tried mocking with a double:</p>

<pre><code>helper = double
Helper.stub(:new).and_return(helper)
allow(helper).to receive(:do_something_useful).and_return('foobar')
</code></pre>

<p>This fails with <code>uninitialized constant Helper</code></p></li>
</ul>
",https://stackoverflow.com/questions/44181461/how-do-you-mock-a-function-call-in-chefspec-for-an-object-instance-extended-with,"['unit-testing', 'chef-infra', 'chefspec']",542,TRUE,2,1
MVPMosby and Mockito,"<p>I'm struggling to make unit tests using <code>Mockito</code> and <code>MVPMosby</code>. I'm attaching the presenter to the view, but in my <code>init()</code> method, <code>presenter.getView()</code> is returning null. Here's my code:</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)
public class MainActivityUnitTest {

    @Mock
    public MainView mainView;
    @Mock
    public MainPresenter mainPresenter;

    @Before
    public void setup() throws Exception {
        MockitoAnnotations.initMocks(this);
        mainPresenter.attachView(mainView);
    }

    @Test
    public void asd() throws Exception {
        mainPresenter.init(null);
        verify(mainView).setRefreshing(true);
    }
}
</code></pre>

<p>Am I doing somethig wrong here? What's the proper way of unit testing with <code>MVPMosby</code> and <code>Mockito</code>?</p>
",https://stackoverflow.com/questions/42297514/mvpmosby-and-mockito,"['android', 'android-studio', 'mockito', 'mvp']",21,FALSE,0,0
how to unit test an angular directive that binds to scroll,"<p>I have an angular directive that returns the scroll top attribute of the element on the scroll event, but I'm having some problems unit testing it. </p>

<p>How do I mock a scroll event so that the scrollTop attribute is changed?</p>

<pre><code>angular
  .module('app')
  .directive('scrollTop', scrollTop);

/** @ngInject */
function scrollTop() {
  return {
    restrict: 'A',
    scope: {
      scroll: '=scrollTop'
    },
    link: function (scope, element) {
      element.bind('scroll', function () {
        scope.scroll = element[0].scrollTop;
      });
    }
  };
}

describe('tests for scroll top directive', function () {
  beforeEach(module('app'));

  it('should make the scrollTop of the element available', angular.mock.inject(function ($rootScope, $compile) {
    $rootScope.scroll = 0;
    var element = $compile('&lt;div style=""height: 1px;width: 5px;"" scroll-top=""scroll""&gt;&lt;/div&gt;')($rootScope);
    $rootScope.$digest();
    element.css({scrollTop: 100})
    element.triggerHandler('scroll');
    expect($rootScope.scroll).toEqual(100);
  }));
});
</code></pre>
",https://stackoverflow.com/questions/43237285/how-to-unit-test-an-angular-directive-that-binds-to-scroll,"['angularjs', 'unit-testing', 'karma-jasmine']",351,FALSE,0,0
How to make executable jar in testng using maven,"<p>Can anyone help me how to make executable jar for testng maven project. My goal is to run the testng executable jar using bat file to run the unit testing</p>

<p>Below is my folder structure</p>

<p><a href=""https://i.stack.imgur.com/VWI3g.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/VWI3g.png"" alt=""enter image description here""></a></p>

<p>Appreciate if you could help me.</p>
",https://stackoverflow.com/questions/43229662/how-to-make-executable-jar-in-testng-using-maven,"['maven', 'testng', 'maven-plugin', 'executable-jar', 'maven-assembly-plugin']",4824,FALSE,0,2
stView.el is undefined while testing Backbone view with jasmine,"<p>I'm using Jasmine for unit testing to test an application with Backbone.js (and it's the first time that I'm working with them both so I'm a little bit stuck :/ ) 
Here is my Backbone view </p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>define(['jquery','backbone','underscore','handelbars','models/story','text!templates/story.html',
		'controllers/storyController'], 
function($, Backbone, _,handelbars, story,storyTemplate,ctrl){
	var View = Backbone.View.extend({
		el: '#main',
		events:{
			'click .close-story' : 'closeStory',
		}
        // Some functions
	});
	return View;
});</code></pre>
</div>
</div>
</p>

<p>and the spec of Jasmine </p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>define(['views/storyView'],function (storyView) {
  describe(""Testing the Story View "",function () {
    var stView;
    beforeEach(function(){
      stView=new storyView({id:1});
      stView.render();
    })
    it(""Test if el is defined and trigger the click "",function () {
      expect(stView.el).toBeDefined(); 
    })
  })
})</code></pre>
</div>
</div>
</p>

<p>Thank you :)</p>
",https://stackoverflow.com/questions/45536113/stview-el-is-undefined-while-testing-backbone-view-with-jasmine,"['unit-testing', 'backbone.js', 'jasmine', 'requirejs', 'jasmine-jquery']",285,FALSE,0,1
How to unit test functions that must occur in pairs?,"<p>Quite often I have some functions that must occur in pairs such as </p>

<pre><code>//Example
startSomething()
...
stopSomething()

//Example
openSomething()
...
closeSomething()
</code></pre>

<p>while unit testing <code>startSomething()</code> and <code>openSomething()</code> is easy since they require no prior conditions / setup, how should I unit test their counterparts which require the prior to be called?</p>
",https://stackoverflow.com/questions/43060073/how-to-unit-test-functions-that-must-occur-in-pairs,"['unit-testing', 'language-agnostic']",18,FALSE,0,1
Check internal variables in a function using Jasmine,"<p>I am using Jasmine and Karma for unit testing in my AngularJS app. I need to check value of internal variables in controller function.</p>

<p>Here is my controller.</p>

<pre><code>(function() {
    'use strict';
    angular
        .module('testApp',[])
        .controller('testController', testController);

    function testController($http, $scope, $timeout) {
        var vm = this;
        vm.getTestValues = getTestValues;

        function getTestValues(){

            vm.serverError = undefined;
            vm.priceList = [];

            $http.get('https://example.com/api/getPrice').then(function(response) {

                vm.priceList = response.data;

                vm.value = vm.priceList[0].itemValue;

                vm.totalValue = vm.value * 10;              

            }).catch(function(e){
                vm.serverError = 'Server Error';
            });
        }
    }
})();
</code></pre>

<p>Here is my test code</p>

<pre><code>describe('Test Controller', function() {
  beforeEach(module('testApp')); 

  var ctrl;

  beforeEach(inject(function($rootScope, $controller){

    scope = $rootScope.$new();
    ctrl = $controller('testController', { $scope: scope });
  }));


  describe('vm.value', function() {
    it('Should be ', function() {     

        ctrl.getTestValues();

        console.log(ctrl.priceList);


    });
  });  

});
</code></pre>

<p><code>console.log(ctrl.priceList);</code> prints <code>[]</code>.</p>

<p>How could I access values in <code>vm.priceList</code>, <code>vm.value</code> and <code>vm.totalValue</code>?</p>
",https://stackoverflow.com/questions/47882263/check-internal-variables-in-a-function-using-jasmine,"['angularjs', 'jasmine', 'karma-runner', 'karma-jasmine']",425,FALSE,0,1
java - testing - lambda with inner private method?,"<p>I have some problems with unit testing the following method.</p>

<pre><code>public List&lt;GetSupplyChainResponse&gt; getSupplyChains(){
    List&lt;GetSupplyChainsResponse&gt; response = new ArrayList&lt;&gt;();
    supplyChainRepository.findSupplyChainsWithCompound().forEach(result
            -&gt; response.add(getGetSupplyChainSimpleResponse(result)));

    return response;
}
</code></pre>

<p><code>getGetSupplyChainSimpleResponse()</code> is a private method of the same class as getSupplyChains()</p>

<p>Is there any possibility to define return values therefore or do you have any other ideas how I could test the method <code>getSupplyChains()</code>?</p>
",https://stackoverflow.com/questions/42573871/java-testing-lambda-with-inner-private-method,"['java', 'unit-testing', 'testing', 'lambda', 'private']",881,TRUE,1,2
Mocking service within service in Angular/Jasmine,"<p>In this Angular/Jasmine code I have one controller and two services, <code>service1</code> and <code>service2</code>. The controller calls <code>service1</code> and <code>service1</code> calls <code>service2</code>.</p>

<p>I'm trying to mock <code>service2</code> while unit testing the controller, without mocking <code>service1</code>. Is this possible?</p>

<p>This is my attempt (that doesn't work) in a <a href=""http://plnkr.co/edit/rkr8hQqtdBW85BMCbrrW?p=preview"" rel=""nofollow noreferrer"">plunk</a>:</p>

<pre><code>angular.module(""myModule"", [])

.service('service1', function(service2){
    this.sum = function(num1,num2) {
        return service2.theRealSum(num1,num2);
    };
})

.service('service2', function(){
    this.theRealSum = function(num1,num2) {
        return num1 + num2;
    };
})


.controller('ctl', function($scope,$timeout,service1) {
      $scope.sumTheTwo = function (num1,num2){
        $scope.result = service1.sum(num1,num2);
    };
});



describe('Testing a Controller that sums', function () {
  var $scope;

  beforeEach(module('myModule'));

  beforeEach(inject(function($controller, _$rootScope_, service1,service2) {
    $scope = _$rootScope_.$new();
    spyOn(service2, 'theRealSum');

    $controller('ctl', { 
      $scope: $scope, 
      service1: service1
    });

  }));

  it('should resolve promise', function () {
    $scope.sumTheTwo(1,2);
    $scope.$apply();
    expect($scope.result).toBe(3);
  });

});
</code></pre>
",https://stackoverflow.com/questions/41636254/mocking-service-within-service-in-angular-jasmine,"['angularjs', 'jasmine', 'karma-jasmine']",105,FALSE,1,0
Mocha test results in browser shows blank,"<p>I am trying to do unit testing with Mocha and Chai. The test runs successfully in terminal, but when I check the testrunner.html file in browser it is blank and just shows ""passes: 0failures: 0duration: 0s""</p>

<p>But in terminal it shows:</p>

<pre><code>$ mocha

  Array
    ✓ should start empty

  1 passing (18ms)
</code></pre>
",https://stackoverflow.com/questions/45471490/mocha-test-results-in-browser-shows-blank,"['unit-testing', 'mocha.js', 'chai']",962,TRUE,0,1
"how to pass react-intl as argument in react component method while jest testing, throws &#39;TypeError: intl.formatMessage is not a function&#39;","<p>I am doing unit testing for my react component(using jest). I have few methods that are called from the component.
For Example:</p>

<pre><code>    export function getText(text, intl) =&gt; ((text !== 'NA') ? (intl.formatMessage({ id: value })) : '');

    const ReactComponent = (props) =&gt; {
       const text = getText(text, intl);

       return (....);
    }

    export default injectIntl(ReactComponent);
</code></pre>

<p>in test file i have:</p>

<pre><code>    import { getText } from 'path';
    import { intl } from 'react-intl';

    it('should render text', () =&gt; {
      expect(getText('string', { intl })).toBe('string');
    });
</code></pre>

<p>When i try to run test, it throws error intl.formatMessage is not a function.</p>
",https://stackoverflow.com/questions/47300600/how-to-pass-react-intl-as-argument-in-react-component-method-while-jest-testing,"['javascript', 'reactjs', 'unit-testing', 'jestjs']",3697,TRUE,1,2
Way to disable sqlalchemy event listeners,"<p>I use sqlalchemy 1.0.
My project has several models, some of them have event listeners, like
<code>event.listen(Model, 'after_update', Model._after_update)</code>.</p>

<p>In case of unit-testing I need to disable all event listeners on model/session/etc.</p>

<p>When particular test finished I need to enable all listeners.</p>

<p>Is there any ways to achieve this?</p>
",https://stackoverflow.com/questions/44947831/way-to-disable-sqlalchemy-event-listeners,"['python', 'unit-testing', 'sqlalchemy']",2188,TRUE,6,1
How to test a class with anonymous listener that is set inside a function?,"<p>I am just getting into unit testing on Android and I ran into some difficulties when I tried to test <code>bindTo()</code> function of this class.</p>

<pre><code>class DataFlow&lt;T&gt; (produce: DataFlowProducer&lt;T&gt;): BaseDataFlow&lt;T&gt;(produce) {
    var updateOnAttach: Boolean = true

    fun bindTo(viewKontroller: ViewKontroller, updateImmediately: Boolean, updateUi: (data: T) -&gt; Unit) {
        this.updateUi = updateUi
        if (updateImmediately)
            flow()
        viewKontroller.addLifecycleListener(object : Controller.LifecycleListener() {
            override fun postAttach(controller: Controller, view: View) {
                if (updateOnAttach) flow()
            }
            override fun preDestroyView(controller: Controller, view: View) {
                viewKontroller.removeLifecycleListener(this)
                this@DataFlow.updateUi = null
            }
        })
    }
}
</code></pre>

<p>If I mock my ViewKontroller test still crashes with NPE on line <code>viewKontroller.addLifecycleListener</code>. </p>

<p>So what am I doing wrong?</p>
",https://stackoverflow.com/questions/47797729/how-to-test-a-class-with-anonymous-listener-that-is-set-inside-a-function,"['android', 'unit-testing', 'kotlin']",268,TRUE,1,1
Partial mocking on class that do not follow SOLID principles (especially Dependency Injection),"<p>I have an example class ""A"" which I am unit testing. I need to dictate the behaviour of class ""X"" such that it gives me a random number that I specified in my unit tests, than a generated value. I am not sure which class should I mock, I need to have the behaviour of X as it is except for the method ""getGen()"" it inherits from the abstract class ""Y"" or is there any other way for me to do what I want to do.</p>

<p>Also, how stupid of an idea is it to override ""getGen()"" in class X, just for unit testing my code? or is my code un-testable?</p>

<p>Testing class A:</p>

<pre><code>class A {
   public Type method(Typ1 a) {
      //do something
      X x = new X(a, String a);
      x.doSmething();
      //do something?
   }
}
</code></pre>

<p>Class X:</p>

<pre><code>final class X extends Y {
   Typ1 t;
   String x;
   X(Typ1 t, String x) {
   this.t = t;
   this.x = x;
   }
   public void doSomething() {
      int x = getGen().method(x);
      //do something
   }
}
</code></pre>

<p>Abstract class y:</p>

<pre><code>abstract class Y {
  Obj getGen(){
    return someInstanceOfObj;
  }
}
</code></pre>

<p>Obj class:</p>

<pre><code>class Obj {
  int method(){
    return someNumber;
  }
}
</code></pre>
",https://stackoverflow.com/questions/41725821/partial-mocking-on-class-that-do-not-follow-solid-principles-especially-depende,"['java', 'unit-testing', 'junit', 'mocking', 'powermock']",42,TRUE,0,1
VB.NET Unit Test with parameters,"<p>At my job, I often switch between developing on projects written in VB.NET and C#. I'm fairly new to Unit Testing and I've been researching and doing some tutorials on how to implement it, but everything I've been able to find has been written in C# (no vb.net examples). I use Visual Studio 2017, so I'm using msTest for Unit Testing.</p>

<p>For the most part I've been able to figure out the syntax differences between C# and vb.net unit testing with msTest, but there's one feature I can't seem to figure out in vb.net. In C# you can do this:</p>

<pre><code>[DataTestMethod]
[DataRow(1)]
[DataRow(2)]
[DataRow(3)]
public void unitTest(int n) {
    // Test code here
}
</code></pre>

<p>This allows you to run the same test for multiple values. I can't find the equivalent syntax for vb.net. Is there even a way to do this in vb.net?</p>

<p>Thanks in advance!</p>

<p><strong>EDIT:</strong>
Here is how my unit test class is setup and what I'm hoping to achieve:</p>

<pre class=""lang-vb prettyprint-override""><code>Imports System
Imports Microsoft.VisualStudio.TestTools.UnitTesting

&lt;TextClass()&gt; Public Class MyUnitTests

    &lt;DataTestMethod()&gt; _
    &lt;DataRow(1)&gt; _
    &lt;DataRow(2)&gt; _
    &lt;DataRow(3)&gt; _
    Public Sub IsValueLessThanTwo(ByVal n as Integer)
        Assert.IsTrue(n &lt; 2, $""{n} is not less than 2"")
    End Sub

End Class
</code></pre>

<p>I would expect this test to run 3 times and pass when the value is 1 but fail when the value is 2 or 3. If I convert this to C#, it runs as expected. But as is, when I build the project I get the following errors:</p>

<blockquote>
  <p>Type 'DataTestMethod' is not defined.</p>
  
  <p>'DataRow' cannot be used as an attribute because it does not inherit from 'System.Attribute'.</p>
</blockquote>
",https://stackoverflow.com/questions/43643863/vb-net-unit-test-with-parameters,"['.net', 'vb.net', 'unit-testing', 'mstest']",1973,FALSE,0,1
Unit test for @viewChild in angular4,"<p>Iam new to unit testing. I tried to write test for @viewChild to be defined or not.</p>

<pre><code>describe('App Component', () =&gt; {
  let component: AppComponent;
  let fixture: ComponentFixture&lt;AppComponent&gt;;
  let debugElement: DebugElement;
  let htmlElement: HTMLElement;
  let testFixture: ComponentFixture&lt;AppTestComponent&gt;;
  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
      imports: [
        HttpClientModule
      ],
      providers: [FileUploadService, HttpClientModule]
    }).compileComponents();
  }));

  beforeEach(async(() =&gt; {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    debugElement = fixture.debugElement;
    htmlElement = debugElement.nativeElement;
  }));

  beforeEach(() =&gt; {
    testFixture = TestBed.createComponent(AppTestComponent);
  });

  it('will have the both `ViewChild`s defined', () =&gt; {
    expect(testFixture.componentInstance.fileInputOne).toBeDefined();
    expect(testFixture.componentInstance.fileInputTwo).toBeDefined();
  });


});


class AppTestComponent {
  @ViewChild('fileInputOne') fileInputOne;
  @ViewChild('fileInputTwo') fileInputTwo;

}
</code></pre>

<p>But this doesnt work. Is this the correct way to write unit test for @viewChild?
Can someone refer intersting and good sites for learning angular4 unit tests ?
What </p>
",https://stackoverflow.com/questions/47427117/unit-test-for-viewchild-in-angular4,"['angular', 'unit-testing', 'karma-jasmine']",768,FALSE,2,0
Google app maker testing approach,"<p>After development how can we test the application, is there any tools available for unit testing or any automation testing can be done in app maker.</p>

<p>If the above things cannot be done means the only option is manual testing. Please suggest me any ideas.</p>
",https://stackoverflow.com/questions/46669690/google-app-maker-testing-approach,['google-app-maker'],183,TRUE,2,1
Syntax error in .runsettings file,"<p>I am trying to include a function in the code coverage using the following line in the .runsettings file:</p>

<pre><code>&lt;Function&gt;^Fort\.CMS\.CMSPages\.BlogModerator\.GetBlogComments$&lt;/Function&gt;
</code></pre>

<p>In the .runsettings file in MSTest project for unit testing. But it gives a syntax error, what I am doing wrong here?</p>

<p>Here </p>

<pre><code>**Fort.CMS.CMSPages**  is the *namespace*
**BlogModerator** is the *Class Name*.
**GetBlogComments** is the *function name*
</code></pre>
",https://stackoverflow.com/questions/46420895/syntax-error-in-runsettings-file,"['c#', 'asp.net', '.net', 'unit-testing', 'mstest']",65,FALSE,0,1
How to test Evernote&#39;s Android Jobs?,"<p>How do I test Jobs created with <a href=""https://github.com/evernote/android-job"" rel=""noreferrer"" title=""android-job"">Android-Job</a> library? Any ideas on unit testing, instrumented testing or even manual testing are appreciated, I just want to check if it works as expected.</p>

<p>To be specific, I have a job that performs an HTTP request every N hours:</p>

<pre><code>package com.kondenko.yamblzweather.job;


import android.support.annotation.NonNull;

import com.evernote.android.job.Job;
import com.evernote.android.job.JobRequest;
import com.kondenko.yamblzweather.model.entity.WeatherData;
import com.kondenko.yamblzweather.ui.weather.WeatherInteractor;
import com.kondenko.yamblzweather.utils.SettingsManager;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

public class UpdateWeatherJob extends Job {

private WeatherInteractor interactor;
private String cityId;
private String units;
private long refreshRateHr;

// Do not delete, needed for job creation
public static final String TAG = ""UpdateWeaterJob"";

@Inject
public UpdateWeatherJob(WeatherInteractor interactor, SettingsManager settingsManager) {
    this.interactor = interactor;
    this.cityId = settingsManager.getSelectedCity();
    this.units = settingsManager.getSelectedUnitValue();
    this.refreshRateHr = settingsManager.getRefreshRate();
}

@NonNull
@Override
protected Result onRunJob(Params params) {
    WeatherData data = interactor.getWeather(cityId, units).blockingGet();
    return data != null ? Result.SUCCESS : Result.FAILURE;
}


public void buildJobRequest(String name) {
    new JobRequest.Builder(UpdateWeatherJob.TAG)
            .setPeriodic(TimeUnit.HOURS.toMillis(refreshRateHr))
            .setRequiredNetworkType(JobRequest.NetworkType.CONNECTED)
            .setRequirementsEnforced(true)
            .setPersisted(true)
            .build()
            .schedule();
}

}
</code></pre>
",https://stackoverflow.com/questions/45123628/how-to-test-evernotes-android-jobs,"['android', 'testing', 'android-job']",448,TRUE,5,1
"Compare two array of object to its value, unit test","<p>Suppose I have two similar array, how can I write unittest to check if these array has the same values.  And these values are equal. I use mocha and enzyme for unit testing. What is the best way to compare this value?</p>

<pre><code>const devices = [{
        deviceType: 'Tag',
        deviceId: 1,
        name: 'Tag For Sending and alarm',
        version: '',
        location: 'Room1',
        lastAliveMessage: '',
        deviceStatus: 'Active',
        actions: 'offline',

    },{
        deviceType: 'Tag1',
        deviceId: 2,
        name: 'Tag For Sending and alarm2 ',
        version: '',
        location: 'Room2',
        lastAliveMessage: '',
        deviceStatus: 'Active',
        actions: 'offline',
    }]

const devices2 = [{
        deviceType: 'Tag',
        deviceId: 1,
        name: 'Tag For Sending and alarm',
        version: '',
        location: 'Room1',
        lastAliveMessage: '',
        deviceStatus: 'Active',
        actions: 'offline',

    },{
        deviceType: 'Tag1',
        deviceId: 2,
        name: 'Tag For Sending and alarm2 ',
        version: '',
        location: 'Room2',
        lastAliveMessage: '',
        deviceStatus: 'Active',
        actions: 'offline',
    }]

 data.forEach(item =&gt; {
                devices.forEach(device =&gt;{
item.deviceId.should.be.equal(device.deviceId))
                })
            })
</code></pre>
",https://stackoverflow.com/questions/46282270/compare-two-array-of-object-to-its-value-unit-test,"['javascript', 'arrays', 'unit-testing', 'ecmascript-6', 'mocha.js']",1715,TRUE,0,2
How to Unit Test in F# using dictionary,"<p>having problems unable to figure out why I can execute this code in f# unit testing </p>

<pre><code>// testing the dictionary method 
   let callStatus = dict[
        ""busy"", ""Monday"";
        ""quite"", ""Tuesday"";
        ""okay"", ""Friday"";
        ""ok"", ""Wednesday"";
   ]

   Assert.AreEqual((""Wednesday"",callStatus.['ok']))
</code></pre>

<p>the Error I am getting is Unmatched '[' which does not make sense as the same code in Console application works fine.</p>

<p>any support would be appreciated. </p>
",https://stackoverflow.com/questions/44175162/how-to-unit-test-in-f-using-dictionary,"['unit-testing', 'f#', 'functional-programming']",61,TRUE,0,2
Python 3: My decorated function runs twice,"<p>I have some simple fibonacci sequence functions that I am practicing unit testing and builds with Travis-CI/Docker:</p>

<p>fib_recursive.py:</p>

<pre><code>from fib.fib import benchmark, fib_rec_memo

@benchmark
def print_fib(n):
    for x in range(0, n):
        print(fib_rec_memo(x))

print_fib(100)
</code></pre>

<p>here is the fib.fib import source code:</p>

<pre><code>from time import time
from functools import wraps

def benchmark(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        t = time()
        func(*args, **kwargs)
        print(func.__name__, 'took:', time() - t)
        return func(*args, **kwargs)
    return wrapper


def fib_rec_memo(n, hash = {0:1, 1:1}):
    if n not in hash:
        hash[n] = fib_rec_memo(n-1) + fib_rec_memo(n-2)
    return hash[n]


@benchmark
def fib_standard(num):
    a, b = 0, 1
    c = []
    while a &lt; num:            # First iteration:
        c.append(a)            # yield 0 to start with and then
        a, b = b, a + b    # a will now be 1, and b will also be 1, (0 + 1)
    return c
</code></pre>

<p>For some reason executing python3 ./fib_recursive.py launches the function twice:</p>

<pre><code># python3 ./fib_recursive.py
1
1
2
3
5
8
13
21
34
55
print_fib took: 0.00011181831359863281
1
1
2
3
5
8
13
21
34
55
#
</code></pre>

<p>Does anyone know why?</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/48026242/python-3-my-decorated-function-runs-twice,"['python', 'python-3.x', 'function']",50,TRUE,0,1
Visual Studio 2017 Unit Test Project vs xUnit Test Project,"<p>In .NET Core under Visual Studio 2015 one had to create a unit test project that was based on xunit, though the command line (no dedicated project was available in Visual Studio for .NET Core).</p>

<p>In Visual Studio 2017, under .NET Core section there are now 2 types of unit testing projects available:</p>

<ol>
<li>Unit Test Project (.NET Core)</li>
<li>xUnit Test Project (.NET Core)</li>
</ol>

<p>What is the difference between them? What is the recommended one these days?</p>
",https://stackoverflow.com/questions/44165832/visual-studio-2017-unit-test-project-vs-xunit-test-project,"['.net-core', 'visual-studio-2017', 'xunit.net']",7116,TRUE,28,2
how to test picasso using unit-test and mockito,"<p>I am learning how to unit-testing in android studio. as shown below, I would like to test the two methods shown below in the code section.</p>

<p>can you please help and guide me how to test this method?</p>

<p><strong>code</strong></p>

<pre><code>public RequestCreator requestCreatorFromUrl(String mPicUrl) 
{
    return Picasso.with(mCtx).load(mPicUrl);
}

public void setImageOnImageView(RequestCreator requestCreator, ImageView mImagView) 
{
    requestCreator.into(mImagView);
}
</code></pre>

<p><strong>My Attempts</strong>:</p>

<pre><code>@Test
public void whenRequestCreatorFromUrlTest() throws Exception {
    Picasso mockPicasso = mock(Picasso.class);
    File mockFile = mock(File.class);

    Assert.assertNotNull(""returned Request creator is not null"",    
 mockPicasso.load(mockFile));
}
</code></pre>
",https://stackoverflow.com/questions/46262467/how-to-test-picasso-using-unit-test-and-mockito,"['android', 'junit', 'mocking', 'mockito', 'junit4']",1036,FALSE,0,1
jUnit testing using hamcrest matcher - how to test the size of a collection.,"<p>Does a specific api exist to check the size of collections while unit testing using JUnit/hamcrest.</p>

<p>Currently I am doing -  </p>

<pre><code>Set&lt;String&gt; result = program.getCollection(""inputdata"");
assertThat(3, is(result.size()) );
</code></pre>

<p>Is the above acceptable or I should be using <code>iterableWithSize</code> , as below</p>

<pre><code>assertThat(result, iterableWithSize(3));
</code></pre>

<p>What should be the standard way, or are both approaches ok.</p>
",https://stackoverflow.com/questions/46413584/junit-testing-using-hamcrest-matcher-how-to-test-the-size-of-a-collection,"['java', 'unit-testing', 'junit', 'matcher', 'hamcrest']",1707,TRUE,0,2
Unit test case with controller as syntax giving error,"<p>I am unit testing a controller
USing karma.</p>

<p>Test case for controller:</p>

<pre><code>    'use strict';
fdescribe('products', function() {
    // load the controller's module
    var ctrl, scope;
    beforeEach(angular.mock.module('products'));
    beforeEach(function() {
        module('products', function($controllerProvider) {
            $controllerProvider.register('productsController', function($scope) {

            });
        });
    });

    describe('controller', function() {

        beforeEach(function() {
            angular.mock.inject(function($controller, $rootScope) {
                scope = $rootScope.$new();
                ctrl = $controller('productsController', {
                    $scope: scope
                });
            })
        });

        it('controller is set', function() {
            expect(ctrl.currentCategory).toBe(""ALL_PRODUCTS"");
        });
    });
});
</code></pre>

<p>I have mocked the module in which the controller is there.
The expected code here is giving error as expect undefined to be ""ALL_PRODUCTS"".
controller.js:</p>

<pre><code>(function() {
'use strict';
var productsController = function($rootScope, $scope) {
    var vm = this;
    vm.currentCategory = ""ALL_PRODUCTS"";

};

productsController.$inject = ['$rootScope', '$scope'];

module.exports = productsController;
</code></pre>

<p>})();</p>

<p>Module.js:</p>

<pre><code>(function() {
'use strict';
module.exports = angular.module('products', ['common.services'])
    .controller('productController', require('./controller.js'))
</code></pre>

<p>})();</p>

<p>Any help would be appreciated.</p>
",https://stackoverflow.com/questions/43320417/unit-test-case-with-controller-as-syntax-giving-error,"['javascript', 'angularjs', 'unit-testing', 'karma-runner', 'karma-jasmine']",116,FALSE,0,0
How to have default imports for all my spec files in TypeScript?,"<p>Here's a really simple spec file for unit testing a TypeScript + React application:</p>

<pre><code>import * as React from ""react""; // COMMON

import * as chai from ""chai""; // COMMON
import * as chaiEnzyme from ""chai-enzyme"" // COMMON
import * as sinon from ""sinon""; // COMMON
import * as sinonChai from ""sinon-chai""; // COMMON

import { expect } from ""chai""; // COMMON
import { shallow } from ""enzyme""; // COMMON

import Hello from ""./Hello"";

describe(""Hello"", () =&gt; {

    chai.use(chaiEnzyme()); // COMMON
    chai.use(sinonChai); // COMMON

    let hello = shallow(&lt;Hello name=""Willson"" /&gt;);

    it(""should render correctly"", () =&gt; {
        expect(hello).to.have.tagName(""div"");
    });

    it(""should have correct prop values"", () =&gt; {
        expect(hello).to.have.text(""Hello, Willson"");
    });

});
</code></pre>

<p>I see myself using the lines with <code>// COMMON</code> being used on every spec file. <strong>Is there a TypeScript way to do this by default on all my files matching this: <code>/Spec\.(ts|tsx)/</code>?</strong></p>
",https://stackoverflow.com/questions/41744239/how-to-have-default-imports-for-all-my-spec-files-in-typescript,"['unit-testing', 'reactjs', 'typescript', 'typescript-typings']",418,TRUE,0,1
How to test router.navigate with subscribe ? Angular2,"<p>I'm pretty new in unit testing in Angular 2 so i'm asking your help. </p>

<p>My logout function : </p>

<pre><code>logOut() {
    this.authService.logOut().subscribe(() =&gt; {
        this.router.navigate(['login']);
    });
}
</code></pre>

<p>And my unit test :</p>

<pre><code>describe('HomeComponent', () =&gt; {
  let component: HomeComponent;
  let fixture: ComponentFixture&lt;HomeComponent&gt;;
  let authenticationService: AuthenticationService;
  let mockLogOut = {
    logOut: () =&gt; { }
  };

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
        imports: [
            FormsModule,
            HttpModule,
            CommonModule,
            ReactiveFormsModule,
            TranslateModule,
            RouterTestingModule.withRoutes([
                { path: 'login', component: LoginComponent }
            ])
        ],
        declarations: [HomeComponent, LoginComponent],
        providers: [
            { provide: AuthenticationService, useValue: mockLogOut },
            TranslateService,
            TRANSLATION_PROVIDERS
        ],
        schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
        .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(HomeComponent);
    authenticationService = TestBed.get(AuthenticationService);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });

  describe('Authentication Tests', () =&gt; {
    it('should log out the user', inject([AuthenticationService], (mockLogin: AuthenticationService) =&gt; {
        fakeAsync(() =&gt; {
            spyOn(authenticationService, 'logOut');
            let navigateSpy = spyOn((&lt;any&gt;component).router, 'navigate');
            component.logOut();
            expect(mockLogin.logOut).toHaveBeenCalled();
            expect(navigateSpy).toHaveBeenCalledWith(['/log1n']);
        });
    }));
  });
});
</code></pre>

<p>I want to check if the user is redirected to the route /login but this test always success even if I put something else than /login</p>
",https://stackoverflow.com/questions/43201716/how-to-test-router-navigate-with-subscribe-angular2,"['unit-testing', 'angular', 'routes', 'jasmine', 'subscribe']",816,FALSE,3,0
Getting compile time error : The import net.corda.core.testing cannot be resolved,"<p>I am using gradle + Eclipse(Oxygen), and I'm trying to implement Unit testing for my Corda app, for this I am following the example from <a href=""https://docs.corda.net/tutorial-test-dsl.html"" rel=""nofollow noreferrer"">https://docs.corda.net/tutorial-test-dsl.html</a></p>

<p>Here they have used:</p>

<pre><code>import static net.corda.core.testing.JavaTestHelpers.*;
import static net.corda.core.contracts.JavaTestHelpers.*;

@Test
public void emptyLedger() {
    ledger(l -&gt; {
        return Unit.INSTANCE; // We need to return this explicitly
    });
}
</code></pre>

<p>Here I'm getting compile time error as following: </p>

<pre><code>The import net.corda.core.testing cannot be resolved. 
There is no package called net.corda.core.testing, and no javadocs.
</code></pre>
",https://stackoverflow.com/questions/47450849/getting-compile-time-error-the-import-net-corda-core-testing-cannot-be-resolve,"['java', 'corda']",141,TRUE,0,1
Can&#39;t make schema into cassandra using phantom-dsl,"<p>Trying to create a schema into cassandra using <code>phantom-dsl</code> for unit testing following this tutorial:</p>

<p><a href=""http://outworkers.com/blog/post/phantom-tips-3-understanding-phantom-connectors"" rel=""nofollow noreferrer"">http://outworkers.com/blog/post/phantom-tips-3-understanding-phantom-connectors</a></p>

<p>I ran into this issue when trying to auto-generate schema</p>

<pre><code>[ERROR] /home/.../test/BaseCassandraSpec.scala:54: error: not enough arguments for method autocreate: (keySpace: com.websudos.phantom.connectors.KeySpace)
com.websudos.phantom.builder.query.CreateQuery.Default[com.neruti.db.models.ConcreteUserModel,com.neruti.User].
[ERROR] Unspecified value parameter keySpace.
[ERROR] Await.result(database.userModel.autocreate().future(),10.seconds)
</code></pre>

<p>Any advice?</p>

<p>Currently using version <code>1.29.6</code></p>

<p><strong>BaseCassandraSpec</strong></p>

<pre><code>import com.neruti.User
import com.neruti.db.models._
import com.neruti.db.databases._
import com.neruti.db.services._
import com.neruti.db.Connector._    
import org.scalatest._
import org.scalatest.{BeforeAndAfterAll,FlatSpec,Matchers,ShouldMatchers}
import org.scalatest.concurrent.ScalaFutures
import org.scalamock.scalatest.MockFactory
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
import scala.concurrent.ExecutionContext.Implicits.global

 override protected def beforeAll(): Unit = {
    Await.result(database.userModel.autocreate().future(),10.seconds)
   } 
</code></pre>

<p><strong>Database</strong></p>

<pre><code>class UserDatabase (val connector: KeySpaceDef){
  object userModel extends ConcreteUserModel with connector.Connector
}

object ProductionDb extends UserDatabase(connector)

trait ProductionDatabaseProvider {
  def database: UserDatabase
}

trait ProductionDatabase extends ProductionDatabaseProvider {
  override val database = ProductionDb
}

object testDB extends UserDatabase(testConnector)

trait testDatabaseProvider {
  def database: UserDatabase
}

trait testDatabase extends testDatabaseProvider{
  override val database = testDB
}
</code></pre>

<p><strong>Connector</strong></p>

<pre><code>package com.neruti.db

import com.neruti.db.models._

import com.websudos.phantom.database.Database
import com.websudos.phantom.connectors.ContactPoints
import com.websudos.phantom.dsl.KeySpaceDef

object Connector {



    // TODO: these key value pairs shld get from HOCON config file
      val host= Seq(""127.0.0.1"")
      val port = 9042
      val keySpace: String = ""nrt_entities""
      //  val inet = InetAddress.getByName

      lazy val connector = ContactPoints(host,port).withClusterBuilder(
        _.withCredentials(""dev"", ""nrtDev1989"")
      ).keySpace(keySpace)

      //  embedded cassandra is not supported anymore.  Check phantom-sbt.
      //    lazy val testConnector: KeySpaceDef = ContactPoint.embedded.keySpace(keySpace)
      lazy val testConnector: KeySpaceDef = ContactPoints(host,port).noHeartbeat().keySpace(keySpace)
    }
</code></pre>
",https://stackoverflow.com/questions/41569218/cant-make-schema-into-cassandra-using-phantom-dsl,"['scala', 'cassandra', 'phantom-dsl']",421,FALSE,0,1
Error: Invalid configuration of route &#39;&#39;: Encountered undefined route.,"<p>trying Unit testing out in Angular 4 and getting the following error: </p>

<pre><code>Error: 
          Invalid configuration of route '': Encountered undefined route.
          The reason might be an extra comma.
          Example:
          const routes: Routes = [
            { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
            { path: 'dashboard',  component: DashboardComponent },, &lt;&lt; two commas
            { path: 'detail/:id', component: HeroDetailComponent }
          ];
</code></pre>

<p>however if add my routing paths in manually in RouterTestingModule.withRoutes(), it seems they work perfect so I'm concluding that my import of the routing from app-routing.module.ts is messing up somewhere?</p>

<p><strong>app-routing.module.ts</strong></p>

<pre><code>import {Routes, RouterModule} from '@angular/router';
import {ModuleWithProviders} from '@angular/core';
import {ScreenComponent} from './screen/screen.component';

const router: Routes = [
  {path: '', redirectTo: 'https://www.examplehere.com', pathMatch: 'full'},
  {path: 'home/:rmId/:leadId', component: ScreenComponent},
  {path: '**', redirectTo: 'https://www.examplehere.com'}
];

export const routes: ModuleWithProviders = RouterModule.forRoot(router)
</code></pre>

<p><strong>spec file</strong></p>

<pre><code>import { ScreenComponent } from './screen/screen.component';
import { async, getTestBed, inject, TestBed } from '@angular/core/testing';
import { DropdownModule } from 'primeng/primeng';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';
import { Http } from '@angular/http';
import { AppGlobalService } from './shared/app.global.service';
import { Router } from '@angular/router';
import { Location } from '@angular/common';
import { routes } from './app-routing.module';

describe('component: ScreenComponent', () =&gt; {
      let router, location, injector;

      beforeEach(() =&gt; {
        TestBed.configureTestingModule({
          imports: [
            DropdownModule,
            ReactiveFormsModule,
            FormsModule,
            RouterTestingModule.withRoutes([
              // {path: 'home/:rmId/:leadId', component: ScreenComponent}
              router
            ])],
          declarations: [ ScreenComponent ],
          providers: [ {provide: AppGlobalService}, {provide: Http} ]
        });

        beforeEach(inject([Router, Location], (_router: Router, _location: Location) =&gt; {
          location = _location;
          router = _router;
        }));

        injector = getTestBed();
        location = injector.get(Location);
        router = injector.get(Router);

      });

      it('should go home', async(() =&gt; {
        const fixture = TestBed.createComponent(ScreenComponent);
        router.navigate(['home/:rmId/:leadId']).then(() =&gt; {
          expect(location.path()).toBe('/home/:rmId/:leadId');
        });
      }));

    });
</code></pre>
",https://stackoverflow.com/questions/46306079/error-invalid-configuration-of-route-encountered-undefined-route,"['angular', 'unit-testing', 'angular-ui-router', 'karma-jasmine']",1512,FALSE,3,0
Testing async method in react with jest,"<p>I am a newbie in unit testing and I have 2 files:</p>

<p>RestaurantReducer</p>

<pre><code>import * as Const from '../constants/Const'

const RestaurantReducer = (state = {
    restaurantList: []
}, action) =&gt; {
    switch (action.type) {
        case Const.GET_RESTAURANT_LIST: {

            return {
                ...state,
                restaurantList: action.payload
            };
        }
    }
    return state;
};

export default RestaurantReducer;
</code></pre>

<p>and RestauntActions.js</p>

<pre><code>export function getRestaurantList() {
    return dispatch =&gt; {
        axios({
            method: ""GET"",
            url: URLS.URL_RESTAURANT_LIST
        }).then((response) =&gt; {
            dispatch({
                type: CONST.GET_RESTAURANT_LIST,
                payload: response.data
            })
        })
    }
}
</code></pre>

<p>and my test: </p>

<pre><code>describe('request reducer', () =&gt; {

    it('Default values', () =&gt; {
        expect(restReducer(undefined, {type: 'unexpected'})).toEqual({
          restaurantList: []
        });
    });

    // ---------------- Dont know how to check this -------------------
    it('Async data',async () =&gt; {

        expect(restReducer(undefined, {
            type: 'GET_RESTAURANT_LIST',
        })).toEqual({
            ...state,
            restaurantList: []
        });
    });
});
</code></pre>

<p>I do not know how to go about it. Can you check the connection or data that come from the server? Can such data simulate but they are dynamic.</p>
",https://stackoverflow.com/questions/46197111/testing-async-method-in-react-with-jest,"['javascript', 'reactjs', 'testing', 'jestjs']",1142,FALSE,3,1
How to generate writable path in FileManager that works in XCTest,"<p>I am writing an XCTest that involves writing a file to disk. I am using an AppGroup to define the file path. This works fine running on device or simulator.</p>

<pre><code>class func filePath()-&gt;URL {
    guard let path = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: ""my.app.group.id"") else {
        fatalError(""No File Path"")
    }
    let filePath = path.appendingPathComponent(""filename.json"")
    return filePath
}
</code></pre>

<p>… However the <code>containerURL</code> doesn't return something in an XCTest environment. The test crashes.</p>

<p>How can I generate a temporary path that works for Unit Testing?</p>
",https://stackoverflow.com/questions/47849600/how-to-generate-writable-path-in-filemanager-that-works-in-xctest,"['swift', 'unit-testing', 'xctest', 'nsfilemanager', 'ios-app-group']",496,FALSE,9,1
Mock jdbcTemplate instantiated by class,"<p>I got a class that creates it's own jdbcTemplate using <code>new jdbcTemplate(dataSource)</code> and creates its own NamedParameterJdbcTemplate when needed using new <code>NameParameterJdbcTemplate(jdbcTemplate)</code>. How do I use Mockito to make it so that when unit testing the templates are mocked templates that I can control the return value of?</p>
",https://stackoverflow.com/questions/44591982/mock-jdbctemplate-instantiated-by-class,"['java', 'unit-testing', 'mockito']",1015,FALSE,1,1
React Jest - Expecting an element after form submit,"<p>I'm currently encountering this error in my unit testing wherein I cannot find the element with an specific classname after I simulate the form submit:</p>

<p><strong>HTML Element in inspect element:</strong></p>

<pre><code>&lt;div class=""ant-form-item-control has-error""&gt;
  &lt;input type=""text"" class=""ant-input ant-input-lg addSiteBasics_businessName"" value="""" placeholder=""English Business Name"" id=""businessName""&gt;
  &lt;div class=""ant-form-explain""&gt;Please add the name of your business.&lt;/div&gt;
&lt;/div&gt;
</code></pre>

<p><strong>Test Script:</strong></p>

<pre><code>describe('given business name is empty', () =&gt; {
    it('display error if business name empty', () =&gt; {
      const form = wrapper.find('form').first();
      form.simulate('submit');
      expect(wrapper.find('div.has-error #businessName').exists()).toBe(true);
    })
  });
</code></pre>

<p><strong>This is the error that displays in my terminal:</strong></p>

<blockquote>
  <p>expect(received).toBe(expected)</p>

<pre><code>    Expected value to be (using ===):
      true
    Received:
      false
</code></pre>
</blockquote>
",https://stackoverflow.com/questions/47939613/react-jest-expecting-an-element-after-form-submit,"['reactjs', 'enzyme', 'jestjs']",431,FALSE,1,0
"Rails Clearance, Unit Test Controller","<p>I'm having trouble getting the Clearance authentication to work with Rails controller unit testing. I've followed the instructions at <a href=""https://github.com/thoughtbot/clearance"" rel=""nofollow noreferrer"">https://github.com/thoughtbot/clearance</a> ""Controller Test Helpers"". How do you unit test controllers that require authentication?</p>

<p>I get the following error:</p>

<pre><code>GoalsControllerTest#test_should_get_index:
NoMethodError: undefined method `sign_in_as' for #&lt;GoalsControllerTest:0x007f8c41c6b9c8&gt;
    test/controllers/goals_controller_test.rb:7:in `block in &lt;class:GoalsControllerTest&gt;'
</code></pre>

<p><strong>test/test_helper.rb</strong></p>

<pre><code>require 'clearance/test_unit'
</code></pre>

<p><strong>test/controller/goals_controller_test.rb</strong></p>

<pre><code>require 'test_helper'

class GoalsControllerTest &lt; ActionDispatch::IntegrationTest
  setup do
    user = User.new(fname: ""Test"", lname: ""User"", email: ""testuser@test.com"", password: ""password"")
    sign_in_as(user)
    @goal = goals(:one)
  end
</code></pre>
",https://stackoverflow.com/questions/42604284/rails-clearance-unit-test-controller,"['ruby-on-rails', 'unit-testing', 'clearance']",770,TRUE,1,2
Does a static property in a non-staic class get removed by the GC?,"<p>I have a mock database class for unit testing</p>

<p>In each unit test I create a MockDB object and the users added from previously run tests are already there but how long will the static List object last since the class isn't marked as <code>static</code>?</p>

<pre><code>public class MockDB
{
    public static List&lt;User&gt; users = new List&lt;User&gt;();

    public void Add(User user)
    {
        users.Add(user);
    }

    public void Remove(User user)
    {
        users.Remove(user);
    }

    public User Get(int userId)
    {
        return users.Where(u =&gt; u.UserId == userId);
    }
}
</code></pre>
",https://stackoverflow.com/questions/47781058/does-a-static-property-in-a-non-staic-class-get-removed-by-the-gc,['c#'],44,TRUE,1,1
Running a Python unittest test on multiple files,"<p>I want to add unit testing to the assessment of my high school programming class.  </p>

<p>If I have twenty submissions of files that look like this:</p>

<pre><code>def calculateReturn(principle, rate, freq, time):
    final = principle * (1 + (rate/freq)) ** (freq * time)
    return final
</code></pre>

<p>Can I use a test case like this?</p>

<pre><code>import unittest

class test(unittest.TestCase):
    def test1(self):
        value = calculateReturn(5000, 0.05, 12, 11)
        self.assertAlmostEqual(value, 8235.05, 2)

if __name__ == '__main__':
    unittest.main()
</code></pre>

<p>How do I run this one simple test on twenty modules?</p>

<p><strong>FURTHER INFORMATION</strong></p>

<p>For testing I have created three ""submissions"" all of which show different ways of calculating x^y.</p>

<p>submission1.py:</p>

<pre><code>from math import pow

def powerFunction(base, power):
   result = pow(base, power)
   return result
</code></pre>

<p>submission2.py:</p>

<pre><code>def powerFunction(base, power):
    result = base ** power
    return result
</code></pre>

<p>submission3.py:</p>

<pre><code>def powerFunction(base, power):
    result = 1
    for i in range(power):
        result = result * base

    return result
</code></pre>

<p>The test code is:</p>

<pre><code>import unittest
import importlib

class MyTest(unittest.TestCase):
    def setUp(self):
        pass

    def test_power_3_4(self):
        self.assertEqual(module.powerFunction(2, 3), 8)

files = ['submission1', 'submission2', 'submission3']
for file in files:
    module = importlib.import_module(file)
    print module
    unittest.main()
</code></pre>

<p>if the test code is run the console output shows only submission1 being tested:</p>

<pre><code>/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
/Users/staff/PycharmProjects/UnitTest/powerTest.py
&lt;module 'submission1' from '/Users/staff/PycharmProjects/UnitTest/
submission1.pyc'&gt;
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

Process finished with exit code 0
</code></pre>

<p>Interestingly if I don't use unit testing I can correctly import and test using this approach:</p>

<pre><code>import importlib

files = ['submission1', 'submission2', 'submission3']

for file in files:
    module = importlib.import_module(file)
    print module
    print module.powerFunction(2,3)
</code></pre>

<p>The console output here is:</p>

<pre><code>/System/Library/Frameworks/Python.framework/Versions/2.7/bin/
python2.7 /Users/staff/PycharmProjects/UnitTest/importlib1.py
&lt;module 'submission1' from '/Users/staff/PycharmProjects/UnitTest/
submission1.pyc'&gt;
8.0
&lt;module 'submission2' from    '/Users/staff/PycharmProjects/UnitTest/
submission2.pyc'&gt;
8
&lt;module 'submission3' from   '/Users/staff/PycharmProjects/UnitTest/
submission3.pyc'&gt;
8

Process finished with exit code 0
</code></pre>

<p>It may well be that the unittest module is not the best approach here but I'm still interested on how to implement it.</p>
",https://stackoverflow.com/questions/44620766/running-a-python-unittest-test-on-multiple-files,"['python', 'python-2.7', 'unit-testing']",2905,TRUE,2,2
How do I mock the @Attribute decorator string provider in an ng2 unit test?,"<p>I have a component that I'm unit testing, but I've run into a gotcha. I don't know how to mock the work of the @Attribute decorator in my test.</p>

<p><code>Error: No provider for String!</code></p>

<pre><code>@Component({...})
export class MyComponent {
    constructor(@Attribute(""handle"") private handle: string) { }
}
</code></pre>

<p>I specifically need to know what to 'provide' in my test.</p>

<p><code>{ provide: ??, useValue: """" }</code></p>

<p><strong>UPDATE</strong></p>

<p>Here's the test setup</p>

<pre><code>describe(""MyComponent"", () =&gt; {
    let component: MyComponent;

    beforeEach(() =&gt; {
        this.injector = ReflectiveInjector.resolveAndCreate([
            { provide: ??, useValue: """" }, //@Attribute provider??
            ... // other mocked providers
            MyComponent
        ]);

        component = this.injector.get(MyComponent);
    });
    ...
});
</code></pre>
",https://stackoverflow.com/questions/45510091/how-do-i-mock-the-attribute-decorator-string-provider-in-an-ng2-unit-test,"['angular', 'unit-testing', 'typescript']",710,TRUE,1,1
How to test byte[] array with xUnit?,"<p>I'm new to C# unit testing and xUnit. What is the correct way to test <code>byte[]</code> array?</p>

<p>I'm trying to test raw packet to object to raw packet again.</p>

<pre><code>[Fact]
public void DiscoverTest()
{
    // DHCP Discover packet (#1) from 
    // https://wiki.wireshark.org/DHCP
    // https://wiki.wireshark.org/SampleCaptures?action=AttachFile&amp;do=view&amp;target=dhcp.pcap
    // Ethernet and UDP metadata stripped
    byte[] b = new byte[]
    {
       0x01, 0x01, 0x06, 0x00, 0x00, 0x00, 0x3d, 0x1d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
       0x00, 0x0b, 0x82, 0x01, 0xfc, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x82,
       0x53, 0x63, 0x35, 0x01, 0x01, 0x3d, 0x07, 0x01, 0x00, 0x0b, 0x82, 0x01, 0xfc, 0x42,
       0x32, 0x04, 0x00, 0x00, 0x00, 0x00, 0x37, 0x04, 0x01, 0x03, 0x06, 0x2a, 0xff, 0x00,
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00
    };

    // raw byte[] to object's properties etc
    DHCPPacket p = new DHCPPacket(b);

    // p.GetRawBytes() object properties etc to raw byte[]
    Assert.Equal&lt;byte[]&gt;(b, p.GetRawBytes());
}
</code></pre>

<p>This gives:</p>

<pre><code>Assert.Equal() Failure
Expected: Byte[] [1, 1, 6, 0, 0, ...]
Actual:   Byte[] [1, 1, 6, 0, 0, ...]
</code></pre>

<p>So I can't see in which offset data is actually wrong. </p>

<p>What's the correct way?</p>

<p>I'm using xUnit 2.2.0.</p>
",https://stackoverflow.com/questions/47943110/how-to-test-byte-array-with-xunit,"['c#', 'unit-testing', 'xunit.net']",5977,TRUE,4,2
Error in unit tests after yeoman gulp-angular projekt setup,"<p>...</p>

<p>got a problem with a problem setup. </p>

<p>I use yeoman and create my project with </p>

<pre><code>yo gup-angular
</code></pre>

<p>After setup I start the unit testing with</p>

<pre><code>gulp test
</code></pre>

<p>But it fails with:</p>

<pre><code>PS P:\projects\test-logbook&gt; gulp test
[15:15:14] Using gulpfile P:\projects\mydisk-logbook\gulpfile.js
[15:15:14] Starting 'scripts'...
[15:15:15] all files 14.08 kB
[15:15:15] Finished 'scripts' after 840 ms
[15:15:15] Starting 'test'...
28 09 2017 15:15:15.601:WARN [proxy]: proxy ""\base\src\assets\"" normalized to ""\base\src\assets\/""
28 09 2017 15:15:15.665:WARN [watcher]: Pattern ""P:/projects/mydisk-logbook/src/**/*.mock.js"" does not match any file.
PhantomJS 1.9.8 (Windows 8 0.0.0) ERROR
  TypeError: 'undefined' is not a function (near '....info({ angularVersion: '...')
  at P:/projects/mydisk-logbook/bower_components/angular-animate/angular-animate.js:4138


[15:15:18] 'test' errored after 2.69 s
[15:15:18] Error: Failed 1 tests.
    at P:\projects\mydisk-logbook\gulp\unit-tests.js:41:22
    at removeAllListeners (P:\projects\mydisk-logbook\node_modules\karma\lib\server.js:336:7)
    at Server.&lt;anonymous&gt; (P:\projects\mydisk-logbook\node_modules\karma\lib\server.js:347:9)
    at Server.g (events.js:292:16)
    at emitNone (events.js:91:20)
    at Server.emit (events.js:185:7)
    at emitCloseNT (net.js:1554:8)
    at _combinedTickCallback (internal/process/next_tick.js:77:11)
    at process._tickCallback (internal/process/next_tick.js:104:9)
</code></pre>

<p>It failed in bower_components/angular-animate/angular-animate.js, line 4138. </p>

<p>How to solve that error? What is my fail?</p>

<p>Regards
n00n</p>

<p>ps: Bower Update gets me this information</p>

<pre><code>Please note that,
    angular-aria#1.5.11, angular-cookies#1.5.11, angular-messages#1.5.11, angular-mocks#1.5.11, angular-resource#1.5.11, angular-sanitize#1.5.11, angular-touch#1.5.11 depends on angular#1.5.11 which resolved to angular#1.5.11
    mydisk-logbook depends on angular#~1.5.3 which resolved to angular#1.5.11
    angular-material#1.0.9 depends on angular#^1.4.8 which resolved to angular#1.5.11
    angular-ui-router#0.2.18 depends on angular#^1.0.8 which resolved to angular#1.5.11
    angular-toastr#1.5.0 depends on angular#&gt;=1.3.0 which resolved to angular#1.5.11
    angular-animate#1.6.6 depends on angular#1.6.6 which resolved to angular#1.6.6
Resort to using angular#~1.5.3 which resolved to angular#1.5.11
Code incompatibilities may occur.

bower jquery                    extra-resolution Unnecessary resolution: jquery#~2.1.4
</code></pre>
",https://stackoverflow.com/questions/46470265/error-in-unit-tests-after-yeoman-gulp-angular-projekt-setup,"['javascript', 'angularjs', 'unit-testing', 'yeoman']",155,TRUE,9,1
What is the best approach to unit test node js controller which using a service method,"<p>My Controller => below controller is using reqpoertService.getFiles method and that method itself using a external APIs to call the data.</p>

<pre><code>function getFiles(req, res) {
    reportService.getFiles({
        fromDate: req.query.fromdate,
        endDate: req.query.enddate,
        fileTypes: req.query.filetypes || [],
        fileStatus: req.query.filestatus || []
    })
    .then(data =&gt; {
       logger.info('-&gt; reportService.getFiles :: Successfully fetched data',
                   resolveLogger({ statusCode: res.statusCode })
       );
       res.send(data);
   })
   .catch(err =&gt; {
       logger.error('&lt;- OOPS :: reportService.getFiles fail to fetch data');
       res.status(statusCodes.INTERNAL_SERVER_ERROR).send({});
       logger.error('&lt;- ERROR', resolveLogger({
           statusCode: res.statusCode,
           errMessage: err.message,
           errorStack: err
       }));
   });
}
</code></pre>

<p>Reporter Service</p>

<pre><code>function getFiles() {
    return new Promise((resolve, reject) =&gt; {
        requestPromise(options)
            .then(data =&gt; {
                var duration = new Date - start;
                logger.info(resolveLogger({
                    duration: duration + 'ms',
                    reqUrl: options.url,
                    bodyLengh: data &amp;&amp; data.length
                }));
                logger.info('&lt;= Request complete successfully.');
                var resData = JSON.parse(data);
                resolve(resData);
            })
            .catch(error =&gt; {
                logger.error('=&gt; Request failed for URL:', options.url);
                reject(error);
            });
    });
}
</code></pre>

<p>My Unit Test Approach to test above controller</p>

<pre><code>it('METHOD: getFiles -&gt; should response 500 without data', done =&gt; {
    nock('http://localhost:1708/fakeapi')
        .get('/files')
        .reply(statusCodes.INTERNAL_SERVER_ERROR);

    const res = buildResponse();
    const req = httpMocks.createRequest({
        method: 'GET',
        url: '/api/submitted-data/1/files'
    });

    res.on('end', function () {
        var data = res._getData();
        expect(data).toEqual({});
        expect(statusCodes.INTERNAL_SERVER_ERROR).toBe(res.statusCode);
        done();
        nock.cleanAll();
    });

    reporterController.getFiles(req, res);
});
</code></pre>

<p>Can someone suggest me the approach I am following is acceptable or is there any better approach to do the unit test. As I am beginner to do the unit testing.</p>
",https://stackoverflow.com/questions/45921228/what-is-the-best-approach-to-unit-test-node-js-controller-which-using-a-service,"['javascript', 'node.js', 'unit-testing', 'jasmine']",2675,TRUE,13,2
Xunit test not working for mongodb service,"<p>I want to make a small XUnit test but it is not working. (<code>AddTest</code> is working but <code>GetAllRestaurantsCountShouldReturnThree</code> not working. ) </p>

<p>I am new to unit testing and I don't know about Moq and how to use it.</p>

<p>How can I mock my <code>IMongoService</code> and get restaurant count?</p>

<p>MongoService.cs</p>

<pre><code>public class MongoService : IMongoService
{

    private readonly IMongoDatabase _mongoDatabase;
    private readonly IMongoClient _mongoClient;

    public MongoService()
    {
        _mongoClient = new MongoClient(""mongodb://localhost:27017"");
        _mongoDatabase = _mongoClient.GetDatabase(""Restaurant"");
    }

    public List&lt;RestaurantDto&gt; GetAllRestaurants()
    {
        var collection = _mongoDatabase.GetCollection&lt;RestaurantDto&gt;(""Restaurant"");
        return collection.Find(_ =&gt; true).ToList();
    }
}
</code></pre>

<p>MongoServiceTest.cs</p>

<pre><code>public class ReviewServiceTests
{
    private List&lt;RestaurantDto&gt; _allRestaurants = new List&lt;RestaurantDto&gt;()
    {
        new RestaurantDto() {Name=""xxx"", ZipCode = ""111"" },
        new RestaurantDto() {Name=""yyy"", ZipCode = ""222"" },
        new RestaurantDto() {Name=""zzz"", ZipCode = ""333"" },
    };

    [Fact] //Not Working
    public void GetAllRestaurantsCountShouldReturnThree()
    {

        var _mongoService = new Mock&lt;IMongoService&gt;();
        _mongoService.Setup(x =&gt; x.GetAll()).Returns(_allRestaurants );
        var count = _mongoService.GetAll(); //GetAll() not seeing

        Assert.Equal(count, 3);

    }

    [Fact] //Working
    public void AddTest()
    {
        Assert.Equal(10, Add(8, 2));
    }

    int Add(int a, int b)
    {
        return a + b;
    }
}
</code></pre>
",https://stackoverflow.com/questions/42773422/xunit-test-not-working-for-mongodb-service,"['c#', 'mongodb', 'unit-testing', 'moq', 'xunit']",1091,TRUE,2,1
Generate XML-Report for xUnit using Visual Studio Runner,"<p>I just setup a new project (.net 4.6.2) using xUnit Tests. In order to get unit-testing in VSTS I added the visual-studio runner to the project (using nuget).</p>

<p>Now I'm wondering: how do I get XML-Reports of my testruns, so I can publish those results in VSTS?</p>
",https://stackoverflow.com/questions/46788547/generate-xml-report-for-xunit-using-visual-studio-runner,"['visual-studio-2017', 'azure-pipelines', 'xunit']",7888,TRUE,5,2
How to test React using jest with redux connect on the nested child?,"<p>If anyone could share if there's a way of unit testing react using jest with redux connect on the nested child, I prefer the easiest implementation</p>

<pre><code>import React from 'react'
import sinon from 'sinon'
import { bindActionCreators } from 'redux'
import { shallow } from 'enzyme'
import { CoreLayoutWithRedux } from '../index'
import createStore from '../../../redux/create'

describe('(Layout) Core', () =&gt; {
  let _props, _spies, _wrapper

  beforeEach(() =&gt; {
    _spies = {}
    _props = {
      store: createStore({}),
      isOnline: false,
      notifications: [],
      ...bindActionCreators({
        notificationDismiss : (_spies.notificationDismiss = sinon.spy()),
        notificationDispatch : (_spies.notificationDispatch = sinon.spy()),
        updateConnectionStatus: (_spies.updateConnectionStatus = sinon.spy())
      }, _spies.dispatch = sinon.spy())
    }
    _wrapper = shallow(&lt;CoreLayoutWithRedux {..._props}&gt;&lt;div /&gt;&lt;/CoreLayoutWithRedux&gt;)
  })

  test('Should render as a &lt;CoreLayout&gt;.', () =&gt; {
    expect(_wrapper.is('CoreLayout')).toBe(true)
  })
})
</code></pre>

<p>Here's what I have done so far, but the problem is when we need Store for the nested child</p>
",https://stackoverflow.com/questions/47787094/how-to-test-react-using-jest-with-redux-connect-on-the-nested-child,"['reactjs', 'unit-testing', 'redux', 'jestjs']",492,TRUE,-1,1
Mock/Stub a function (a npm module) with callback using Sinon,"<p>I'm using json2csv npm module to convert the json response to csv format, the code looks like below..</p>

<pre><code>json2csv({ data: data, fields: ['id', 'firstName', 'lastName'] }, function (err, csv) {
          if (err) {
            reject(err);
          } else {
            resolve(csv);
          }
        });
</code></pre>

<p>How to stub the above function using sinon so i can write unit tests for success and error scenarios. My unit testing stack is Jasmine and Istanbul.</p>
",https://stackoverflow.com/questions/46004385/mock-stub-a-function-a-npm-module-with-callback-using-sinon,"['node.js', 'angular', 'jasmine', 'sinon', 'istanbul']",396,FALSE,0,0
How to mock window.Raven with Jest,"<p>I am unit-testing a custom piece of Sentry middleware for a Redux application. The testing framework of choice is Jest. I have tried every single which way to mock out <code>window.Raven</code> and cannot get it working.</p>

<pre><code>window.Raven = {
   isSetup: jest.fn(() =&gt; false)
}
...
expect(Raven.isSetup).toHaveBeenCalled()
</code></pre>

<p>What am I missing? Do I need to use <code>jest.setMock('raven-js')</code> instead?</p>
",https://stackoverflow.com/questions/43892947/how-to-mock-window-raven-with-jest,"['javascript', 'unit-testing', 'jestjs', 'sentry']",1345,TRUE,2,3
What may cause EnumProcesses() to fail?,"<p>The <a href=""https://msdn.microsoft.com/en-us/library/windows/desktop/ms682629(v=vs.85).aspx"" rel=""nofollow noreferrer"">documentation</a> states:</p>

<blockquote>
  <p>If the function fails, the return value is zero. To get extended error
  information, call GetLastError.</p>
</blockquote>

<p>But it doesn't give any example how the function could possibly fail.</p>

<p>For unit testing I need to reliably create a situation that makes <code>EnumProcesses()</code> fail.</p>
",https://stackoverflow.com/questions/46568751/what-may-cause-enumprocesses-to-fail,"['c++', 'unit-testing', 'winapi']",668,TRUE,0,1
How can i automate testing for my database driven .Net application,"<p>I have spent the last few days learning about Unit testing. However I am looking to automate some testing for my .Net web application and am having trouble trying to workout exactly how I would go about this.</p>

<p>My web application is basically a quiz that retrieves articles, questions and multi choice answers from a SQL and then displays these to the user.</p>

<p>The web application then records the selected answers and saves them in the database.</p>

<p>From what I have read about Unit testing is that you test a single component at a time, however I don't have any complex algorithms as the app just checks if the user got the answers right or wrong.</p>

<p>What kind of automated tests can I add to my application (if any)?</p>
",https://stackoverflow.com/questions/43753898/how-can-i-automate-testing-for-my-database-driven-net-application,"['.net', 'unit-testing']",28,FALSE,1,0
Owin test server how to add a header before executing middleware,"<p>I am using OWIN middleware and I am trying to set a header that is getting set on a controller. For unit testing I am trying to set the header in the test to no avail. What is the best way to set this header? </p>

<pre><code>[TestMethod]
public async Task HasHeader()
{
        using (var server = TestServer.Create(app =&gt;
        {
            //need to set header before calling the below middleware header name is bobsyouruncle
            app.Use(typeof(HeaderMiddleware));

        }))

        using (var client = new HttpClient(server.Handler))
        {
            var response = await client.GetAsync(""http://win.example.com/bob/"");
            System.Diagnostics.Debugger.Break();
        }
}
</code></pre>
",https://stackoverflow.com/questions/44376548/owin-test-server-how-to-add-a-header-before-executing-middleware,"['c#', '.net', 'unit-testing', 'owin', 'owin-middleware']",870,FALSE,0,1
"How to add a specs for checking ion-title, ion-content with Karma/Jasmine?","<p>I am performing unit testing on Ionic2, using Karma/Jasmine.
How to write specs for ion-title and ion-content?Will it be similar to how I wrote for <strong>h4</strong> tag?</p>

<p>And can we make the custom mocks for using in the test?
<strong>homePage.html</strong></p>

<pre><code> &lt;ion-header&gt;
      &lt;ion-navbar&gt;
        &lt;ion-title&gt;
          Ionic Blank
        &lt;/ion-title&gt;
      &lt;/ion-navbar&gt;
    &lt;/ion-header&gt;

    &lt;ion-content padding&gt;
      The world is your oyster.
      &lt;p&gt;
        If you get lost, the &lt;a href=""http://ionicframework.com/docs/v2""&gt;docs&lt;/a&gt; will be your guide.
      &lt;/p&gt;
      &lt;h4&gt;Testing&lt;/h4&gt;
    &lt;/ion-content&gt;
</code></pre>

<p>homePage.spec.ts</p>

<pre><code>import { async, TestBed, ComponentFixture } from ""@angular/core/testing"";
import { HomePage } from ""./home"";
import { IonicModule, NavController } from ""ionic-angular"";
import { DebugElement } from ""@angular/core"";
import { By } from ""@angular/platform-browser"";

describe('HomePage', () =&gt; {

    let fixture: ComponentFixture&lt;HomePage&gt;;
    let comp: HomePage;
    let de: DebugElement;
    let el: HTMLElement;

    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({

            declarations: [HomePage],
            imports: [
                IonicModule.forRoot(HomePage)
            ],
            providers: [
                NavController
            ]

        }).compileComponents();
    }));

    beforeEach(() =&gt; {
        fixture = TestBed.createComponent(HomePage);
        comp = fixture.componentInstance;
        de = fixture.debugElement.query(By.css('h4'));
        el = de.nativeElement;
    });

    it('initializes', () =&gt; {
        expect(fixture).toBeTruthy();
        expect(comp).toBeDefined();
    });

    it('checks for the h4 element in the DOM', () =&gt; {
        fixture.detectChanges();
        expect(el.textContent).toContain('Testing');
    });

    it('checks the ion-title', ()=&gt;{
        //how to write a test case for checking ion-title,
          ion-content?
    });
});
</code></pre>
",https://stackoverflow.com/questions/44147727/how-to-add-a-specs-for-checking-ion-title-ion-content-with-karma-jasmine,"['ionic-framework', 'ionic2', 'karma-jasmine', 'angular2-testing']",591,FALSE,0,1
How to Unit Test a GlassController Action which Uses Sitecore.Mvc.Presentation.RenderingContext,"<p>I'm a sitecore developer and I want to create a sample sitecore helix unit testing project for testing out the logic you see in our ""EmailArticleController"" controller's Index() action method:</p>

<pre><code>using Sitecore.Mvc.Presentation;

public class EmailArticleController : GlassController
{
    //logic in below Index() method is what I want to test
    public override ActionResult Index()
    {
        var _emailArticleBusiness = new EmailArticleBusiness();
        var model = _emailArticleBusiness.FetchPopulatedModel;
        var datasourceId = RenderingContext.Current.Rendering.DataSource;
        _emailArticleBusiness.SetDataSourceID(datasourceId);

        return View(""~/Views/EmailCampaign/EmailArticle.cshtml"", model);
    }

    //below is alternative code I wrote for mocking and unit testing the logic in above Index() function
    private readonly IEmailArticleBusiness _businessLogic;
    private readonly RenderingContext _renderingContext;

    public EmailArticleController(IEmailArticleBusiness businessLogic, RenderingContext renderingContext)
    {
        _businessLogic = businessLogic;
        _renderingContext = renderingContext;
    }

    public ActionResult Index(int forUnitTesting)
    {
        var model = _businessLogic.FetchPopulatedModel;
        // *** do below two lines of logic somehow go into my Unit Testing class?  How?
        var datasourceId = _renderingContext.Rendering.DataSource;
        _businessLogic.SetDataSourceID(datasourceId);
        // *** 
        return View(""~/Views/EmailCampaign/EmailArticle.cshtml"", model);
    }
}
</code></pre>

<p>OK this is what I have in my unit testing class:</p>

<pre><code>[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void Test_EmailArticleController_With_RenderingContext()
    {
        //Arrange
        var businessLogicFake = new Mock&lt;IEmailArticleBusiness&gt;();

        var model = new EmailArticleViewModel()
        {
            ArticleControl  = new Article_Control() { },
            Metadata = new Metadata() { }
        };

        businessLogicFake.Setup(x =&gt; x.FetchPopulatedModel).Returns(model);

        // I'm not sure about the next 3 lines, how do I mock the RenderingContext and send it into the constructor, given that it needs a DataSource value too?
        var renderingContext = Mock.Of&lt;Sitecore.Mvc.Presentation.RenderingContext&gt;( /*what goes here, if anything?*/ ) {  /*what goes here, if anything?*/  };

        EmailArticleController controllerUnderTest = new EmailArticleController(businessLogicFake.Object, renderingContext);

        var result = controllerUnderTest.Index(3) as ViewResult;

        Assert.IsNotNull(result);
    }
}
</code></pre>

<p>Basically I want to mock a rendering context, make sure it has a (string) DataSource value set to some value such as ""/sitecore/home/..."", I want to send it into the controller's constructor (if that's the proper way), call the Index(int ) method, and at the same time make sure my _businessLogic, which is only an interface in this case (should it be the concrete class instead?) has its dataSource set to that same value before returning the View.  </p>

<p>What's the exact code for doing all of this?  Thanks!</p>
",https://stackoverflow.com/questions/46228915/how-to-unit-test-a-glasscontroller-action-which-uses-sitecore-mvc-presentation-r,"['c#', 'moq', 'sitecore8', 'sitecore-mvc', 'glass-mapper']",655,TRUE,1,1
Programatically check symbols loaded with assembly,"<p>I am loading an assembly with its corresponding symbol file (.pdb) using the <code>Assembly.Load(byte[], byte[])</code> method. As part of my unit testing I want to verify that the symbols have been loaded successfully.</p>

<p>Is there any way to programmatically verify this from the resulting Assembly object?</p>
",https://stackoverflow.com/questions/43590767/programatically-check-symbols-loaded-with-assembly,"['c#', '.net-assembly', 'debug-symbols']",90,FALSE,0,1
How to unit test reactjs component?,"<p>I am trying to get my head around a unit testing a 'container' component. It looks something like this:</p>

<pre><code>import React, { Component } from 'react';

interface IAppState {
  x: number;
  y: number;
  command: string;
  facing: string;
  init: boolean;
}

export class App extends Component&lt;any, IAppState&gt; {
  constructor(props) {
    super(props);
    this.state = {
      x: 0,
      y: 0,
      command: '',
      facing: 'EAST',
      init: false
    };
    this.handleKeyDown = this.handleKeyDown.bind(this);
  }

  public render() {
    const { x, y } = this.state;
    return (
      &lt;div onKeyDown={this.handleKeyDown}&gt;
        x:{x},y:{y}
      &lt;/div&gt;
    );
  }

  private handleKeyDown = (e: React.KeyboardEvent&lt;HTMLDivElement&gt;): void =&gt; {
    console.log('handlekeydown');

    switch (e.keyCode) {
      case 37:
        console.log('key left');
        this.setState({ x: this.state.x - 1 });
        break;
      case 38:
        console.log('key up');
        this.setState({ y: this.state.y + 1 });
        break;
      case 39:
        console.log('key right');
        this.setState({ x: this.state.x + 1 });
        break;
      case 40:
        console.log('key down');
        this.setState({ y: this.state.y - 1 });
        break;
    }
  };
}

</code></pre>

<p>I know how to test 'presentational' components with mocking props but how can I test 'container' components? </p>

<p>This is my unit test, how can I test the function <code>handleKeyDown</code>?</p>

<pre><code>import React from 'react';
import ReactDOM from 'react-dom';
import { createRenderer } from 'react-test-renderer/shallow';
import App from '../App';

it('does it render', () =&gt; {

    const props = {
      addTodo: jest.fn()
    }

    const renderer = createRenderer();
    renderer.render(&lt; App /&gt;)
    const output = renderer.getRenderOutput()

    //todo expect component top level type
    console.log(output)

  });
</code></pre>
",https://stackoverflow.com/questions/46783353/how-to-unit-test-reactjs-component,"['reactjs', 'unit-testing', 'mocha.js', 'jestjs', 'enzyme']",285,FALSE,1,1
How to test a method returns boolean in Mockito,"<p>I am learning how to unit-testing in android studio. As shown below, I have a method called ""isValidUrl"" and in the testing section below, I coded the testing
of that method using Mockito, but the test always fails.</p>

<p>Can you please help and guild me how to test this method?</p>

<p><strong>code</strong></p>

<pre><code>public boolean isValidUrl(String url) {
    return (url != null &amp;&amp; !url.equals("""")) ? true : false;
}
</code></pre>

<p><strong>testing</strong>:</p>

<pre><code>public class ValidationTest {
@Mock
private Context mCtx = null;

@Before
public void setUp() throws Exception {
    mCtx = Mockito.mock(Context.class);
    Assert.assertNotNull(""Context is not null"", mCtx);
}

@Test
public void isValidUrl() throws Exception {
    Validation validation = new Validation(mCtx);
    String url = null;
    Mockito.when(validation.isValidUrl(url)).thenReturn(false);
}
</code></pre>

<p>}</p>
",https://stackoverflow.com/questions/46258721/how-to-test-a-method-returns-boolean-in-mockito,"['android', 'junit', 'mockito', 'junit4', 'powermockito']",26064,TRUE,6,1
Pass the XML file content to a java method,"<p>I am doing a unit testing.</p>

<p>there is a method where xml need to be passed , in the method the parameter type is <code>String</code> I have the xml file in my laptop.</p>

<p>can some one suggest me how we can pass this xml file data to the method ?</p>
",https://stackoverflow.com/questions/44069968/pass-the-xml-file-content-to-a-java-method,"['java', 'xml', 'unit-testing']",1129,TRUE,1,1
AngularJS and QUnit: Unknown provider: LocalDataProvider &lt;- LocalData &lt;- FileLogger,"<p>Anyone who can help me fix this? I'm such a beginner in unit testing scripts.</p>

<p>Here's my html code.</p>

<pre><code>&lt;html&gt;
   &lt;head&gt;
      &lt;meta charset = ""utf-8""&gt;
      &lt;title&gt;QUnit and AngularJS&lt;/title&gt;
      &lt;link rel = ""stylesheet"" href = ""https://code.jquery.com/qunit/qunit-1.22.0.css""&gt;
  &lt;script src = ""https://code.angularjs.org/1.1.0/angular.js""&gt;&lt;/script&gt;
  &lt;script src = ""https://code.angularjs.org/1.1.0/angular-mocks.js""&gt;&lt;/script&gt;
  &lt;script src = ""https://code.jquery.com/qunit/qunit-1.22.0.js""&gt;&lt;/script&gt;
  &lt;script src = ""OfflineStorage/local-storage.service.js""&gt;&lt;/script&gt;
  &lt;script src = ""AppLogging/file-logger.service.js""&gt;&lt;/script&gt;
  &lt;script src = ""basic.js""&gt;&lt;/script&gt;
  &lt;script src = ""qunit.js""&gt;&lt;/script&gt;
   &lt;/head&gt;

  &lt;body&gt;
      &lt;div id = ""qunit""&gt;&lt;/div&gt;
      &lt;div id = ""qunit-fixture""&gt;&lt;/div&gt; 
   &lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>here's qunit js.</p>

<pre><code>var injector = angular.injector(['ng', 'FileLoggerManager']);

module(""File Logger Test"", function () {
    var svc = injector.get('FileLogger');
});
</code></pre>

<p>and here's the one that needed to be tested.</p>

<pre><code>    (function() {
    'use strict';
    angular
    .module('FileLoggerManager', [])
    .service('FileLogger', Body);

    function Body(LocalData, $q, $timeout) {
        var service = {
            writeLog: writeLog,
            SetLogLevel: SetLogLevel,
            SetFilePath: SetFilePath,
            SetMaxLogSize: SetMaxLogSize,
            DeleteLogFiles: DeleteLogFiles,
            SendLogsToEmail: SendLogsToEmail
        };

        // LOG WRITER
        var logOb;
        var logDirOb;
        var logLocation;
        var curlogsize = 0;
        var logStrings = [];
        var loggingStopped = true;

        //  DEFAULT CURRENT LOG FILE NAME
        var logfilename = ""MPC"";
        var appObj = null;
        var maxlogsize = 1000000;
        var customlogfolder = ""sdcard/"";
        var maxloglevel = 2;

        console.log(""File Logger initialized."");

        // SETTINGS
        if (LocalData.loadData('application')) {
            appObj = JSON.parse(LocalData.loadData('application'));

            // MAX LOGFILE SIZE (BYTES)
            maxlogsize = 1000000 * ( appObj.maxLogFileSize ? appObj.maxLogFileSize : 1 );

        //  LOG SAVE PATH CUSTOM FOLDER NAME
            customlogfolder = appObj.logFilePath ? appObj.logFilePath + '/' : 'sdcard/';

            //  MAX LOG LEVEL (everything below will be logged)
            maxloglevel = appObj.logLevel ? appObj.logLevel : 2;
        }

        // DEVICE READY
        document.addEventListener('deviceready', onDeviceReady, false);

        function onDeviceReady(){
            //  WRITE AND GET LOG FILE READY
            SetFilePath(customlogfolder);
        }

        // SET LOG LEVEL
        function SetLogLevel(logLevel) {
            console.log(""File Logger: Set log level to "" + logLevel);
            maxloglevel = logLevel;
        }

        // SET FILE PATH
        function SetFilePath(filePath) {
            while (filePath.indexOf('//') &gt; -1) {
                filePath = filePath.replace('//','/');
            }

            while(filePath[0] == '/') {
                filePath = filePath.substring(1);
            }

            if (filePath[filePath.length-1] != '/') {
                filePath = filePath + '/';
            }

            if (filePath.indexOf('sdcard') == 0) {
                filePath = filePath.substring(7);
            }

            customlogfolder = filePath;
            logLocation = cordova.file.externalRootDirectory + customlogfolder;
            console.log(""File Logger: Log Path = "" + customlogfolder);

            if (customlogfolder == """") {
                initializeLogFile(logLocation);
            } 
            else {
                checkIfDirectoryExist(customlogfolder, cordova.file.externalRootDirectory);
            }
        }

        /*
            CHECK IF DIRECTORY EXISTS
        */
        function checkIfDirectoryExist(filePath, rootDirLoc) {
            window.resolveLocalFileSystemURL(filePath, function(dir) {
                    console.log(""File Logger: Path found = "" + filePath);
                },
                function (dir) {
                    var curFolder = filePath;
                    var withSubDir = false;

                    if ((filePath.indexOf('/') &gt; 0) &amp;&amp; 
                        (filePath.indexOf('/') != filePath.length-1)) {
                        withSubDir = true;
                        curFolder = filePath.substring(0, filePath.indexOf('/'));
                    }

                    window.resolveLocalFileSystemURL(rootDirLoc, function(dir) {
                        dir.getDirectory(curFolder, { create: true }, function (dirEntry) {
                            console.log(""File Logger: New Directory = "" + curFolder );
                            if(withSubDir == false) {
                                initializeLogFile(logLocation);
                            }
                        },
                        function(dirEntry) {
                            console.log(""File Logger: Create Dir failed = "" + curFolder);
                        });
                    },
                    function(dir){
                        console.log(""File Logger: Root directory not found = "" + rootDirLoc);
                    });

                    if (withSubDir) {
                        filePath = filePath.substring(filePath.indexOf('/')+1);
                        checkIfDirectoryExist(filePath, rootDirLoc + curFolder + '/');
                    }
            });
        }

        // INITIALIZE AND CREATE LOG FILE
        function initializeLogFile(logLocation) {
            window.resolveLocalFileSystemURL(logLocation, function(dir) {
                logDirOb = dir;
                dir.getFile(logfilename + "".txt"", { create:true }, function(file) {         
                    logOb = file;
                    writeToLog();
                });
            });
        }

        // SET MAX SIZE
        function SetMaxLogSize (maxSize) {
            maxlogsize = 1000000 * ( maxSize? maxSize : 1 );
            console.log(""File Logger: Max File size = "" + maxlogsize);
        }

        // WRITE LOG
        function writeToLog() {
            if(!logOb){
                console.log(""File Logger: No log added."");
                return; 
            }

            if(logStrings.length == 0) {
                return;
            }

            loggingStopped = false;
            logOb.createWriter(function(fileWriter) {
                fileWriter.onwriteend = function(e) {
                    logStrings.splice(0,1);
                    if(logStrings.length == 0) {
                        loggingStopped = true;
                    }
                    else {
                        loggingStopped = false;
                        writeToLog();
                    }
                };

                var log = logStrings[0];
                fileWriter.seek(fileWriter.length); 
                var blob = new Blob([log], {type:'text/plain'});
                fileWriter.write(blob);
            }, ReadLogfail);

            CheckLogSize();
        }

        function writeLog(logLevel, str) {
            if (maxloglevel == 0) return;
            if (maxloglevel&gt;=logLevel &amp;&amp; logLevel&gt;0){
                var level;
                if(logLevel == 4)
                    level = ""DEBUG"";
                else if(logLevel == 3)
                    level = ""INFO"";
                else if(logLevel == 2)
                    level = ""WARNING"";
                else if(logLevel == 1)
                    level = ""ERROR"";

                var log = ""["" + GetLogDate() + ""] "" + level + "" : "" + str + ""\n"";
                logStrings.push(log);
                if(loggingStopped){
                    writeToLog();
                }
            }
        }

        // CHECK LOG SIZE
        function CheckLogSize(){
            logOb.file(function(file) {
                curlogsize = file.size;
                if (parseFloat(curlogsize)&gt;parseFloat(maxlogsize)) {
                    DeleteLogFiles();
                    initializeLogFile(logLocation);
                }
            }, ReadLogfail);
        }

        function ReadLogfail(e) {
            console.log(""File Logger: FileSystem Error"");
            console.dir(e);
        }

        // GET DATE (SERIAL/NORMAL)
        function GetLogDate(){
            //var monthNames = [""January"", ""February"", ""March"", ""April"", ""May"", ""June"", ""July"", ""August"", ""September"", ""October"",  ""November"", ""December""];
            var date = new Date();
            var dateYear = date.getFullYear();  
            var dateMonth = LogPad(date.getMonth()+1);
            var dateDay = LogPad(date.getDate());
            var dateHour = LogPad(date.getHours());
            var dateMinute = LogPad(date.getMinutes());
            var dateSeconds = LogPad(date.getSeconds());

            return dateYear + '.' + dateMonth + '.' + dateDay + ' ' + dateHour + ':' + dateMinute + ':' + dateSeconds;
        }

        //  ADD 0 if number is below 9
        function LogPad(n){
            return n&lt;10 ? '0'+n : n;
        }

        // DELETE LOG FILE
        function DeleteLogFiles(){
            if (!logOb) return 0;
            window.resolveLocalFileSystemURL(logLocation, function(dir) {
                logDirOb = dir;
                dir.getFile(logfilename+"".txt"", {create:true}, function(file) {         
                    file.remove(function() {
                        console.log('File logger: File removed = ' + logfilename + "".txt"");
                    });
                });     
            });
        }

        function SendLogsToEmail() {
            cordova.plugins.email.isAvailable( function (isAvailable) {
                if(isAvailable) {
                    cordova.plugins.email.open({
                        to:      '',
                        subject: 'MSCM MPC Logs',
                        body:    '',
                        attachments: [logLocation+'MPC.txt',logLocation+'MPC_COMM.txt']
                    });
                } else {
                    console.log(""No email account is setup in this device."");
                    var confirmPopup  = $ionicPopup.alert({
                        cssClass: 'custom-popup',
                        template: '&lt;div&gt;{{ ""confirm_no_email_setup"" | translate }}&lt;/div&gt;'
                    });
                };
            });
        }

        return service;
    }})();  
</code></pre>

<p>However while writing QUnit test an error occurs. ""Unknown provider: LocalDataProvider &lt;- LocalData &lt;- FileLogger"".</p>

<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/43862644/angularjs-and-qunit-unknown-provider-localdataprovider-localdata-filelog,"['angularjs', 'unit-testing', 'qunit']",42,FALSE,1,0
Grails: Setting datasource bean in applicationcontext in unit Tests,"<p>I am using grails 3.2.7 &amp; 
I am unit Testing a method that has following lines of code:</p>

<pre><code>void abc(){
ApplicationContext ctx = Holders.grailsApplication.mainContext
def dataSource = ctx.getBean('dataSource')
}
</code></pre>

<p>Inside unit test(JUnit) can anyone please help me with : <strong>How to set 'datasource' Bean in applicationContext?</strong></p>

<p>I tried:</p>

<pre><code>applicationContext.beanFactory.registerSingleton(""dataSource"", DataSource)
</code></pre>

<p>But this doesn't work.
Can anyone help me here?</p>
",https://stackoverflow.com/questions/45009522/grails-setting-datasource-bean-in-applicationcontext-in-unit-tests,"['junit', 'applicationcontext', 'grails3']",425,TRUE,1,2
Mock document.cookie using Javascript,"<p>I am using Jasmine for unit testing, and document.cookie in my code. Is it possible to mock document.cookie in my test file ?</p>

<p>I found out that I could use this : </p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>var mock = {
    value_: '', 

    get cookie() {
        return this.value_;
    },

    set cookie(value) {
        this.value_ += value + ';';
    }
};</code></pre>
</div>
</div>
</p>

<p>But I don't know how to tell Javascript that I want to use this instead of the document.cookie ? 
Is it possible ?</p>
",https://stackoverflow.com/questions/43544739/mock-document-cookie-using-javascript,"['javascript', 'cookies']",1683,FALSE,4,0
How to including angular material libraries within the karma test bed,"<p>So I am meeting an issue with Angular 4 unit testing.</p>

<p>""Failed: Uncaught (in promise): Error: Template parse errors:
Can't bind to 'mdMenuTriggerFor' since it isn't a known property of 'button'."" </p>

<p>Anyone has idea or documentation reference for including Angular Material within the karma test? Thank you!</p>
",https://stackoverflow.com/questions/45470430/how-to-including-angular-material-libraries-within-the-karma-test-bed,"['angular', 'unit-testing', 'testing', 'karma-jasmine']",737,TRUE,1,1
how to mock angularJs filter value for unit tests,"<p>I am unit testing a function in a controller which is using a translate filter
I want to mock the filter with a custom value<br>
I am using <code>$provide</code> for mocking a value but it does nothing<br>
Any advices ?<br>
Thank you very much</p>

<p>My controller :</p>

<pre><code>    function MainCtrl($scope,$filter){
        $scope.onDateChange = onDateChange;

        var date = new Date();
        var date_format_filter = $filter(""i18nFilter"")(""DATE_FORMAT_FILTER"");
        // i want this to be dd/mm/yyyy
        var date_format_moment = $filter(""i18nFilter"")(""DATE_FORMAT_MOMENT"");
         // i want this to be DD/MM/YYYY
        console.log(""DATE FORMAT"" , date_format_moment); // print DATE_FORMAT_MOMENT in unit test = test fail
        $scope.startDate = $filter('date')(date , date_format_filter);
        $scope.endDate = $filter('date')(date , date_format_filter);

        function onDateChange(whichDate){

            var startDateFormatted = moment($scope.startDate , date_format_moment).startOf('day').toDate();
            var endDateFormatted =  moment($scope.endDate, date_format_moment).startOf('day').toDate();
                if(startDateFormatted.getTime() &gt; endDateFormatted.getTime()){
                    $scope.startDateError = true;
                    $scope.errorLabel = $filter(""i18nFilter"")(""DATE_START_ERROR"");
                }else {
                    $scope.monitoring.startDateError = false;
                }
         }
    }
</code></pre>

<p>My unit test</p>

<pre><code>describe('CONTROLLER : MainCtrl', function() {  


    // MAIN VARIABLES ==================================================================
    var $scope,
        $controller,
        $rootScope,
        $filter;


    // LOAD APP MODULE =================================================================
    beforeEach(module('myApp'));


    // SETUP ===========================================================================
    beforeEach(function() {

        module(function($provide) {
            $provide.value('i18nFilter', 'DD/MM/YYYY');
        });

         inject(function ($rootScope , _$controller_ , $injector) {
                $scope          = $rootScope.$new();
                $filter = $injector.get(""$filter"");
                $controller     = _$controller_;
                $controller = $controller('MainCtrl' , {$scope : $scope  , $filter : $filter});
         });
    });

    // Controller initialization -------------------------------------------------------
    it('- Controller should be defined.', function() {
        expect($controller).toBeDefined();
    });

    it('- Should test startDate change event KO .', inject(function($controller){
        var date_format_moment = 'DD/MM/YYYY';
        $scope.startDate = moment(new Date()).add(1, 'days').format(date_format_moment);
        $scope.endDate = moment(new Date()).format(date_format_moment);
        $scope.onDateChange('startDate');
        expect($scope.startDateError).toEqual(true);
    }));
});
</code></pre>
",https://stackoverflow.com/questions/43396747/how-to-mock-angularjs-filter-value-for-unit-tests,"['angularjs', 'unit-testing', 'jasmine', 'angular-filters']",1406,TRUE,1,1
Typescript Unit Tests on imported modules only works if result is not object/array,"<p>I am trying to learn/understand how to do unit testing on typescript code and am running into an issue that I simply do not understand. </p>

<p>If I import modules into my test.ts file, the tests will run fine but only pass if the result is NOT an object or array. In those cases, the test will fail and tell me:</p>

<pre><code>AssertionError: expected { greeting: 'Hello' } to equal { greeting: 'Hello' }
</code></pre>

<p>Code:</p>

<p>hello.ts:</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>export function helloString() {
    return ""Hello"";
}
export function helloObject() {
    return {greeting: ""Hello""}
}
export function helloArray() {
    return [""Hello""]
}</code></pre>
</div>
</div>
</p>

<p>test.ts:</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>import { helloString, helloObject, helloArray } from ""./hello"";
import { expect } from ""chai""

describe(""Hello string function"", () =&gt; {
    it(""should return hello"", () =&gt; {
        const result = helloString();
        expect(result).to.equal(""Hello"");
    })
})

describe(""Hello object function"", () =&gt; {
    it(""should return hello"", () =&gt; {
        const result = helloObject();
        expect(result).to.equal({greeting: ""Hello""});
    })
})

describe(""Hello array function"", () =&gt; {
    it(""should return hello"", () =&gt; {
        const result = helloArray();
        expect(result).to.equal([""Hello""]);
    })
})</code></pre>
</div>
</div>
</p>

<p>package.json:
<div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>{
  ""name"": ""typescriptTesting"",
  ""version"": ""1.0.0"",
  ""main"": ""index.js"",
  ""license"": ""MIT"",
  ""scripts"": {
    ""test"": ""mocha -r ts-node/register src/test.ts""
  },
  ""devDependencies"": {
    ""@types/chai"": ""^3.4.35"",
    ""@types/mocha"": ""^2.2.39"",
    ""chai"": ""^3.5.0"",
    ""mocha"": ""^3.2.0"",
    ""ts-node"": ""^2.1.0"",
    ""typescript"": ""^2.2.1""
  }
}</code></pre>
</div>
</div>
</p>

<p>github repo: <a href=""https://github.com/llanginger/typescriptUnitTestsIssue"" rel=""nofollow noreferrer"">https://github.com/llanginger/typescriptUnitTestsIssue</a></p>

<p>I imagine that there's something simple I'm missing here, but having worked through multiple examples of ""typescript unit testing"" tutorials using everything from a gulp suite to karma/sinon etc. The result is always the same - if I import a function that returns an object or array, the test will fail while presenting case-passing results. Any help would be much appreciated!</p>
",https://stackoverflow.com/questions/42569460/typescript-unit-tests-on-imported-modules-only-works-if-result-is-not-object-arr,"['javascript', 'unit-testing', 'typescript', 'mocha.js', 'chai']",329,TRUE,0,1
How to check wether $interval is called with exact arguments or not in sinon.js,"<p>I want to test whether the callback function of $interval is getting called or not after a certain time interval. But I am getting the argument list as empty. I don't know why.</p>

<p>Below is the code which contains $interval - </p>

<pre><code>(function() {
    ""use strict"";

    var app = angular.module(""AppModule"");

    app.controller(""cntrl"", cntrl);

    /*@ngInject*/
    function cntrl($scope, $state, $interval, utils) {

        var vm = this,
            data,
            timer,
            i;

        init();

        function init() {
            _createList();
        }

        /*Refreshing list after each 30 second interval*/
        timer = $interval(function() {

            utils.getObjectList()
                .then(function(data) {
                    utils.data = data;
                });

            init();

        }, 1000);

        /*Cancelling interval when scope is destroy*/
        $scope.$on('$destroy', function() {
            $interval.cancel(timer);
        });

        function _createList() {

            //some code            

        }
    }

})();
</code></pre>

<p>Below is the unit testing for it - </p>

<pre><code>describe.only(""Unit Controller: cntrl"", function() {
    ""use strict"";

    // Angular injectables
    var $q, $httpBackend, $injector, $controller, $rootScope, $state, $location, $templateCache, $compile, $interval;

    // Module defined (non-Angular) injectables
    var $scope;

    // Local variables used for testing
    var vm;

    // Initialize modules
    beforeEach(function() {
        module(""AppModule"");
    });

    beforeEach(function() {

        var templateHtml;

        inject(function(_$q_, _$controller_, _$rootScope_, _$state_, _$location_, _$templateCache_, _$compile_, _$interval_) {
            $q = _$q_;
            $controller = _$controller_;
            $rootScope = _$rootScope_;
            $location = _$location_;
            $state = _$state_;
            $templateCache = _$templateCache_;
            $compile = _$compile_;
            $interval = _$interval_;

            $scope = $rootScope.$new();
            templateHtml = $templateCache.get(""/modules/list.html"");

            $compile(templateHtml)($scope);
        });

    });

    beforeEach(function() {

        vm = $controller(""cntrl"", {
            $scope: $scope
        });

    });

    it(""Should call the list API continuosly after a certain interval"", function() {

        var fn = function() {

            utils.getObjectList()
                .then(function(data) {
                    utils.data = data;
                });

            init();

        };

        var clock = sinon.useFakeTimers();
        var mySpy = sinon.spy($interval);
        var throttled = throttle(mySpy);

        throttled();

        clock.tick(999);
        console.log(mySpy);
        expect(mySpy.notCalled).to.be.true;

        clock.tick(1);
        expect(mySpy.called).to.be.true;

        expect(intervalSpy.calledWith(fn)).to.be.true; //This is failing

        console.log(intervalSpy.getCall(0).args); //this shows empty. 

        function throttle(callback) {
            var timer;
            return function() {
                clearTimeout(timer);
                var args = [].slice.call(arguments);
                timer = setTimeout(function() {
                    callback.apply(this, args);
                }, 1000);
            };
        }
    });

});
</code></pre>
",https://stackoverflow.com/questions/41460151/how-to-check-wether-interval-is-called-with-exact-arguments-or-not-in-sinon-js,"['javascript', 'angularjs', 'unit-testing', 'sinon-chai']",118,FALSE,0,0
How to run Typescript (not AngularJs) unit tests with Jasmine and Webpack,"<p>There is a ton of information on how to unit test with Webpack and Jasmine for Angular projects.</p>

<p>But I have a project that uses 'plain' typescript, not AngularJs. So I have ts classes, but I don't use components. 
I cannot figure out how to apply the information I'm finding to a non-AngularJs project; everything seems geared toward using components.</p>

<p><strong>How do I integrate Jasmine (ts spec files) in a Typescript Webpack project?</strong></p>

<p>I'd prefer a solution that uses a separate webpack config for the tests. </p>

<h2>My setup/what I have to work with:</h2>

<p><strong>package.json</strong>
Start script launches node with dev-build</p>

<pre><code>{
  ""name"": ""webpack.typescript"",
  ""version"": ""1.0.0"",
  ""description"": ""Webpack + TypeScript"",
  ""main"": ""dev-build.js"",
  ""author"": ""Shane Osbourne and John Lindquist"",
  ""license"": ""MIT"",
  ""scripts"": {
    ""start"": ""node dev-build""
  },
  ""dependencies"": {
    ""bootstrap"": ""^3.3.7"",
    ""lodash"": ""^4.17.4""
  },
  ""devDependencies"": {
    ""@types/lodash"": ""^4.14.53"",
    ""browser-sync"": ""^2.18.8"",
    ""bs-pretty-message"": ""^1.0.8"",
    ""css-loader"": ""^0.26.2"",
    ""node-sass"": ""^4.5.0"",
    ""sass-loader"": ""^6.0.2"",
    ""style-loader"": ""^0.13.2"",
    ""ts-loader"": ""^2.0.1"",
    ""typescript"": ""^2.2.1"",
    ""url-loader"": ""^0.5.8"",
    ""webpack"": ""^2.2.1"",
    ""webpack-dev-middleware"": ""^1.10.1""
  }
}
</code></pre>

<p><strong>dev-build.js</strong>
Load config, bundle, and start BrowserSync.</p>

<pre><code>/**
 * Require Browsersync along with webpack and middleware for it
 */
var browserSync          = require('browser-sync').create();
var webpack              = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');

/**
 * Require ./dev-webpack.config.js and make a bundler from it
 */
var webpackConfig = require('./dev-webpack.config');
var bundler       = webpack(webpackConfig);

/**
 * Reload all devices when bundle is complete
 * or send a fullscreen error message to the browser instead
 */
bundler.plugin('done', function (stats) {
    if (stats.hasErrors() || stats.hasWarnings()) {
        return browserSync.sockets.emit('fullscreen:message', {
            title: ""Error"",
            timeout: 100000
        });
    }
    browserSync.reload();
});

/**
 * Run Browsersync and use middleware for Hot Module Replacement
 */
browserSync.init({
    server: 'app',
    open: false,
    logFileChanges: false,
    middleware: [
        webpackDevMiddleware(bundler, {
            publicPath: webpackConfig.output.publicPath,
            stats: {colors: true}
        })
    ],
    plugins: ['bs-pretty-message'],
    files: [
        'app/css/*.css',
        'app/*.html'
    ]
});
</code></pre>

<p><strong>dev-webpack.config.js</strong>
Handle Typescript and scss. (I was thinking I should have a test-webpack.config.js)</p>

<pre><code>var webpack = require('webpack');
var path = require('path');

module.exports = {
  devtool: '#inline-source-map',

  entry: [
    './src/main.ts',
    './src/main.scss'
  ],

  output: {
    path: path.join(__dirname, 'app'),
    publicPath: '/',
    filename: 'dist/bundle.js'
  },

  plugins: [
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.LoaderOptionsPlugin({
      debug: true
    })
  ],

  resolve: {
    extensions: ['.ts', '.js', '.scss']
  },

  module: {
    rules: [
      {
        test: /\.ts$/, use: [{
          loader: 'ts-loader'
        }]
      },
      {
        test: /\.woff($|\?)|\.woff2($|\?)|\.ttf($|\?)|\.eot($|\?)|\.svg($|\?)/,
        use: [{
          loader: 'url-loader'
        }]
      },
      {
        test: /\.scss$/,
        use: [{
          loader: ""style-loader""
        }, {
          loader: ""css-loader"", options: {
            sourceMap: true
          }
        }, {
          loader: ""sass-loader"", options: {
            sourceMap: true
          }
        }]
      }
    ],
  }
};
</code></pre>

<p>What I've found:</p>

<p><a href=""https://dzone.com/articles/unit-testing-with-webpack-amp-mocha"" rel=""nofollow noreferrer"">https://dzone.com/articles/unit-testing-with-webpack-amp-mocha</a></p>

<p><a href=""https://stackoverflow.com/questions/39487487/unit-testing-with-webpack-jasmine-core-typescript"">Unit testing with Webpack, Jasmine (-core), typescript</a></p>

<p><a href=""https://stackoverflow.com/questions/38269907/jasmine-spec-as-typescript-file?rq=1"">Jasmine Spec as Typescript File</a></p>

<p><a href=""https://stackoverflow.com/questions/35840541/typescript-compilation-failure-and-karma-test-execution?rq=1"">TypeScript compilation failure and Karma test execution?</a></p>

<p><a href=""https://stackoverflow.com/questions/35290176/executing-typescript-jasmine-tests-via-webpack-terminal-to-test-angular2?rq=1"">Executing Typescript Jasmine tests via Webpack (Terminal) to test Angular2</a></p>
",https://stackoverflow.com/questions/42585255/how-to-run-typescript-not-angularjs-unit-tests-with-jasmine-and-webpack,"['unit-testing', 'typescript', 'webpack', 'jasmine']",6232,TRUE,10,2
cakephp 3 undefined property cookie component unit test,"<p>I tried to test my component function through unit testing.
My component function below</p>

<pre><code>public function userRole() { 

    $loginId = $this-&gt;Cookie-&gt;read('Admin.login_id');
    $name = $this-&gt;Cookie-&gt;read('Admin.name'); 
    $role = $this-&gt;Cookie-&gt;read('Admin.role'); 
    if (empty($loginId) || empty($name)){ 
        return false; 
    }

    $adminsORM = TableRegistry::get('Admins');
    $admin = $adminsORM-&gt;find('all', [
        'conditions' =&gt; ['login_id' =&gt; $loginId, 'name' =&gt; $name, 'disable' =&gt; 0]
    ])-&gt;first(); 



    return empty($admin)? false : $admin-&gt;role; 
}
</code></pre>

<p>And my component testing function below</p>

<pre><code>public $Acl;

public function setUp()
{
    parent::setUp();
    $registry = new ComponentRegistry();
    $this -&gt;Acl = new AclComponent($registry);
}

public function testUserRole()
{
    // Test our adjust method with different parameter settings       
        $this-&gt;Cookie-&gt;write('Admin.login_id', 'demo12');
        $this-&gt;Cookie-&gt;write('Admin.role', 1);        
        $this-&gt;Cookie-&gt;write('Admin.name', 'demo 12');   
    $output = $this-&gt;Acl-&gt;userRole();
    $this-&gt;assertResponseOk();

}
</code></pre>

<p>composer testing code</p>

<pre><code>vendor/bin/phpunit --filter testUserRole /d/xampp/htdocs/admin/admin/tests/TestCase/Controller/Component/AclComponentTest.php
</code></pre>

<p>error</p>

<blockquote>
  <p>Notice Error: Undefined property: App\Test\TestCase\Controller\Component\AclComponentTest::$Cookie in [D:\xampp\htdocs\admin\admin\tests\TestCase\Controller\Component\AclComponentTest.php, line 31]</p>
</blockquote>
",https://stackoverflow.com/questions/46825934/cakephp-3-undefined-property-cookie-component-unit-test,"['unit-testing', 'cakephp', 'cookies', 'phpunit', 'cakephp-3.0']",824,TRUE,2,2
Using Catch2 in Visual C++ 2015,"<p>I'm trying to make a Unit Testing project using the Catch framework, but am faced with Link errors.</p>

<p>I've set up the project as follows:</p>

<ol>
<li>Create a Native Unit Test project</li>
<li>Add Catch to the include directories</li>
<li>Add <code>#include &lt;catch.hpp&gt;</code> to stdafx.h</li>
<li>Write the following simple source file</li>
</ol>

<p>unittest.cpp:</p>

<pre><code>#include ""stdafx.h""
namespace Catch2_Test
{
  TEST_CASE(""Y U no work"")
  {
    REQUIRE(1);
  }
}
</code></pre>
",https://stackoverflow.com/questions/47146170/using-catch2-in-visual-c-2015,"['c++', 'visual-studio', 'unit-testing', 'catch-unit-test']",5444,TRUE,0,2
Stub an internal functions?,"<p>I want to stub a internal function in my code when unit testing it, example:</p>

<pre><code>//foobar.js
const uuid = require('uuid');

function foo() {
    console.log('uuid: ' + uuid.v4());
    // Lots of timers
}
exports._foo = foo;

function bar() {
    //Logic...
    foo();
    //Logic...
}
exports.bar = bar;
</code></pre>

<p>And the unit test:</p>

<pre><code>// test/foobar.js
const chai = require('chai'),
    expect = chai.expect,
    proxyquire = require('proxyquire'),
    sinon = require('sinon');

describe('bar', () =&gt; {
    it('call foo', () =&gt; {
        let foo = proxyquire('./foo.js', {
                uuid: {
                    v4: () =&gt; {
                        return '123456789';
                    }
                }
            }),
            fooSpy = sinon.spy(foo._foo);

        foo.bar();
        expect(fooSpy.calledOnce);
    });
});
</code></pre>

<p>Now, when unit testing <code>bar</code>, I can spy on <code>foo</code> just fine, and it is quite fine.<br>
However, the real <code>foo</code> make a lot of time consuming calls (DB calls, file IO...), and while I could use proxyquire to stub all <code>fs</code> and db calls to terminate immediately, that would duplicate code from the test of <code>foo</code>, be unreadable, and being bad altogether.</p>

<p>The simple solution would be to stub <code>foo</code>, but proxyquire doesn't seems to like that. A naive <code>foo._foo = stubFoo</code> didn't worked either. Rewire doesn't seems to handle this either.</p>

<p>What I could do would be to make a file that import and export foobar.js, and use proxyquire on it, but the idea itself is already bad.</p>

<p>How can I stub the <code>foo</code> function when testing <code>bar</code>?</p>
",https://stackoverflow.com/questions/45755318/stub-an-internal-functions,"['javascript', 'node.js', 'unit-testing', 'mocha.js', 'stubbing']",786,FALSE,3,1
Angular 1.x Jasmine testing directive that uses variable from `controller As` syntax,"<p>I am trying to test a directive using Jasmine + Karma and for other ones I have tested they have worked no problem. However this template has <code>ng-if=""vm.validUser""</code>. The template I grab using <code>$templateCache.get()</code> shows that the template is in fact grabbed. The problem is using <code>$compile</code> the <code>element.html()</code> will come up undefined in the <code>expect</code> test. I am trying to set the <code>scope.vm.validUser = true</code> or <code>scope.controller.validUser = true</code> as <code>vm</code> is just a reference but both are not working.</p>

<p><strong>Template</strong> (Shortend to show relative information):</p>

<pre><code>&lt;section ng-cloak ng-if=""vm.validUser""&gt;
  &lt;!-- more HTML --&gt;
&lt;/section&gt;
</code></pre>

<p>Controller:</p>

<pre><code>// More JS
var vm = this;
vm.validUser = false;
// More JS
</code></pre>

<p><strong>Jasmine Test Suite:</strong></p>

<pre><code>controller = _$controller_('userController as vm',
{
  $scope: scope,
  $element: element,
  UserFactory:  _UserFactory_
});

template = $templateCache.get('pathToTemplate'); // Create instance of template

scope.vm={
  validUser : true
};

element = _$compile_(template)(scope);
scope.$digest(); // will run watchers and resolve angular expressions in template

describe('userPage.tpl.html tests', function() {

  it('should have template defined', function() {

    console.log(""TEST,"", template);
    console.log(""TEST 2"", scope.vm);
    console.log(""TEST 3"", element);

    expect(element.html()).toBeDefined()
});
</code></pre>

<p><strong>Results:</strong> </p>

<p>As you can see I have three console logs in my test. The first one for <code>template</code> shows the entire html as expected. The second shows that <code>validUser</code> does equal <code>true</code>. <code>Element</code> shows the result of <code>LOG: 'Test 3', {0: &lt;!-- ngIf: vm.validUser--&gt;, length: 1}</code>. </p>

<p>The actual <code>expect</code> test fails and states ""Expected undefined to be defined""</p>

<p>To my understanding, and from what I have read, this should be working.</p>

<p>Links I found Helpful:</p>

<ul>
<li><a href=""http://blog.cdh.com/unit-testing-angularjs-directives-with-external-templates"" rel=""nofollow noreferrer"">http://blog.cdh.com/unit-testing-angularjs-directives-with-external-templates</a></li>
<li><a href=""http://derpturkey.com/unit-testing-directives-in-angular/"" rel=""nofollow noreferrer"">http://derpturkey.com/unit-testing-directives-in-angular/</a></li>
<li><a href=""http://busypeoples.github.io/post/testing-angularjs-directives/"" rel=""nofollow noreferrer"">http://busypeoples.github.io/post/testing-angularjs-directives/</a></li>
<li><a href=""https://www.sitepoint.com/understanding-angulars-apply-digest/"" rel=""nofollow noreferrer"">https://www.sitepoint.com/understanding-angulars-apply-digest/</a></li>
<li><a href=""https://www.yearofmoo.com/2013/01/full-spectrum-testing-with-angularjs-and-karma.html#testing-directives"" rel=""nofollow noreferrer"">https://www.yearofmoo.com/2013/01/full-spectrum-testing-with-angularjs-and-karma.html#testing-directives</a></li>
<li><a href=""http://daginge.com/technology/2014/03/03/testing-angular-directive-controllers-with-jasmine-and-karma/"" rel=""nofollow noreferrer"">http://daginge.com/technology/2014/03/03/testing-angular-directive-controllers-with-jasmine-and-karma/</a></li>
<li><a href=""https://stackoverflow.com/questions/24837571/get-compiled-template-for-controller-in-unit-test"">Get compiled template for controller in unit test</a></li>
<li><a href=""http://daginge.com/technology/2013/12/14/testing-angular-templates-with-jasmine-and-karma/"" rel=""nofollow noreferrer"">http://daginge.com/technology/2013/12/14/testing-angular-templates-with-jasmine-and-karma/</a></li>
<li><a href=""http://blog.cdh.com/unit-testing-angularjs-directives-with-external-templates"" rel=""nofollow noreferrer"">http://blog.cdh.com/unit-testing-angularjs-directives-with-external-templates</a></li>
</ul>
",https://stackoverflow.com/questions/44728065/angular-1-x-jasmine-testing-directive-that-uses-variable-from-controller-as-sy,"['javascript', 'angularjs', 'angularjs-directive', 'jasmine', 'karma-jasmine']",137,FALSE,1,0
TypeError: modules[moduleId] is undefined,"<p>I am trying to run jasmine unit testing with Jenkins using Firefox browser on Linux and I keep having this behavior:</p>

<pre><code>[32m02 08 2017 08:16:26.443:INFO [Firefox 50.0.0 (Windows 8.1 0.0.0)]:  [39mConnected on socket /#KYlvgi9JYtXnD1jZAAAB with id manual-931
Firefox 50.0.0 (Windows 8.1 0.0.0) ERROR
  TypeError: modules[moduleId] is undefined
  at http://52.5.4.155:9876/_karma_webpack_/inline.bundle.js:55
Firefox 50.0.0 (Windows 8.1 0.0.0) ERROR
  TypeError: modules[moduleId] is undefined
  at http://52.5.4.155:9876/_karma_webpack_/inline.bundle.js:55


[33m02 08 2017 08:21:27.750:WARN [Firefox 50.0.0 (Windows 8.1 0.0.0)]:  [39mDisconnected (1 times)
Firefox 50.0.0 (Windows 8.1 0.0.0) ERROR
Disconnectedundefined
Firefox 50.0.0 (Windows 8.1 0.0.0) ERROR
Disconnectedundefined
</code></pre>

<p>The exception is on this Line of code:</p>

<pre><code>// Execute the module function
/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
</code></pre>

<p>I research a lot about the issue, but I couldn't find any solution. Is there anyone that can help me to solve it. </p>
",https://stackoverflow.com/questions/45467087/typeerror-modulesmoduleid-is-undefined,"['javascript', 'firefox', 'jenkins', 'karma-jasmine']",10324,FALSE,5,1
nyc coverage shows incorrect line numbers,"<p>My group is building an application with the following front-end stack:</p>

<ul>
<li>VueJS</li>
<li>Webpack 2.2</li>
<li>AvaJS (for unit testing)</li>
<li>nyc (Istanbul) for test coverage</li>
</ul>

<p>We started off with <code>vue-cli</code> to create a Webpack template for our project. For the most part everything has gone smoothly. We are able to use Ava for unit testing separate <em>.vue</em> component files using <em>vue-node</em> However there is a problem with the test coverage report generated through <em>nyc</em>. Below is a snippet of our <em>package.json</em> file with the relevant nyc and ava sections defined:</p>

<pre><code>""nyc"": {
    ""exclude"": [
        ""build"",
        ""config"",
        ""static"",
        ""tests""
    ],
    ""extension"": [
        "".js"",
        "".vue""
    ]
},
""ava"": {
    ""require"": [
        ""./tests/unit/helpers/setup.js"",
        ""ignore-styles""
    ]
},
</code></pre>

<p>All the tests pass successfully. The <code>nyc</code> report shows the following:
<a href=""https://i.stack.imgur.com/HIWnq.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/HIWnq.png"" alt=""nyc generated report""></a></p>

<p>The problem is that the line #s listed under <em>Uncovered Lines</em> don't exist. The <em>.vue</em> file is only 402 lines long so I can't figure out where these line #s in the nyc report are coming from.</p>

<p>Any help would be appreciated and thank you in advance.</p>
",https://stackoverflow.com/questions/44120502/nyc-coverage-shows-incorrect-line-numbers,"['unit-testing', 'vue.js', 'istanbul', 'ava']",3787,TRUE,5,1
Python Unittest: TypeError: __init__() missing,"<p>I am very new to Unit Testing in Python. I was writing a unit test for a very small method. The code implementation is a follows. But if I run the test script, I get an error saying : </p>

<blockquote>
  <p>TypeError: <code>__init__()</code> missing 4 required positional arguments: 'x ,'y','z','w' </p>
</blockquote>

<pre><code>class get_result():
    def __init__(self,x,y,z,w):
        self.x=x
        self.y=y
        self.z=z
        self.w=w


    def generate_result(self):
        curr_x= 90
        dist= curr_x-self.x
        return dist


import unittest
from sample import get_result
result = get_result()

class Test(unittest.TestCase):

    def test_generate_result(self):
        self.assertEqual(somevalue, result.generate_result())
</code></pre>
",https://stackoverflow.com/questions/45886509/python-unittest-typeerror-init-missing,"['python', 'unit-testing']",1547,TRUE,1,2
"Unity, Moq, and NUnit - Controller Constructor with Parameters Not Recognized in Tests","<p>I am very new to unit testing, so I apologize if this is not a very good question.</p>

<p>I have a main web project, and an accompanying NUnit tests library. I am using Unity to inject interfaces into my controller within the main project. For example:</p>

<pre><code>    public class EquipmentController : Controller
{
    private readonly ILocationRepository locationContext = null;
    private readonly IRepository&lt;EquipmentCategory&gt; categoryContext = null;
    private readonly IEquipmentRepository equipmentContext = null;
    private readonly IRecordRepository recordContext = null;

    public EquipmentController(ILocationRepository locationRepo, IRepository&lt;EquipmentCategory&gt; categoryRepo, IEquipmentRepository equipmentRepo, IRecordRepository recordRepo)
    {
        this.locationContext = locationRepo;
        this.categoryContext = categoryRepo;
        this.equipmentContext = equipmentRepo;
        this.recordContext = recordRepo;
    }
</code></pre>

<p>The web application itself actually works as expected. However, I am encountering issues while trying to write test cases. For example, in test library, I have the following:</p>

<pre><code>using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.Unity.Mvc;
using Microsoft.Practices.Unity.ObjectBuilder;
using Microsoft.Practices.Unity.StaticFactory;
using Moq;
using ITEquipmentDatabase;
using ITEquipmentDatabase.Models;
using ITEquipmentDatabase.Controllers;

namespace ITEquipmentDatabase.Tests
{
    [TestFixture]
    public class EquipmentController
    {
        [Test]
        public void TestMethod()
        {
            var equipRepo = new Mock&lt;IEquipmentRepository&gt;();
            var categoryRepo = new Mock&lt;IRepository&lt;EquipmentCategory&gt;&gt;();
            var locationRepo = new Mock&lt;ILocationRepository&gt;();
            var recordRepo = new Mock&lt;IRecordRepository&gt;();

            EquipmentController controller = new EquipmentController(locationRepo.Object, categoryRepo.Object, equipRepo.Object, recordRepo.Object);



        }
    }
}
</code></pre>

<p>However, I am receiving the following error:</p>

<pre><code>Error   1   'ITEquipmentDatabase.Tests.EquipmentController' does not contain a constructor that takes 4 arguments   C:\Users\Khandokar\Documents\Visual Studio 2013\Projects\IT Equipment Log\ITEquipmentDatabase.Tests\EquipmentController.cs  27  46  ITEquipmentDatabase.Tests
</code></pre>

<p>I have Unity referenced in my tests project and even added Bootstrapper.cs (not sure if it was necessary, but I was trying to resolve the above issue). I am quite sure I am doing something very wrong, but I am just starting to venture into unit testing and am having a bit of a difficult time.</p>

<p>Thanks for any advice.</p>
",https://stackoverflow.com/questions/43788802/unity-moq-and-nunit-controller-constructor-with-parameters-not-recognized-in,"['c#', 'unit-testing', 'unity-container']",650,TRUE,2,1
Testing framework for C# WPF application,"<p>I have already created C# WPF application and I would like to create test application for same. 
I have searched for that on Internet, I have found below test framework : </p>

<ul>
<li><p>Nunit</p></li>
<li><p>Robot framework</p></li>
<li>Unit testing</li>
</ul>

<p>I am confused to select the best test framework for C# WPF application. 
Can you please suggest me </p>
",https://stackoverflow.com/questions/47386877/testing-framework-for-c-wpf-application,"['c#', 'wpf', 'automated-tests']",3624,TRUE,4,3
OCMOCK iOS how to test if property is called?,"<p>I use <a href=""http://ocmock.org/"" rel=""nofollow noreferrer"">OCMOCK</a> to build unit test for my plugin.</p>

<p>I have Singleton class <code>MyClass</code> with some property:</p>

<pre><code>@property (nonatomic, strong, setter=setUserID:) NSString *userID;
</code></pre>

<p>I want to validate if <code>[MyClass shared].userID</code> is called.</p>

<p>Im able to run unit testing for setter a.e. <code>setUserID</code>.</p>

<pre><code>id myClassMock = [OCMockObject partialMockForObject:[MyClass shared]];

OCMExpect([myClassMock setUserID:[OCMArg isNotNil]]);

[[MyClass shared] setUserID:@""someUserId""];

OCMVerifyAll(myClassMock);
myClassMock = nil;
</code></pre>

<p>But how can I test for property <code>userID</code>?</p>

<p>In real code I set this properly as:</p>

<pre><code>[MyClass shared].userID = @""some id"";
</code></pre>

<p>Thanks,</p>
",https://stackoverflow.com/questions/42734451/ocmock-ios-how-to-test-if-property-is-called,"['ios', 'unit-testing', 'mocking']",108,FALSE,1,0
Selenium server did not start.Another Selenium process may already be running or your java version may be out of date,"<p>Just starting out with Polymer and Unit Testing. I was trying out the activity on this page <a href=""https://www.polymer-project.org/2.0/docs/tools/tests"" rel=""nofollow noreferrer"">https://www.polymer-project.org/2.0/docs/tools/tests</a> but I couldn't get <code>polymer test</code> to run. So I tried running <code>polymer test --verbose</code> and end up getting this error:</p>

<p><code>
Error: Selenium server did not start.Another Selenium process may already be running or your java version may be out of date.</p>

<p>error:   cli runtime exception: Error: Selenium server did not start.Another Selenium process may already be running or your java version may be out of date.
error:   Error: Selenium server did not start.Another Selenium process may already be running or your java version may be out of date.
    at ChildProcess.errorIfNeverStarted (C:\Users\Eleonor Somosot\AppData\Roaming\npm\node_modules\polymer-cli\node_modules\selenium-standalone\lib\start.js:141:15)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:215:12)
</code></p>

<p>Hoping someone could help me with this and maybe explain. Thanks..</p>
",https://stackoverflow.com/questions/44511912/selenium-server-did-not-start-another-selenium-process-may-already-be-running-or,"['unit-testing', 'selenium', 'polymer', 'polymer-cli']",4559,TRUE,2,1
Mock child component in React,"<p>Is there a clean way to be able to mock a child element when unit testing an element, using Mocha and friends?</p>

<p>For example, say I have something like this:</p>

<pre><code>&lt;Parent&gt;
  &lt;Child aProp={ this.props.clickChild() }/&gt;
&lt;/Parent&gt;
</code></pre>

<p>I want to mock it so I can manually trigger <code>aProp</code> and then tell that it called the <code>clickChild</code> that I passed it.</p>
",https://stackoverflow.com/questions/42562169/mock-child-component-in-react,"['unit-testing', 'reactjs', 'enzyme']",7747,TRUE,2,1
Angular: Unit test that a component&#39;s output is not emitted,"<p>Let's say I have a component like the following:</p>
<pre class=""lang-js prettyprint-override""><code>@Component({
  selector: 'example',
  template: ` `
})
export class ExampleComponent {
  value: any;
  @Output() output: EventEmitter&lt;any&gt; = new EventEmitter();

  onValueChange(newValue: any) {
    if (newValue !== this.value) {
      this.value = newValue;
      this.output.emit(newValue);
    }
  }
}
</code></pre>
<p>I've written a test like the one below. I want to test that if <code>onValueChange</code> is called with the same value as <code>value</code>, the component will not output the duplicate value. Is there a best practice for unit testing that an observable subscription is never called? While what I did technically works, it feels a little hacky.</p>
<pre class=""lang-js prettyprint-override""><code>describe('ExampleComponent', () =&gt; {
  it('should not output duplicate values', () =&gt; {
    const component = new ExampleComponent();
    component.value = 1;
    component.output.subscribe(value =&gt; {
      // if the output is not triggered then we'll never reach this 
      // point and the test will pass
      expect(true).toEqual(false);
    });
    component.onValueChange(1);
  });
});
</code></pre>
",https://stackoverflow.com/questions/46817783/angular-unit-test-that-a-components-output-is-not-emitted,"['angular', 'jasmine', 'rxjs']",18203,TRUE,13,2
How to write unit test cases for session variables in laravel 5.4,"<p>Hello I have a test case which will call a route and it will return some data if the session will set.
Here is my test case</p>

<pre><code>class TestControllerTest extends TestCase
{
    // ...

    public function testResponseOfJson()
    {
        $response = $this-&gt;call('GET', 'profile/test');
        $this-&gt;assertEmpty( !$response );
    }

    // ...
}
</code></pre>

<p>and here is my controller</p>

<pre><code>Class TestController{
   public function sendResponse(Request $request){
     $this-&gt;data['user_id'] = $this-&gt;request-&gt;session()-&gt;get('userdata.userid'); 
if($this-&gt;data['userid']){
   return data;
}
else{ 
   return Failed;
     }
   }
}
</code></pre>

<p>My routes.php</p>

<pre><code>Route::get('profile/test',['uses'=&gt;'TestController@sendResponse']);
</code></pre>

<p>how can i set the session variable userdata.userid and get while doing unit testing. </p>
",https://stackoverflow.com/questions/44539331/how-to-write-unit-test-cases-for-session-variables-in-laravel-5-4,"['laravel-5', 'phpunit']",2239,TRUE,0,1
How can I write Test Unit for CRUD in MVC5 / Entity Framework 6?,"<p>I am new to ASP.NET MVC and unit testing, I don't know how can I write a test method for these methods:</p>

<pre><code>// GET: Worts/Details
public ActionResult Details(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    var wort = (from s in db.Worts
                where s.ID == id
                select s).FirstOrDefault();

    if (wort == null)
    {
        return HttpNotFound();
    }

    return View(wort);
}

// GET: Worts/Create
public ActionResult Create()
{
    return View();
}

// POST: Worts/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = ""ID,Title,CreateDate,ClickCount,DislikeCount,LikeCount, Creator_ID"")] Wort wort)
{
    if (ModelState.IsValid)
    {
        wort.CreateDate = DateTime.Now;
        wort.ClickCount = 0;
        wort.DislikeCount = 0;
        wort.LikeCount = 0;

        var userId = User.Identity.GetUserId();
        wort.Creator = db.Users.Where(x =&gt; x.ID == userId).FirstOrDefault();

        db.Worts.Add(wort);
        db.SaveChanges();

        try
        {
            this.mailSender.SendEmail(wort);
            return RedirectToAction(""Index"");
        }
        catch (Exception)
        {
            throw;
        }
    }
    return View(wort);
}

// GET: Worts/Edit/5
public ActionResult Edit(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    Wort wort = db.Worts.Find(id);

    if (wort == null)
    {
        return HttpNotFound();
    }
    return View(wort);
}

// POST: Worts/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = ""ID,Title,CreateDate"")] Wort wort)
{
    if (ModelState.IsValid)
    {
        db.Entry(wort).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction(""Index"");
    }

    return View(wort);
}

// GET: Worts/Delete/5
public ActionResult Delete(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    Wort wort = db.Worts.Find(id);

    if (wort == null)
    {
        return HttpNotFound();
    }
    return View(wort);
}

// POST: Worts/Delete/5
[HttpPost, ActionName(""Delete"")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
    Wort wort = db.Worts.Find(id);
    db.Worts.Remove(wort);
    db.SaveChanges();
    return RedirectToAction(""Index"");
}
</code></pre>

<p>I have written this code for testing, but it is not enough.</p>

<pre><code>[TestMethod]
public void Details()
{
        // Arrange
        WortsController controller = new WortsController();

        int id = 22;

        // Act
        ViewResult result = controller.Details(id) as ViewResult;

        // Assert
        Assert.IsNotNull(""Details"", result.ViewName);
}

[TestMethod]
public void Create()
{
        // Arrange
        WortsController controller = new WortsController();

        // Act
        ViewResult result = controller.Create(new LikeWort.Models.Wort()) as ViewResult;

        // Assert
        Assert.IsNotNull(result);
}

[TestMethod]
public void Edit(int? id)
{
        // Arrange
        WortsController controller = new WortsController();

        // Act
        ViewResult result = controller.Edit(id) as ViewResult;

        // Assert
        Assert.IsNotNull(result);
}

[TestMethod]
public void Delete(int? id)
{
        // Arrange
        WortsController controller = new WortsController();

        // Act
        ViewResult result = controller.Delete(id) as ViewResult;

        // Assert
        Assert.IsNotNull(result);
}
</code></pre>

<p>Can anyone help me to write correct and complete test units for these methods? </p>
",https://stackoverflow.com/questions/41767700/how-can-i-write-test-unit-for-crud-in-mvc5-entity-framework-6,"['c#', 'asp.net-mvc', 'unit-testing']",1499,TRUE,0,3
Jest React-native How to mock a function and return a response,"<p>I am new to Jest unit testing.</p>

<p>I want to test a component that <strong>makes multiple calls</strong> to the <a href=""https://facebook.github.io/react-native/docs/geolocation.html"" rel=""nofollow noreferrer"">Geolocation</a> getCurrentPosition() method.</p>

<p><strong>For each call to the function I want to return a new coordinate object.</strong></p>

<p>I have read various articles and tutorials but I am still struggling.</p>

<p>Any Ideas?</p>
",https://stackoverflow.com/questions/42599274/jest-react-native-how-to-mock-a-function-and-return-a-response,"['unit-testing', 'react-native', 'jestjs']",1487,TRUE,2,1
Unit test for a component in angularJS 1.X (karma and Jasmine),"<p>I have the component in angularJS 1.5  </p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>(function () {
  'use strict';

  angular
    .module('app')
    .component('appLayout', {
      templateUrl: 'app/app-layout/app-layout.html',
      bindings: {
        envConfig: '&lt;',
        categoriesByArea: '=',
        listCycles: '=',
        userRole: '='
      },
      controller: function ($log, $rootScope, ModalService, $scope) {
        var vm = this;
        $rootScope.categoryList = vm.categoriesByArea;
        var error500 = $rootScope.$on('event:internalServerError', function () {
          _showError(""ERROR 500"", ""Error"");
        });
        $scope.$on('$destroy', error500);

        // PRIVATE FUNCTIONS
        function _showError(errorTitle, errorDescription) {
          $log.error('Error _showError', errorTitle, errorDescription);
          ModalService.showModal({
            templateUrl: ""app/shared/modals/modal-error.html"",
            controller: ""ModalErrorController"",
            inputs: {
              errorTitle: errorTitle,
              errorDescription: errorDescription
            }
          });
        }
      }
    });
})();</code></pre>
</div>
</div>
</p>

<p>I have created the test according to the official docs from Angular <a href=""https://docs.angularjs.org/guide/component#unit-testing-component-controllers"" rel=""nofollow noreferrer"">https://docs.angularjs.org/guide/component#unit-testing-component-controllers</a></p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>describe('component: appLayout', function () {
  var $componentController;
  var rootScope;
  var scope;

  beforeEach(module('app'));
  beforeEach(angular.mock.inject(function (_$componentController_) {
    $componentController = _$componentController_;
  }));

  // Here we are passing actual bindings to the component
  var bindings = {
    envConfig: {""api"": ""http://localhost:8080"", ""env"": ""local"", ""version"": ""1.7.2""},
    categoriesByArea: {},
    listCycles: {},
    userRole: {}
  };

  it('should expose a `appLayout` object', function () {
    var ctrl = $componentController('appLayout', null, bindings);

    expect(ctrl.envConfig).toBeDefined();
    expect(ctrl.categoriesByArea).toBeDefined();
    expect(ctrl.listCycles).toBeDefined();
    expect(ctrl.userRole).toBeDefined();

    expect(ctrl.envConfig.api).toBe('http://localhost:8080');
    expect(ctrl.envConfig.env).toBe('local');
    expect(ctrl.envConfig.version).toBe('1.7.2');
  });
});</code></pre>
</div>
</div>
</p>

<p>But this is covering just the component but not the controller of that component.</p>

<p>what is the best approach to cover this 100%?</p>
",https://stackoverflow.com/questions/42672041/unit-test-for-a-component-in-angularjs-1-x-karma-and-jasmine,"['javascript', 'angularjs', 'unit-testing', 'karma-jasmine', 'angular-components']",601,FALSE,2,0
Testing a ngrx effect that in one case does not dispatch a new action,"<p>I have this one effect where some preconditions have to be true so that a specific action gets dispatched:</p>

<pre><code>@Effect()
prepareLoadDetails$: Observable&lt;Action&gt; = this.actions$
    .ofType(PREPARE_LOAD_DETAILS)
    .withLatestFrom(this.store)
    .filter(([actionType, stateStore]) =&gt; this.necessarySelectionsMade(stateStore))
    .map(() =&gt; {
        return new LoadDetailsAction();
    });
</code></pre>

<p>Now I'm somehow stuck in unit testing this code. There's no problem getting the LoadDetailsAction dispatched. But how can I test that no action is dispatched in the other cases?</p>

<pre><code>describe('prepareLoadDetails$', () =&gt; {
    it('should trigger a LoadDetailsAction if all needed selections are made', (done) =&gt; {
        // given
        const {runner, effects} = setup({
            // some setup of state here
        });

        // when
        runner.queue(new PrepareLoadDetailsAction());

        // then
        effects.prepareLoadDetails$.subscribe(result =&gt; {
            expect(result).toEqual(new LoadDetailsAction());
            done();
        });
    });

    it('should not trigger a LoadDetailsAction if needed selections are not made', (done) =&gt; {
        // given
        const {runner, effects} = setup({
            // some other setup of state here
        });

        // when
        runner.queue(new PrepareLoadDetailsAction());

        // then ???
    });
});
</code></pre>
",https://stackoverflow.com/questions/45920724/testing-a-ngrx-effect-that-in-one-case-does-not-dispatch-a-new-action,"['angular', 'unit-testing', 'ngrx']",1277,FALSE,0,0
how to write junit test cases return dummy repository session,"<p>repository = JcrUtils.getRepository('http"" + "":"" + ""/""+ ""/"" + ""localhost"" + "":""+ ""4502"" + ""/crx/server"");</p>

<p>session = repository.login(
                    new SimpleCredentials(""admin"",""admin"".toCharArray()),""crx.default"");</p>

<p>How to get dummy repository and session in junit test class.</p>

<p>i searched below url's</p>

<p><a href=""https://stackoverflow.com/questions/9419606/unit-testing-a-method-dependent-to-the-request-context"">https://stackoverflow.com/questions/11550568/unit-testing-by-mocking-the-data-layer-or-using-embedded-database?noredirect=1&amp;lq=1</a></p>
",https://stackoverflow.com/questions/45620474/how-to-write-junit-test-cases-return-dummy-repository-session,"['java', 'spring-boot', 'junit4', 'aem']",955,FALSE,-2,1
Mockito test not working,"<p>I am new to Mockito and while unit testing i am getting a null pointer exception. Can someone please let me know what am i doing wrong here? Below is the service method which needs to be tested:</p>

<pre><code>    class a{
     public List&lt;String&gt; getabc(String div){
     ResponseEntity&lt;SD&gt; sd = resttemplate.getforEntity(""http://localhost:8080/abc/""+div,SD.class);
     if(sd !=NULL &amp;&amp; sd.getstatuscode() == HTTPstatus.oK){
     return sd.getbody().getsd();
     }
     }
</code></pre>

<hr>

<pre><code>    Public class testa{
     @Mock
     Resttemplate resttemplate;//mocking resttemplate

     @InjectMocks
     private a a1= new a(restTemplate); //injectingmocks to the service

     @Test
     public void testmetha(){
     List&lt;String&gt; ts = new ArrayList&lt;&gt;();
     ts.add(""t1"");
     ts.add(""t2"");
     SD sd = new SD();
      sd.setid(ts);
     ResponseEntity&lt;SD&gt; rs = new ResponseEntity&lt;SD&gt;(sd, HTTPSTATUS.OK);
     when(resttemplate.getforEntity(""http://localhost:8080/abc/25"",SD.class)).thenReturn(rs);
     ts = a1.getabc(""25"");
     assertEquals(3, a1.getabc(""25"").size());
     }
     }
</code></pre>

<p>It gives a null pointer exception at -  ts = a1.getabc(""25"");</p>
",https://stackoverflow.com/questions/47047478/mockito-test-not-working,"['java', 'junit', 'mockito']",418,TRUE,-2,1
Angularjs - Test unit directive only numbers,"<p>I have a directives.js file with two directives and I would like apply unit testing necesary, to improve coverage, but I do not know how to do it</p>

<p>This the directive.js file:</p>

<pre><code>(function () {
  'use strict';

  angular
    .module('app')
    .directive('numbersOnly', function(){
        return {
            require: 'ngModel',
            link: function(scope, element, attrs, modelCtrl) {
                modelCtrl.$parsers.push(function (inputValue) {
                    var transformedInput = inputValue ? inputValue.replace(/[^\d.-]/g,'') : null;
                    if (transformedInput!=inputValue) {
                        modelCtrl.$setViewValue(transformedInput);
                        modelCtrl.$render();
                    }
                    return transformedInput;
                });
            }
        }
    })
    .directive('numbersOnlyPositive', function(){
        return {
            require: 'ngModel',
            link: function(scope, element, attrs, modelCtrl) {
                modelCtrl.$parsers.push(function (inputValue) {
                    var transformedInput = inputValue ? inputValue.replace(/[^\d.]/g,'') : null;
                    if (transformedInput!=inputValue) {
                        modelCtrl.$setViewValue(transformedInput);
                        modelCtrl.$render();
                    }
                    return transformedInput;
                });
            }
        }
    });
 })();  
</code></pre>

<p>This is the tests file (directives.spec.js):</p>

<pre><code>(function () {
  'use strict';

    describe('Unit testing directives general', function() {
        var $compile,
            $rootScope,
            element,
            vm;

        // Load the app module, which contains the directive
        beforeEach(module('app'));

        // Store references to $rootScope and $compile
        // so they are available to all tests in this describe block
        beforeEach(inject(function(_$compile_, _$rootScope_){
            // The injector unwraps the underscores (_) from around the parameter names when matching
            $compile = _$compile_;
            $rootScope = _$rootScope_;
            vm.mesHastaSelected = ""3"";
            vm.cantidadHastaSelected = ""5"";
            //element = angular.element('&lt;input text ng-model=""mesHastaSelected""&gt;');
        }));


        it('should accept number input only', function() {
            expect(vm.cantidadHastaSelected).toBe('1');
        });

        it('should accept number positive input only', function() {
            expect(vm.mesHastaSelected).toBe('8');
        });          

    });
})();  
</code></pre>

<p>This is the html code input fields:</p>

<pre><code>&lt;input type=""text"" ng-model=""vm.mesHastaSelected"" maxlength=""2"" numbers-only-positive /&gt;
&lt;input type=""text"" ng-model=""vm.cantidadHastaSelected"" maxlength=""4"" numbers-only /&gt;
</code></pre>

<p>Thanks for the help,</p>
",https://stackoverflow.com/questions/42645821/angularjs-test-unit-directive-only-numbers,"['angularjs', 'unit-testing', 'angularjs-directive']",412,FALSE,0,0
"In React, how to test the click event in child that&#39;s inside a parent element","<p>I'm doing unit-testing on a <code>component</code> child element, for a React app using Jest, the issue is I cannot test if a function has been called or not when the child element is clicked. The function is mocked with <code>jest.fn()</code>. But I still get this error <code>Expected mock function to have been called.</code>.</p>

<h3>Component:</h3>

<pre><code>import React, { Component } from 'react';

class Panel extends Component {

  static defaultProps = {
    title: 'No data',
    info: 'Please add some info!.'
  }

  handleRemove() {
    alert('Panel should be removed!');
  }

  handleShare(e) {
    e.preventDefault();
    alert('Panel info can shared on social media.');
  }

  render() {
    return (
      &lt;div className=""panel col-md-4 col-xs-6""&gt;
        &lt;a href=""#"" className=""panel-remove-btn"" onClick={this.handleRemove}&gt;Remove&lt;/a&gt;
        &lt;div&gt;
          &lt;h3 className=""panel-title""&gt;{this.props.panel.title}&lt;/h3&gt;
          &lt;p className=""panel-info""&gt;{this.props.panel.info}&lt;/p&gt;
        &lt;/div&gt;
        &lt;div&gt;
          &lt;a className=""panel-share-btn btn btn-primary"" onClick={this.handleShare}&gt;Share&lt;/a&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    );
  }
}

export default Panel;
</code></pre>

<h3>Component unit-test:</h3>

<pre><code>import React from 'react';
import ReactDOM from 'react-dom';
import renderer from 'react-test-renderer';
import { shallow, mount } from 'enzyme';
import Panel from '../Panel/Panel';

describe('Panel', () =&gt; {
  let panel,
    panelData = {
      title: 'Sabrina girls!!',
      info: 'Some Sabrina best kitchen dishes'
    };

  beforeEach(() =&gt; {
    panel = shallow(&lt;Panel panelDate={panelData} /&gt;);
  });

  it('renders as intended', () =&gt; {
    const component = renderer.create(&lt;Panel panelData={panelData} /&gt;),
      json = component.toJSON();

    expect(json).toMatchSnapshot();
  });

  it('renders Panel title', () =&gt; {
    expect(panel.find('.panel-title').text()).toEqual('Sabrina girls!!');
  });

  it('renders Panel information', () =&gt; {
    expect(panel.find('.panel-info').text()).toEqual('Some Sabrina best kitchen dishes');
  });

  it('should remove the Panel', () =&gt; {
    const handleRemove = jest.fn();

    expect(panel.find('.panel-remove-btn').length).toEqual(1);

    // accessing the child element and simulate a click
    panel.first().find('.panel-remove-btn').simulate('click');

    expect(handleRemove).toHaveBeenCalled(); // &lt;= ""handleRemove"" is not called even though I've defined it above and simulated a click event!
  });
});
</code></pre>
",https://stackoverflow.com/questions/43802572/in-react-how-to-test-the-click-event-in-child-thats-inside-a-parent-element,"['javascript', 'unit-testing', 'reactjs', 'jestjs']",2204,FALSE,0,1
Error in phpunit laravel 5.4,"<p>I need to use unit testing in laravel but they need to download library <code>laravel/browser-kit-testing</code>
When i download it tell me they  need  php 5.6 
And i using php 5.4.</p>

<pre><code> public function testBasicTest()
    {
        $this-&gt;visit('/home')
            -&gt;seePageIs('/login');
        $response = $this-&gt;call('GET', '/dradmin');
        $this-&gt;assertEquals(200, $response-&gt;status());
        $this-&gt;visit('/login')
            -&gt;type('mahmoud@mahmoud.com', 'email')
            -&gt;type('123456', 'password')
            -&gt;press('Login')
            -&gt;seePageIs('/home');

    }
}
</code></pre>

<p>when use <code>phpunit</code></p>

<pre><code>Error: Call to undefined method Tests\Feature\UserTest::visit()

/Users/mahmoud310/ecare/tests/Feature/UserTest.php:21
</code></pre>

<p>I read in other problems 
<a href=""https://stackoverflow.com/questions/43531404/laravel-5-4-http-testing-method-seeinelement"">Laravel 5.4 HTTP testing - method seeInElement</a></p>

<p>use command  <code>laravel/browser-kit-testing</code> can solve problem</p>

<p>in my case not work</p>

<pre><code>Using version ^1.0 for laravel/browser-kit-testing
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package phpunit/phpunit (locked at 5.7.19, required as 4.8.*) is satisfiable by phpunit/phpunit[5.7.19] but these conflict with your requirements or minimum-stability.
  Problem 2
    - Conclusion: don't install phpunit/phpunit 4.8.35
    ...
    - Conclusion: don't install phpunit/phpunit 4.8.1
    - phpunit/phpunit 4.8.0 conflicts with phpunit/phpunit-mock-objects[3.4.3].
    ...
    - phpunit/phpunit 4.8.0 conflicts with phpunit/phpunit-mock-objects[3.4.3].
    - Installation request for phpunit/phpunit 4.8.* -&gt; satisfiable by phpunit/phpunit[4.8.0, 4.8.1, ..., 4.8.9].
    - Installation request for phpunit/phpunit-mock-objects (locked at 3.4.3) -&gt; satisfiable by phpunit/phpunit-mock-objects[3.4.3].


Installation failed, reverting ./composer.json to its original content.
</code></pre>
",https://stackoverflow.com/questions/43778728/error-in-phpunit-laravel-5-4,"['unit-testing', 'laravel-5', 'phpunit', 'composer-php', 'laravel-5.4']",1285,TRUE,3,3
Using SSL with Microsoft.AspNetCore.TestHost.TestServer,"<p>Visual Studio 2017 with ASP.NET Core 1.1. Unit Testing with xUnit and Microsoft.AspNetCore.TestHost.TestServer</p>

<p>The code below, copied from the official core source code, works as expected, however, if you change the Uri to http<strong>s</strong>://example.com, the response is 404: </p>

<pre><code>[Fact]
public async Task CheckPermanentRedirectToHttps()
{
    var options = new RewriteOptions().AddRedirectToHttpsPermanent();
    var builder = new WebHostBuilder()
        .Configure(app =&gt;
        {
            app.UseRewriter(options);
        });
    var server = new TestServer(builder);

    var response = await server.CreateClient().GetAsync(new Uri(""http://example.com""));

    Assert.Equal(""https://example.com/"", response.Headers.Location.OriginalString);
    Assert.Equal(StatusCodes.Status301MovedPermanently, (int)response.StatusCode);
}
</code></pre>

<p>How can I make the https work like the http with the <code>TestServer</code>?</p>
",https://stackoverflow.com/questions/46125707/using-ssl-with-microsoft-aspnetcore-testhost-testserver,"['c#', 'ssl', 'asp.net-core', 'xunit.net', 'asp.net-core-1.1']",1224,FALSE,1,0
Angular2 unit testing error: Can&#39;t bind to &#39;routerLink&#39; since it isn&#39;t a known property of &#39;a&#39;,"<p>I'm trying to manage with unit testing (karma, jasmine) and I'm getting an error:</p>

<blockquote>
  <p>Can't bind to 'routerLink' since it isn't a known property of 'a'</p>
</blockquote>

<p>I have not even changed *.spec.ts file that was created by angular-cli...</p>

<p>Here are my files:</p>

<p><strong>user-list.component.html</strong></p>

<pre><code>&lt;ul&gt;
  &lt;li *ngFor=""let user of users""&gt;
    &lt;a [routerLink]=""user._id"" (click)=""userClicked(user)""&gt;{{user.fullName}}&lt;/a&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;router-outlet&gt;&lt;/router-outlet&gt;
</code></pre>

<p><strong>user-list.component.ts</strong></p>

<pre><code>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { IUser, User } from '../../../interfaces/user';
import { UsersService } from '../../../services/users.service';

@Component({
  selector: 'app-user-list',
  templateUrl: './user-list.component.html',
  styleUrls: ['./user-list.component.css']
})
export class UsersListComponent implements OnInit {

  users: IUser[] = [];

  constructor(private usersService: UsersService, private router: Router) { }

  ngOnInit() {
    this.usersService.getAll()
      .subscribe(users =&gt; {
        this.users = users.sort(...).map(...);
      });

  }

  userClicked(user) {
    this.usersService.setCurrentUser(user);
  }

  clickXBtn(user) {
    this.usersService
        .deleteUser(user)
        .subscribe(...);
  }

}
</code></pre>

<p><strong>user-list.component.spec.ts</strong></p>

<pre><code>/* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

import { UsersListComponent } from './user-list.component';

describe('UsersListComponent', () =&gt; {
  let component: UsersListComponent;
  let fixture: ComponentFixture&lt;UsersListComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ UsersListComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(UsersListComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p>What should I change? How to make it work?</p>
",https://stackoverflow.com/questions/42245864/angular2-unit-testing-error-cant-bind-to-routerlink-since-it-isnt-a-known-p,['angular'],5233,TRUE,6,2
Providing mocked object to another mock object constructor?,"<p>First time unit testing, and using Mockito. I'm not sure if I'm thinking about testing this correctly. Here is the situation:</p>

<p>In my Android app, I am using Model-View-Presenter. I am trying to test a method in my presenter class called <code>validateCredential(serviceManager: ServiceManager, email: String, password: String)</code> to see if the service manager I pass to it will eventually call a callback (this method is called by the view) by verifying it with mockito.</p>

<pre><code>// method in presenter class
override fun validateCredential(serviceManager: ServiceManager, email: String, password: String) {
    loginModel = LoginModel(email, password)
    serviceManager.getParent(email, password)
    serviceManager.execute()
}

// callback implemented by presenter class
private fun handleLoginResult(result: ServiceManager.RequestResult, data: ByteArray, responseCode: Int, optionalParam: String) {
    ...
    mView.startHomeScreen()
}
</code></pre>

<p>The presenter class also implements a callback interface (<code>IServiceAsyncTaskCallback</code>) that is provided to the <code>serviceManager</code>'s constructor. What I want in this specific unit test is to verify that <code>mView.startHomeScreen()</code> is called.</p>

<p>The problem:</p>

<ul>
<li>Android unit testing seems to require that ServiceManager be mocked (ServiceManager extends abstract class AsyncTask) because when I call <code>execute()</code>, the Android unit testing lib will throw an exception if it is not mocked. </li>
<li>However, if I mock the ServiceManager, I can't provide it with two necessary parameters to the constructor, which SHOULD be mocked, if I'm understanding unit testing correctly. The two parameters to the constructor are an interface callback (which is the presenter class), and a class object that is responsible for sending JSON through http. Both of these should be mocked, correct? Because in a unit test you don't want these dependencies to actually make HTTP calls or call callbacks, right?</li>
<li>It seems I'm overthinking this. What I really want is to see if my view object which is passed to presenter, calls <code>startHomeScreen()</code>, so I should really just forget testing the <code>validateCredentialMethod()</code> and just call <code>handleLoginResult(...)</code> directly. Is this better than the above route?</li>
<li>However, another problem is that even if I call <code>handleLoginResult(...)</code> directly to test if the mock view that is passed to presenter is called, that method code contains a call to JSONObject which is Android related code, and since it belongs to the android.jar file, it will throw an exception because it is not mocked! Am I supposed to provide an injection for that too?!</li>
</ul>

<p>I'm lost as how to test this. What's the correct way to verify that the mock view has called <code>startHomeScreen()</code>?</p>
",https://stackoverflow.com/questions/47321131/providing-mocked-object-to-another-mock-object-constructor,"['java', 'android', 'unit-testing', 'kotlin', 'mockito']",1070,TRUE,1,1
Testing SharedPrefernces in Flutter,"<p>I would like to test if my method calls SharedPreferences's put method. Is that possible in unit testing?</p>

<p>In general: this is method I would like to test. I want to verify if unit was set.</p>

<pre><code>Future _setUnit(String unit) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setString('unit', unit);
}
</code></pre>

<p>I know there is SharedPreferences.setMockInitialValues method but I don't think it would anyhow help me.</p>
",https://stackoverflow.com/questions/47848747/testing-sharedprefernces-in-flutter,"['dart', 'flutter']",104,FALSE,1,0
&quot;Module was not compiled for testing&quot; error when using Swift Package Manager,"<p>I created a Swift library with <code>swift package init --type library</code> and generated an Xcode project with <code>swift package generate-xcodeproj</code>.</p>

<p>Now I'm trying to run the Test scheme in Xcode. It prints following error:</p>

<pre><code>Module '&lt;title&gt;' was not compiled for testing
</code></pre>

<p>However when I run <code>swift build</code> and <code>swift test</code> in terminal, it works fine.</p>

<p>I have <code>ENABLE_TESTABILITY</code> set to <code>YES</code> in all of the targets. I didn't change anything in the project except this. How can I make Xcode perform unit testing?</p>
",https://stackoverflow.com/questions/42316368/module-was-not-compiled-for-testing-error-when-using-swift-package-manager,"['swift', 'xcode', 'swift-package-manager']",5276,TRUE,9,3
Pull request linter,"<p>I'm searching an easy way to have a sort of pull request linter.
Here is what I want to do.</p>

<ol>
<li>One of my colleagues do a pull request.</li>
<li>A tool check the quality of the code (respect of the standard PSR2, check of the PHP code).</li>
<li>A tool launch the unit testing of this branch.</li>
<li>All the results of these tools appears in comment of the pull request.</li>
<li>If all is ok, the pull request is assigned to me and I can check it manually.</li>
</ol>

<p>If I approve and merge the pull request, a new job is trigged on the destination branch to launch unit testing automatically.</p>

<p>I have see tools like Jenkins but I'm not sure I will be able to do that with it, and if what I want to do is called continuous integration.</p>
",https://stackoverflow.com/questions/44481757/pull-request-linter,"['git', 'jenkins', 'continuous-integration', 'pull-request']",126,FALSE,0,1
redux-observable unit test epci with dependencies,"<p>I have an epic with the following signature (note the dependency)</p>

<pre><code>export const incrementalSearchEpic = (action$, store, { incrementalSearchService }) =&gt; {
    // eslint-disable-next-line max-len
    return action$.ofType('SEARCH_STORES').mergeMap((action) =&gt;
        incrementalSearchService.performIncrementalSearch(action)
    );
};
</code></pre>

<p>Now I need to unit test this and this is my unit testing code</p>

<pre><code>beforeEach(() =&gt; {
    epicMiddleWare = createEpicMiddleware(incrementalSearchEpic,
        {
            dependencies: {
                incrementalSearchService: IncrementalSearchServiceMock
            }
        });
    const mockStore = configureMockStore([epicMiddleWare]);
    const getState = {}; // initial state of the store         
    store = mockStore(getState);
});

// eslint-disable-next-line max-len
it('calls the incrementalSearchService-&gt;performIncrementalSearch with the parameters when called', () =&gt; {
    //dispatch the incremental search action
    const searchStore = {
        type: 'SEARCH_STORES',
        SearchText: 'Aldi'
    };

    store.dispatch(searchStore);

    expect(store.getActions()).toEqual([
        searchStore
    ]);
});
</code></pre>

<p>However when I run the code I get the following error</p>

<p>TypeError: Cannot read property 'performIncrementalSearch' of undefined</p>

<p>Seems like the dependency does not get passed in properly.</p>
",https://stackoverflow.com/questions/45705989/redux-observable-unit-test-epci-with-dependencies,"['unit-testing', 'jestjs', 'redux-observable']",67,FALSE,2,1
junit AssertionFailedError with memory address,"<p>I am new to unit testing.  I am testing a function that ""tokenizes"" a <code>String</code>.  The <code>String</code> is a mathematical expression.  Here is my code:</p>

<pre><code>@Test
public void testTokenizer() throws InvalidExpressionException {

    final String QUERY = ""sin(x) / 5*x"";
    final String[] EXPECTED = {""x"", ""sin"", ""5"", ""x"", ""*"", ""/""};
    parser.parse(QUERY);
    final String[] actual = parser.getTokens().toArray(new String[parser.getTokens().size()]);

    Assertions.assertEquals(EXPECTED, actual);
}
</code></pre>

<p>This is the error I get:</p>

<pre><code>org.opentest4j.AssertionFailedError: 
Expected :[Ljava.lang.String;@62043840
Actual   :[Ljava.lang.String;@5315b42e
</code></pre>

<p>I am using junit5.  It looks like those are memory addresses(I'm a beginner).  <strong>Am I making the wrong assertion(comparing pointers or something)?</strong></p>
",https://stackoverflow.com/questions/44468159/junit-assertionfailederror-with-memory-address,"['java', 'junit']",3186,TRUE,2,2
Karma config to exclude nested directories,"<p>I am using karma for unit testing my angular 2 application. I have following directory structure -</p>

<pre><code>└── src/
    ├── index.js
    ├── index.js.text
    ├── index.test.js
    ├── README.txt
    ├── startuptest.js
    ├── lib/
    |   ├── util.js
    |   ├── util.test.js
    |   └── filters/
    |       ├── kalman.js
    |       └── lowpass.js
    ├── test/
    |   ├── main.js
    |   └── lib/
    |       ├── filters.js
    |       └── util.js
    └── vendor/
        ├── jquery.js
        └── three/
            ├── three.js
            └── three.fps.js
</code></pre>

<p>I want to exclude all files under my </p>

<pre><code>src/lib/!(filters)/**
</code></pre>

<p>from  coverage report. But I want to keep all the files from rest of the directory </p>

<p>I tried,</p>

<pre><code>{src/**, src/lib/!(filters)/**}/!(*.spec!).js : coverage 
</code></pre>

<p>But it's skipping everything.</p>

<p>How to do this?</p>

<p>Reference - <a href=""https://github.com/karma-runner/karma/issues/508"" rel=""noreferrer"">https://github.com/karma-runner/karma/issues/508</a></p>
",https://stackoverflow.com/questions/42105675/karma-config-to-exclude-nested-directories,"['javascript', 'testing', 'karma-runner', 'karma-jasmine', 'karma-coverage']",3515,FALSE,5,1
Encountered two children with the same key(Jest),"<p>Hi I was doing unit testing for react components , every time the uniqid will be generated so i am using jest.mock('uniqid', () => i => <code>${i}someUniqId</code>); , It sets key for both parent and client components it seems </p>

<blockquote>
  <p>jest.mock('uniqid', () => i => <code>${i}someUniqId</code>);</p>
</blockquote>

<p>But it throws a <strong>Warning</strong> </p>

<p><a href=""https://i.stack.imgur.com/2ocga.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/2ocga.png"" alt=""enter image description here""></a></p>

<p>How to solve this issue ,  is this right approach ? </p>
",https://stackoverflow.com/questions/47349669/encountered-two-children-with-the-same-keyjest,"['reactjs', 'unit-testing', 'redux', 'jestjs']",184,TRUE,0,1
All Moq testCases pass without checking any logic?,"<p>I am following this <a href=""https://www.codementor.io/copperstarconsulting/intro-to-unit-testing-c-code-with-nunit-and-moq-part-1-y2b9iv8iq"" rel=""nofollow noreferrer"">intro to unit testing</a> tutorial.</p>

<p>I have not implemented a logic to determine what credit score should return ""Maybe"", ""Declined"" but <strong>Moq</strong> test passes all the Unit Tests.</p>

<pre><code>public interface ICreditDecisionService {
    string GetCreditDecision(int creditScore);
}

public class CreditDecision {
ICreditDecisionService creditDecisionService;

public CreditDecision(ICreditDecisionService creditDecisionService) {
    this.creditDecisionService = creditDecisionService;
}

public string MakeCreditDecision(int creditScore) {
    return creditDecisionService.GetCreditDecision(creditScore);
}

===================================
// Testing Class
[TestFixture]
public class CreditDecisionTests {
    //mock instance for dependency
    Mock &lt; ICreditDecisionService &gt; mockCreditDecisionService;

    CreditDecision systemUnderTest;

    [TestCase(100, ""Declined"")]
    [TestCase(549, ""Declined"")]
    [TestCase(550, ""Maybe"")]
    [TestCase(674, ""Maybe"")]
    [TestCase(675, ""We look forward to doing business with you!"")]
    public void MakeCreditDecision_Always_ReturnsExpectedResult(int creditScore, string expectedResult) {

        //Arrange
        //creating and configuring the mock 
        mockCreditDecisionService = new Mock &lt; ICreditDecisionService &gt; (MockBehavior.Strict);
        mockCreditDecisionService.Setup(p =&gt; p.GetCreditDecision(creditScore)).Returns(expectedResult);

        systemUnderTest = new CreditDecision(mockCreditDecisionService.Object);
        var result = systemUnderTest.MakeCreditDecision(creditScore);

        Assert.That(result, Is.EqualTo(expectedResult));

        mockCreditDecisionService.VerifyAll();
    }
}
</code></pre>

<p>I don't have implementation of <code>ICreditDecisionService</code>, yet <strong>Moq</strong> test passess! Could you explain what is wrong with these codes.</p>
",https://stackoverflow.com/questions/47026424/all-moq-testcases-pass-without-checking-any-logic,"['c#', 'unit-testing', 'moq', 'moq-3']",94,TRUE,0,1
how do I mock objects and their methods in javascript,"<p>I am having trouble unit testing the javascript function listEntities. The difficulty lies in the mocking/stubbing. The documentation for javascript mocking/stubbing libraries is a mess. I am hoping someone with experience can show me the way. Here is the code:</p>

<pre><code>export const listEntities = (kind, googleDatastoreFactory) =&gt; {
  const datastore = googleDatastoreWrapperFactory();
  const query = datastore.createQuery(kind);
  return datastore.runQuery(query)
    .then(results =&gt; (results[0]));
};

export const googleDatastoreFactory = () =&gt; { 
    const Datastore = require('@google-cloud/datastore');
    return Datastore();
};
</code></pre>

<p>Here is my attempt:</p>

<pre><code>describe('datastore api', () =&gt; {
  describe('listEntities', () =&gt; {
    const mockedGoogleDatastore = JsMockito.mock(GoogleDatastore);
    JsMockito.when(mockedGoogleDatastore).runQuery('query').thenReturn(new Promise(resolve =&gt; resolve(['result'])));
    JsMockito.when(mockedGoogleDatastore).createQuery('Test').thenReturn('query');
    const googleDatastoreFactory = () =&gt; (mockedGoogleDatastore);
    test('should return list of items', () =&gt; {
      listEntities('Test', googleDatastoreFactory).then(result =&gt; console.log(result));
    });
  });
});
</code></pre>

<p>Here is my error:</p>

<pre><code>  ● datastore api › listEntities › encountered a declaration exception

    TypeError: _jsmockito2.default.mock is not a function

      at Suite.&lt;anonymous&gt; (app/api/datastore.api.test.js:7:60)
      at Suite.&lt;anonymous&gt; (app/api/datastore.api.test.js:6:3)
      at Object.&lt;anonymous&gt; (app/api/datastore.api.test.js:5:1)
          at Generator.next (&lt;anonymous&gt;)
          at Promise (&lt;anonymous&gt;)
          at Generator.next (&lt;anonymous&gt;)
          at &lt;anonymous&gt;
      at process._tickCallback (internal/process/next_tick.js:188:7)
</code></pre>
",https://stackoverflow.com/questions/47150559/how-do-i-mock-objects-and-their-methods-in-javascript,"['javascript', 'google-cloud-datastore', 'jsmockito']",163,FALSE,0,1
How do I correctly pass DateTime from C# to SQL?,"<p>I'm attempting to run a stored procedure from C# and am getting a conversion error while unit testing. Every search result for this issue I've seen indicated that using ToString() is not the preferred way to pass DateTime's. </p>

<p>C# Code:</p>

<pre><code>using (SqlConnection lvConn = new SqlConnection(gvSQLConnectionS))
{
    lvConn.Open();
    SqlCommand lvCmd = new SqlCommand(gvSQLsp, lvConn);
    lvCmd.CommandType = CommandType.StoredProcedure;
    lvCmd.Parameters.Add(new SqlParameter(gvSQLparamFunction, gvSQLfunctionUpdLE));
    lvCmd.Parameters.Add(new SqlParameter(gvSQLparamID, lvAAAID));
    lvCmd.Parameters.Add(new SqlParameter(gvSQLparamName, lvName));
    lvCmd.Parameters.Add(new SqlParameter(gvSQLparamPath, lvPath)); 
    SqlParameter lvParameterLE = lvCmd.Parameters.Add(gvSQLparamLE, SqlDbType.DateTime);
    SqlDateTime lvDTnow = new SqlDateTime(DateTime.Now);
    lvParameterLE.Value = lvDTnow;
    lvCmd.ExecuteNonQuery();
}
</code></pre>

<p>SQL Setup:
Last Executed (datetime, null)</p>

<p>Stored Procedure:</p>

<pre><code>ALTER PROCEDURE [dbo].[sp_BackupCleaner]
    @lvFunction int,
    @lvAAAID varchar(12) = NULL,
    @lvAAAID_new varchar(12) = NULL,
    @lvName varchar(35) = NULL,
    @lvName_new varchar(35) = NULL,
    @lvPath varchar(255) = NULL,
    @lvPath_new varchar(255) = NULL,
    @lvLastExecuted datetime = NULL
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @lvSQL varchar(max)    
</code></pre>

<hr>

<pre><code>IF @lvFunction = 6
    BEGIN
        SET @lvSQL = 'UPDATE [dbo].[Backup_Paths]
                SET [dbo].[Backup_Paths].[Last Executed] = '+@lvLastExecuted+'
                WHERE [dbo].[Backup_Paths].[AAA Client ID] = '''+@lvAAAID+'''
                AND [dbo].[Backup_Paths].[Process Name] = '''+@lvName+'''
                AND [dbo].[Backup_Paths].[UNC Path] = '''+@lvPath+''''
    END

execute(@lvSQL)
END
</code></pre>

<p>Exception thrown:</p>

<pre><code>System.Data.SqlClient.SqlException: Conversion failed when converting date and/or time from character string.
</code></pre>
",https://stackoverflow.com/questions/45193910/how-do-i-correctly-pass-datetime-from-c-to-sql,"['c#', 'sql-server', 'datetime']",646,TRUE,0,3
"NUnit : Effort.Exceptions.EffortException : The Effort library failed to register its provider automatically, so manual registration is required","<p>I am working on Web API and while unit testing using NUnit i faced this error which said:</p>

<pre><code>Tests.DemoTest.SessionLogOnBreakdownTest:
SetUp : Effort.Exceptions.EffortException : The Effort library failed to register its provider automatically, so manual registration is required.

a) Call the Effort.Provider.EffortProviderConfiguration.RegisterProvider() method at entry point of the application

or

b) Add the following configuration to the App.config file:
   &lt;system.data&gt;
      &lt;DbProviderFactories&gt;
         &lt;add name=""Effort.Provider""
              invariant=""Effort.Provider""
              description=""Effort.Provider""
              type=""Effort.Provider.EffortProviderFactory, Effort"" /&gt;
      &lt;/DbProviderFactories&gt;
   &lt;/system.data&gt;
  ----&gt; System.Configuration.ConfigurationErrorsException : Failed to find or load the registered .Net Framework Data Provider.
TearDown : System.NullReferenceException : Object reference not set to an instance of an object.
</code></pre>

<p>Here is the Test which i am running:</p>

<pre><code>[TestFixture]
public class DemoTest : TestBase
{
    private TestContext _context;
    private DbConnection _dbConnection;

    [SetUp]
    public void Initialization()
    {
        //Effort.Provider.EffortProviderConfiguration.RegisterProvider();
        _dbConnection = Effort.DbConnectionFactory.CreateTransient();
        _context = new TestContext(_dbConnection);
    }

    [Test]
    public void SessionLogOnBreakdownTest()
    {
         //code which uses _context
    }
}
</code></pre>

<p>Error is thrown at <code>_dbConnection = Effort.DbConnectionFactory.CreateTransient();</code></p>

<p>I have followed both the suggestions which the exception gives. But none worked.</p>

<p>Things i have tried:</p>

<ul>
<li>Those two suggestions in the exception helper</li>
<li>Update-Package -reinstall Effort</li>
</ul>
",https://stackoverflow.com/questions/43388713/nunit-effort-exceptions-effortexception-the-effort-library-failed-to-registe,"['c#', 'asp.net-web-api', 'nunit', 'effort']",1388,TRUE,5,1
Mocking methods from package,"<p>I am looking to mock some methods for unit testing. Unfortunately, the code is not structured really well. </p>

<pre><code>var config = struct { abc *abc }

func Init(arg1) {
    // config.abc = newAbc(arg2, arg3)
}   

func UnitTestThis() { 
    //some code here 

    config.abc.Search(arg4,arg5) 

    //code here 
}
</code></pre>

<p>How do I unit test the UnitTestThis function, mocking the results of Search method? I have been trying to create an interface and mock the methods, but been unable to do so.</p>
",https://stackoverflow.com/questions/47328904/mocking-methods-from-package,"['unit-testing', 'go', 'mocking']",156,TRUE,-1,1
Add intentional latency in db.collection.save(),"<p>Which is the best way to intentionally add latency to db.collection.save() for unit testing purposes.</p>

<p>Let say, I have function that I need to test:</p>

<pre><code>function() {
  let item = collection.findOne({});
  ...
  collection.save(item);
}
</code></pre>

<p>I would like collection.save to be delayed without changing the function code.</p>

<p>Basically I'm looking for something like this <a href=""https://stackoverflow.com/a/19954962/2215679"">express pause middleware</a> but for MongoDB driver.</p>
",https://stackoverflow.com/questions/47721653/add-intentional-latency-in-db-collection-save,"['node.js', 'mongodb']",85,FALSE,0,0
Angular2 - KarmaJS - unit Tests no executed automatically on npm test,"<p>I'm using KarmaJS and JasmineJS for unit testing on Angular2.
When I run ""npm test"" the browser opened automatically, however the tests not executed automatically.</p>

<p><a href=""https://i.stack.imgur.com/aoQ7w.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/aoQ7w.png"" alt=""npm test""></a></p>

<p>If I change any file all the tests will be executed in the project.</p>

<p><a href=""https://i.stack.imgur.com/iStYJ.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/iStYJ.png"" alt=""success""></a></p>

<p>Here my ""<strong>karma.conf.js</strong>""</p>

<p><a href=""https://i.stack.imgur.com/HSCid.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/HSCid.png"" alt=""enter image description here""></a></p>

<p>Here my ""<strong>test.ts</strong>"" file that I refer in ""karma.conf.js""</p>

<p><a href=""https://i.stack.imgur.com/Qrsrf.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Qrsrf.png"" alt=""test.ts""></a></p>
",https://stackoverflow.com/questions/43187294/angular2-karmajs-unit-tests-no-executed-automatically-on-npm-test,"['angular', 'jasmine', 'karma-runner', 'karma-jasmine']",70,TRUE,0,1
Code coverage of the given code,"<p>Why is it that,
If only Unit Testing for function B is done then the coverage of function A is 50%.
Even if we take the values of Function B as (1,2,3)
it would cover the if and else of first function, but why the coverage will still be 50% ?</p>

<pre><code>Public int A(int a,int b)
{
if (a%2==0) 
      return a;
else 
    return b;
}


Public int B (int a,int b,int c)
{
 int val=A(a,b);    
 val=A(val,c);
    }
</code></pre>
",https://stackoverflow.com/questions/43772359/code-coverage-of-the-given-code,"['java', 'c#', 'c++', 'code-coverage']",47,FALSE,-1,1
forceclient async call never received,"<p>I'm unit testing one of my async methods but it turns out to be a bit tricky.
In my code I execute two actions witch I try to verify with NSubstitute like so</p>

<pre><code>[TestMethod]
public async Task GivenDebatchingHandler_WhenCommandReceived_EventIsPublishedAndStatusUpdated()
{
    // arrange
    var forceClient = Substitute.For&lt;IForceClient&gt;();
    forceClient.UpdateAsync(EntityNames.EventStore, Arg.Any&lt;string&gt;(), Arg.Any&lt;ExpandoObject&gt;()).Returns(info =&gt; Task.FromResult(new SuccessResponse { Success = true }));
    var messageHandlerContext = Substitute.For&lt;IMessageHandlerContext&gt;();
    var handler = new DebatchingHandler(forceClient);
    var @event = new KlantManagementEnvelopeCreatedEvent { Header = new Header { MessageId = ""UnitTest"" } };
    var cmd = new PublishMultipleKlantManagementEnvelopeCreatedEventsCommand { EventsLargePayload = new List&lt;KlantManagementEnvelopeCreatedEvent&gt;(new[] { @event }) };

    // act
    await handler.Handle(cmd, messageHandlerContext).ConfigureAwait(false);

    // assert
    await messageHandlerContext.Received().Publish(@event, Arg.Any&lt;PublishOptions&gt;()).ConfigureAwait(false);
    await forceClient.Received().UpdateAsync(EntityNames.EventStore, ""UnitTest"", Arg.Any&lt;ExpandoObject&gt;()).ConfigureAwait(false);
}
</code></pre>

<p>The publish is received, but the <code>UpdateAsync</code> is not. This is the code under test:</p>

<pre><code>public async Task Handle(PublishMultipleKlantManagementEnvelopeCreatedEventsCommand message, IMessageHandlerContext context)
{        
    await Task.WhenAll(message.EventsLargePayload.Select(@event =&gt; this.ProcessEvent(@event, context))).ConfigureAwait(false);
}

public async Task ProcessEvent(KlantManagementEnvelopeCreatedEvent envelopeCreatedEvent, IMessageHandlerContext context)
{
    await context.Publish(envelopeCreatedEvent).ConfigureAwait(false);

    var eventStoreRecord = new EventStore__c { Status__c = EventStoreStatus.Published.ToName() };
    await this.forceClient.UpdateAsync(EntityNames.EventStore, envelopeCreatedEvent.Header.MessageId, eventStoreRecord).ConfigureAwait(false);        
}
</code></pre>

<p>Why is the <code>UpdateAsync</code> call never received?</p>
",https://stackoverflow.com/questions/42134372/forceclient-async-call-never-received,"['c#', 'unit-testing', 'asynchronous', 'nsubstitute']",229,TRUE,1,1
What&#39;s the best way to load stored procedures into the Django unit test database?,"<p>I've got some Postgres stored procedures that my selenium tests will depend on. In development, I load them with a line in a script:</p>

<p><code>cat stored_procedures.sql | python manage.py dbshell</code></p>

<p>This doesn't work when unit testing, since a fresh database is created from scratch. How can I load stored procedures saved in a file into the test database before unit tests are run?</p>
",https://stackoverflow.com/questions/42281946/whats-the-best-way-to-load-stored-procedures-into-the-django-unit-test-database,"['django', 'postgresql', 'unit-testing', 'selenium', 'stored-procedures']",2478,TRUE,4,2
Karma callback is always undefined,"<p>I am facing an issue during unit testing of my service
this is my test case</p>

<pre><code>it(""updateUserProfile() should update user profile"", async(() =&gt; {
 mockBackend.connections.subscribe((connection: MockConnection) =&gt; {
 let responseOpts = new ResponseOptions({ body: JSON.stringify({ username: ""testuser"" }) });
  connection.mockRespond(new Response(responseOpts));
 });
 let obj = {
  callback: (r) =&gt; {
    expect(r.username).toBe(""testuser"");
  }
 };
 spyOn(obj, ""callback"").and.callThrough();
 service.updateUserProfile({}, obj.callback);
 expect(obj.callback).toHaveBeenCalled();
}));
</code></pre>

<p>and this my service</p>

<pre><code>updateUserProfile(user: Profile, callback?: Function): void {
 let sub = this.http.patch(url, user, { headers: this.getHeaders() }).subscribe(r =&gt; {
   callback(r);
   if (sub) sub.unsubscribe();
 });
}
</code></pre>

<p>in this case it is working fine my <code>spy</code> is is returning true that callback is been fired but the code inside my <code>callback</code> is always undefined I want to test the response as well.</p>
",https://stackoverflow.com/questions/43209460/karma-callback-is-always-undefined,"['unit-testing', 'angular', 'karma-jasmine']",73,TRUE,1,1
Python unit test failure: should raise value error but not,"<p>Here is my code trying to learn unit testing. 
Create a Student class for the purpose of testing. The test invalid test case constantly failed. </p>

<pre><code>FAIL: test_invalid (__main__.TestStudent)
----------------------------------------------------------------------
Traceback (most recent call last):
  File ""mystudent.py"", line 46, in test_invalid
    s1.get_grade()
AssertionError: ValueError not raised
</code></pre>

<p>above is from running result.</p>

<p>Could anyone help me to figure out why I have this failure while I think I have put the right 'Raise Error' code there....</p>

<pre><code>import unittest

class Student(object):
def __init__(self, name, score):
    self.name = name
    self.score = score


def get_grade(self):
    try:
        if self.score &gt;= 60 and self.score &lt; 80:
            return 'B'
        if self.score &gt;= 80 and self.score &lt;= 100:
            return 'A'
        if self.score &gt;= 0 and self.score &lt;60:
            return 'C'
        if self.score &lt; 0 or self.score &gt; 100:
            raise ValueError('Invalid score value')
    except Exception as e:
        print('Value error!')


class TestStudent(unittest.TestCase):


def test_invalid(self):
    s1 = Student('Bob', -1)
    s2 = Student('Bat', 101)
    with self.assertRaises(ValueError):
        s1.get_grade()
    with self.assertRaises(ValueError):
        s2.get_grade()


if __name__ == '__main__':
    unittest.main()
</code></pre>

<p>Thanks</p>
",https://stackoverflow.com/questions/47400424/python-unit-test-failure-should-raise-value-error-but-not,"['python', 'unit-testing', 'raiserror']",2589,TRUE,2,1
Calling a function (PHP),"<p>I'm currently writing a key-cipher function to be able to test later through unit testing. I'm very new to PHP and I'm struggling to call a function from the same class. Here is the code:</p>

<pre><code>&lt;?php
class Code{

public function keyCipher($code){
    $alphabet = ""ABCDEFGHIJKLMNOPQRSTUVWXYZ"";
    $alphArr = str_split($alphabet);
    $codeArr = str_split($code);
    $cipher = array();
    $counter = 0;
    foreach($codeArr as &amp;$char1){
        foreach($alphArr as &amp;$char2){
            if($char1 == $char2){
                if(!in_array($char1, $cipher)){
                    $cipher[$counter] = $char1;

                    $counter++;
                }
            }
        }

    }
    foreach($alphArr as &amp;$char1){
        if(!in_array($char1, $cipher)){
            $cipher[$counter] = $char1;

            $counter++;
        }
    }

    return implode($cipher);

}

function cipherSolution($keyword, $code){
    $this -&gt; keyCipher($keyword);

    return $cipher;
}
}
?&gt;
</code></pre>

<p>I think it has something to do with the -> operator, but I'm not sure how it works.</p>

<p>Wkr</p>
",https://stackoverflow.com/questions/41678153/calling-a-function-php,['php'],37,TRUE,2,1
How to add unit tests using Moq and xUnit in this specific scenario?,"<p>I have this method in my data/service layer. We are commencing the usage of xUnit and MoQ for unit testing.  We use Autofac as our IoC container.</p>

<p>How to set up a unit test for this method using xUnit and MoQ ? 
Request specific code illustration with usage of Fake (if needed)</p>

<pre><code>public async Task&lt;AddressModel&gt; AddAddress(string useridKey, AddressModel addressModel)
{
    IAddress address = AddressConverters.ToIAddressFromAddressModel(addressModel);
    IAddress newAddress = await _userManager.AddShippingAddressAsync(userKey, address).ConfigureAwait(false);
    return AddressConverters.ToAddressModel(newAddress);
}
</code></pre>
",https://stackoverflow.com/questions/42474111/how-to-add-unit-tests-using-moq-and-xunit-in-this-specific-scenario,"['c#', '.net', 'moq', 'autofac', 'xunit']",210,TRUE,0,1
How do I write an integration test(C++) using Catch?,"<p>I do know that Catch is a unit testing framework. I have a server(C++) and a client(C++) to test. Is this integration testing? I am testing done functionalities in the server and some in the client that I want to test. Can I use CppUnit?
It is written in Windows.</p>
",https://stackoverflow.com/questions/42793008/how-do-i-write-an-integration-testc-using-catch,"['c++', 'windows', 'unit-testing', 'testing', 'integration-testing']",638,FALSE,-1,1
Does RUnit support XML output?,"<p>When running unit tests in Python code, the nosetests tool supports a --with-xunit command line flag which causes it to write a nosetests.xml file suitable for ingestion by (at least) Bamboo, perhaps by other continuous integration/deployment systems. It there something similar for RUnit or other unit testing frameworks for R?</p>
",https://stackoverflow.com/questions/47055801/does-runit-support-xml-output,['r'],23,FALSE,0,1
unit test data arrived from service to controller (Jasmine),"<p>Here is part of my code: </p>

<pre><code>angular.module('mine',[]).factory('MyFactory', ['$http','$q',  function   
     MyFactory($http,$q) {
            return {
                getData: function() {    
                    var deferred = $q.defer(),
                    url = ""http://..."";          

                $http.jsonp(url)
                .then(              
                    function (response) {
                        deferred.resolve(response.data);
                    },  
                    function (error) {
                        return $q.reject('Error retrieving data');
                    }
                );

                return deferred.promise;
            }
        };
 }]);


function MyController(MyFactory) {

    var self = this;

    self.getData= function( ) {
        MyFactory.getData().then(
            function(result) {
                self.contacts = result;
            },
            function(error) {
                console.log('Error retrieving data: ', error);
            }
        );
    };

    self.getData();
}

angular.module('mine').component('myComponent', {     
    templateUrl: '..',
    controller: MyController
  });
</code></pre>

<p>I am trying to unit test if data from factory go correctly to controller. Here is my unit testing code using Jasmine:</p>

<pre><code>describe('component', () =&gt; {
  let $componentController,contactsList,ctrl,$q,$rootScope;      

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


  beforeEach(inject((_$componentController_,_MyFactory_, _$q_, _$rootScope_) =&gt; {
    $componentController = _$componentController_;

    ctrl = $componentController('myComponent',null);
    $q = _$q_;
    contactsList = _MyFactory_; 
    $rootScope = _$rootScope_;    
  }));


it('should ... ', function() {    
       spyOn(contactsList, ""getData"").and.returnValue(
          $q.when({
            message: 'awesome message'
          }));

     ctrl.getData();
     $rootScope.$apply();
     expect(ctrl.contacts.message).toBe('awesome message');
    });  
});
</code></pre>

<p>For some reason, the above test is not running; I am getting the following error:  <code>Possibly unhandled rejection: Error retrieving data thrown</code>. Do you have any idea why? What is wrong?</p>
",https://stackoverflow.com/questions/42344009/unit-test-data-arrived-from-service-to-controller-jasmine,"['angularjs', 'unit-testing', 'jasmine']",87,FALSE,0,2
"In SQL Server unit testing project, how to make pre-test script or test script, or common script to include other script file","<p>I have a SQL Server unit testing project created by Visual Studio 2017, and but need to initialized many tables with many rows, I want the common scripts for Test Initialize could include external script file, so as the pre-test script.</p>

<p>I tried to use "":r"" but failed with syntax error.</p>

<p><a href=""https://i.stack.imgur.com/E9pEu.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/E9pEu.jpg"" alt=""enter image description here""></a></p>

<p><a href=""https://i.stack.imgur.com/Hi1c5.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Hi1c5.jpg"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/47923942/in-sql-server-unit-testing-project-how-to-make-pre-test-script-or-test-script,"['sql-server', 'visual-studio', 'unit-testing', 'visual-studio-2017']",198,FALSE,0,1
React Native: requestAnimationFrame is not supported in Node,"<p><strong>Component:</strong></p>

<pre><code>import React from 'react';
import PropTypes from 'prop-types';
import { StyleSheet, ListView } from 'react-native';
import Card from './card';

const styles = StyleSheet.create( {
  container: {
    flex: 1,
  },
} );

export default class PhotoList extends React.Component {
  static propTypes = {
    feeds: PropTypes.arrayOf( PropTypes.object ),
  };

  static defaultProps = {
    feeds: [],
  };

  constructor( props ) {
    super( props );

    const ds = new ListView.DataSource( { rowHasChanged: ( r1, r2 ) =&gt; r1 !== r2 } );
    this.state = {
      dataSource: ds.cloneWithRows( this.props.feeds ),
    };
  }

  render() {
    return (
      &lt;ListView
        enableEmptySections
        style={ styles.container }
        dataSource={ this.state.dataSource }
        renderRow={ feedItem =&gt; &lt;Card feed={ feedItem } /&gt; }
      /&gt;
    );
  }
}
</code></pre>

<p><strong>__mocks__/react.js</strong></p>

<pre><code>const react = require( 'react' );
// Resolution for requestAnimationFrame not supported in jest error :
// https://github.com/facebook/react/issues/9102#issuecomment-283873039
global.window = global;
window.addEventListener = () =&gt; {};
window.requestAnimationFrame = () =&gt; {
  throw new Error( 'requestAnimationFrame is not supported in Node' );
};

module.exports = react;
</code></pre>

<p><strong>photo-list.test.js</strong></p>

<pre><code>import React from 'react';
import { ListView } from 'react-native';
import renderer from 'react-test-renderer';
import { shallow } from 'enzyme';
import PhotoList from './photo-list';

const feed = {
  url: 'http://placehold.it/600x600',
  title: 'Some title for the card',
};

describe( '&lt;PhotoList /&gt;', () =&gt; {
  it( 'should render without throwing an error', () =&gt; {
    const component = renderer.create(
      &lt;PhotoList feed={ feed } /&gt;,
    ).toJSON();
    expect( component ).toMatchSnapshot();
  } );

  it( 'should contain a ListView', () =&gt; {
    const wrapper = shallow( &lt;PhotoList feed={ feed } /&gt; );
    expect( wrapper.find( ListView ).length ).toBe( 1 );
  } );
} );
</code></pre>

<p>Error:</p>

<pre><code> FAIL  src/components/photo-list.test.js
  ● Console

    console.error node_modules/react-native/Libraries/Core/ExceptionsManager.js:71
      React caught an error thrown by ListView. You should fix this error in your code. Consider adding an error boundary to your tree to customize error handling behavior.

      Error: requestAnimationFrame is not supported in Node

      The error is located at:
          in ListView (created by PhotoList)
          in PhotoList

      The error was thrown at:
          at Object.&lt;anonymous&gt;.window.requestAnimationFrame (/Users/rahulshetty/localshiva/test-rn-apps/__mocks__/react.js:7:7),
          at Component.requestAnimationFrame (/Users/rahulshetty/localshiva/test-rn-apps/node_modules/react-timer-mixin/TimerMixin.js:16:14),
          at Component.componentDidMount (/Users/rahulshetty/localshiva/test-rn-apps/node_modules/react-native/Libraries/CustomComponents/ListView/ListView.js:365:6),
          at commitLifeCycles (/Users/rahulshetty/localshiva/test-rn-apps/node_modules/react-test-renderer/lib/ReactFiberCommitWork.js:421:24),
          at commitAllLifeCycles (/Users/rahulshetty/localshiva/test-rn-apps/node_modules/react-test-renderer/lib/ReactFiberScheduler.js:349:9),
          at invokeGuardedCallback (/Users/rahulshetty/localshiva/test-rn-apps/node_modules/react-test-renderer/lib/ReactErrorUtils.js:21:10),
          at invokeGuardedCallback (/Users/rahulshetty/localshiva/test-rn-apps/node_modules/react-test-renderer/lib/ReactErrorUtils.js:91:34),
          at commitAllWork (/Users/rahulshetty/localshiva/test-rn-apps/node_modules/react-test-renderer/lib/ReactFiberScheduler.js:468:19),
          at completeUnitOfWork (/Users/rahulshetty/localshiva/test-rn-apps/node_modules/react-test-renderer/lib/ReactFiberScheduler.js:614:11),
          at performUnitOfWork (/Users/rahulshetty/localshiva/test-rn-apps/node_modules/react-test-renderer/lib/ReactFiberScheduler.js:641:14)
    console.warn node_modules/react-native/Libraries/Core/ExceptionsManager.js:40
      Unable to symbolicate stack trace: this.dispatchEvent is not a function

  ● &lt;PhotoList /&gt; › should render without throwing an error

    requestAnimationFrame is not supported in Node

      at Object.&lt;anonymous&gt;.window.requestAnimationFrame (__mocks__/react.js:7:7)
      at Component.requestAnimationFrame (node_modules/react-timer-mixin/TimerMixin.js:16:14)
      at Component.componentDidMount (node_modules/react-native/Libraries/CustomComponents/ListView/ListView.js:365:6)
      at commitLifeCycles (node_modules/react-test-renderer/lib/ReactFiberCommitWork.js:421:24)
      at commitAllLifeCycles (node_modules/react-test-renderer/lib/ReactFiberScheduler.js:349:9)
      at invokeGuardedCallback (node_modules/react-test-renderer/lib/ReactErrorUtils.js:21:10)
      at invokeGuardedCallback (node_modules/react-test-renderer/lib/ReactErrorUtils.js:91:34)
      at commitAllWork (node_modules/react-test-renderer/lib/ReactFiberScheduler.js:468:19)
      at completeUnitOfWork (node_modules/react-test-renderer/lib/ReactFiberScheduler.js:614:11)
      at performUnitOfWork (node_modules/react-test-renderer/lib/ReactFiberScheduler.js:641:14)
</code></pre>

<p><strong>Issue:</strong></p>

<p>I'm new to testing and I have set-up a React Native project using Create React Native App to understand unit testing. I'm not sure what's causing this error. All I wish is to test if <code>ListView</code> exists in my component. How can I add support for <code>requestAnimationFrame</code>?</p>
",https://stackoverflow.com/questions/44111231/react-native-requestanimationframe-is-not-supported-in-node,"['react-native', 'jestjs', 'enzyme']",2142,TRUE,0,1
Mocks for AEM application,"<p>we are trying to learn a Unit testing Framework for AEM applications.</p>

<p>We gone through some documentation for 
<strong>- ResourceResolver mock
- sling mocks
- JCR mocks
- OSGI mock
- AEM mocks</strong> 
But didn't get clear understanding of that, If anyone have expertise in it please do share some code demos for above topics</p>

<p>Thanks,
Gunesh Mahajan</p>
",https://stackoverflow.com/questions/42897785/mocks-for-aem-application,"['unit-testing', 'junit', 'mocking', 'aem']",2123,TRUE,-2,1
How can I comment in the file denoted by javax.persistence.sql-load-script-source,"<p>I'm using <code>javax.persistence.sql-load-script-source</code> for my unit testing.
Is there any standard way to put comments on the script?</p>

<p>The file contains insert statements for my entities.</p>

<pre class=""lang-sql prettyprint-override""><code>INSERT INTO ... (...) VALUES (...) -- 1
INSERT INTO ... (...) VALUES (...) -- 2
</code></pre>

<p>I want to comment the generated id value for myself.</p>

<p>P.S. I'm using H2, Derby, and HSQLDB as in-memory databases and EclipseLink and Hibernate as JPA implementations.</p>
",https://stackoverflow.com/questions/44038610/how-can-i-comment-in-the-file-denoted-by-javax-persistence-sql-load-script-sourc,"['sql', 'jpa', 'comments', 'persistence.xml']",190,FALSE,0,1
Spring Boot - How to test that Model attribute was added from configuration file?,"<p>I have a controller which adds attributes from <code>application.properties</code> to a <code>Model</code> object:</p>

<pre><code>@Value(""${products}"")
private String prod;

@GetMapping(""/"")
public String greetingForm(Model model) throws IOException {

    List&lt;String&gt; products = Arrays.asList(prod.split(""\\s*,\\s*""));

    model.addAttribute(""products"",products);

    return ""form"";
}
</code></pre>

<p>How can I test this method? I'm fairly new to unit testing so any advice would be appreciated. I know I have to mock <code>Model</code> somehow but every time I try to run my test, I get a <code>NullPointerException</code>. </p>

<p>My test:</p>

<pre><code>private MockMvc mockMvc;

@MockBean
private Model model;

@Before
public void setUp() {
    this.mockMvc = MockMvcBuilders.standaloneSetup(new WebController()).build();
}



@Test
public void testHomeRoute() {

        try {

            List&lt;String&gt; products = new ArrayList&lt;String&gt;();
            products.add(""Product1"");
            products.add(""Product2"");

            mockMvc.perform(get(""/""))
                .andExpect(MockMvcResultMatchers.view().name(""form""))
                .andExpect(MockMvcResultMatchers.model().attribute(""products"",products));
                ;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}
</code></pre>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/46434553/spring-boot-how-to-test-that-model-attribute-was-added-from-configuration-file,"['spring-boot', 'junit', 'mocking', 'mockito']",874,FALSE,0,1
How to make a unit test for a method that is catching Exception.class?,"<p>I am unit testing a class which is as below : </p>

<pre><code>class ClassUnderTest {
    public SomeOtherClass var;
    public String methodUnderTest(){
        try {
            //call to some other method that throws CustomException
            String localvariable = var.someOtherMethod() //throws CustomException
            // generic operations on localvariable which can throw Exception
        } catch (CustomException e) {
            s.o.p(e);
        } catch (Exception e) {
            s.o.p(e);
        }

    }
}
</code></pre>

<p>The problem arises when I have to test the methodUnderTest for catching Exception.class. I can not mock SomeOtherClass to throw Exception as Exception is a checked exception and someOtherMethod throws only CustomException.
How can I make a test case for this scenario ?</p>
",https://stackoverflow.com/questions/42865142/how-to-make-a-unit-test-for-a-method-that-is-catching-exception-class,"['java', 'mocking', 'junit4']",164,TRUE,0,2
Oracle JDeveloper studio 12c with JBOSS EAP?,"<p>I have java web application which runs on JBOSS EAP6. I wanted to use Oracle JDeveloper studio for my coding and unit testing of application. Could you please let me know if i am good to use Oracle JDeveloper studio to run my application by configuring JBOSS EAP in the IDE?</p>

<p>Thanks,
Venkat</p>
",https://stackoverflow.com/questions/47955288/oracle-jdeveloper-studio-12c-with-jboss-eap,"['java', 'jdeveloper', 'jboss-eap-6']",235,TRUE,-2,1
Can you implement Vue Unit tests without a component using purely the Vue Instance?,"<p>I briefly looked at the documentation on <a href=""https://v2.vuejs.org/v2/guide/unit-testing.html"" rel=""nofollow noreferrer"">Vue Unit Testing</a></p>
<p>It said:</p>
<blockquote>
<p>Anything compatible with a module-based build system will work</p>
</blockquote>
<p>The documentation describes ways to test components</p>
<p>In my case I am not using a component.
I am adding the <code>vue.js</code> to the page and I create a new Vue Instance.</p>
<pre><code>new Vue({
  el: '#app',
  data: {
    ....
  }
});
</code></pre>
",https://stackoverflow.com/questions/45547268/can-you-implement-vue-unit-tests-without-a-component-using-purely-the-vue-instan,"['unit-testing', 'vue.js', 'vue-component']",328,TRUE,0,1
Unit test &quot;No Symbol loaded&quot; is driving me crazy,"<p>When I'm unit testing in VS2017, if I mistakenly press F11 while on method calling something that I DONT want to step in, it will step inside and I get this painful and irritating message.</p>

<p><a href=""https://i.stack.imgur.com/ak8Qy.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ak8Qy.png"" alt=""enter image description here""></a></p>

<blockquote>
  <p>WinTypes.pdb contains the debug information required to find the source for the module WinTypes.dll</p>
</blockquote>

<p>This happens when I have call to windows runtime libraries or framework libraries. I DONT want to step inside these libraries. and no matter how many times I press F10 again or close this page, this message wont let me continue . </p>

<p>All I have to do is to reset debug process and start from over again... I was bearing with this for a while but ive had enough. this is driving me CRAZY. please show me way how to stop this stupid error.</p>

<p>.Net framework source stepping is also unchecked, but I'm unit testing UWP project.</p>

<p><a href=""https://i.stack.imgur.com/r2hmu.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/r2hmu.png"" alt=""enter image description here""></a></p>

<p>PS: Just my code is also enabled FFS -.-</p>
",https://stackoverflow.com/questions/46501999/unit-test-no-symbol-loaded-is-driving-me-crazy,"['c#', 'visual-studio', 'unit-testing', 'debugging', 'uwp']",1891,TRUE,4,1
Unit test private methods in roboletric android,"<p>Unit testing private methods may not be good practise but few methods in product has complex login in private methods.</p>

<p>Can we somehow reflect or call private methods in roboletric in android OR any library similar to roboletric which helps in testing private methods ?</p>

<p>Any hints or help would be greatly appreciated </p>
",https://stackoverflow.com/questions/43533993/unit-test-private-methods-in-roboletric-android,"['android', 'robolectric']",1793,TRUE,0,1
How to compare lists of custom classes without defining equals() and hashCode()?,"<p>Since defining <code>equals()</code> and <code>hashCode()</code> only for testing purpose is considered as a code smell, I prefer to use <code>ReflectionEquals</code> or custom matchers to compare objects while doing unit testing.</p>

<p>However, I don't know how to use <code>ReflectionEquals</code> or custom matchers in comparing lists of user-defined classes.</p>

<p>For example, how do I assert the following code without defining <code>equals()</code> and <code>hashCode()</code> (maybe only use <code>ReflectionEquals</code> or custom matchers)?</p>

<pre class=""lang-java prettyprint-override""><code>// When
List&lt;Record&gt; actual = sut.findBySomeId();

// Then
List&lt;Record&gt; expected = asList(
    aRecord()...build(), 
    aRecord()...build()
);
assertThat(expected, /* how to compare? */);
</code></pre>
",https://stackoverflow.com/questions/42388086/how-to-compare-lists-of-custom-classes-without-defining-equals-and-hashcode,"['java', 'unit-testing', 'assert', 'equality']",6140,TRUE,6,4
Vue.js Avoriaz unit test produces translation warnings when vue-i18n is used,"<h1>Summary</h1>

<p>I am using <a href=""https://github.com/kazupon/vue-i18n"" rel=""nofollow noreferrer"">vue-i18n</a> for i18n and <a href=""https://github.com/eddyerburgh/avoriaz"" rel=""nofollow noreferrer"">Avoriaz</a> for unit testing my Vue.js components. I get many warnings because of not translated strings, which I can't fix. How can I get rid of these warnings?</p>

<h1>Warning example</h1>

<blockquote>
  <p>'[vue-i18n] Cannot translate the value of keypath 'description.first'.
  Use the value of keypath as default.'</p>
</blockquote>

<h1>Test setup</h1>

<pre><code>import Vue from 'vue'
import Vuex from 'vuex'
import {
  mount
} from 'avoriaz'
import sinon from 'sinon'
import VueResource from 'vue-resource'
import BootstrapVue from 'bootstrap-vue'
import VueI18n from 'vue-i18n'
import store from './../../../state/index'
import Register from '@/components/Register'

Vue.use(BootstrapVue)
Vue.use(VueResource)
Vue.use(VueI18n)

describe('Register', () =&gt; {
  it('should accept inputs', () =&gt; {
    store.locale = 'en'
    const wrapper = mount(Register, {
      store
    })

    let name = 'Hans'
    let password = '123'

    let nameInput = wrapper.find('input')[0]
    let passwordInput = wrapper.find('input')[1]

    nameInput.element.value = name
    passwordInput.element.value = password

    nameInput.trigger('input')
    passwordInput.trigger('input')

    expect(wrapper.vm.$store.state.user.name).to.equal(name)
    expect(wrapper.vm.$store.state.user.password).to.equal(password)
  })
})
</code></pre>

<h1>Tested component</h1>

<pre><code>&lt;template&gt;
  &lt;div class=""row justify-content-md-center""&gt;
    &lt;div class=""col-6""&gt;
      &lt;b-form-fieldset
        :description=""$t('description.first')""
        :label=""$t('label.first')""
        :label-size=""1""&gt;
        &lt;b-form-input v-model=""name""&gt;&lt;/b-form-input&gt;
      &lt;/b-form-fieldset&gt;
      &lt;b-form-fieldset
        :description=""$t('description.second')""
        :label=""$t('label.second')""
        :label-size=""1""&gt;
        &lt;b-form-input v-model=""password"" type=""password""&gt;&lt;/b-form-input&gt;
      &lt;/b-form-fieldset&gt;
      &lt;b-button variant=""outline-success"" size=""sm"" @click=""create""&gt;{{ $t('button.first') }}&lt;/b-button&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
  export default {
    i18n: {
      messages: {
        en: {
          'description.first': 'Enter a name',
          'label.first': 'Name *',
          'description.second': 'Enter a password',
          'label.second': 'Password *',
          'button.first': 'Create'
        },
        de: {
          'description.first': 'Gebe einen Namen ein',
          'label.first': 'Name *',
          'description.second': 'Gebe ein Passwort ein',
          'label.second': 'Passwort *',
          'figcaption.first': 'Du kannst einen dieser Nutzer wählen, um dich einzuloggen.',
          'button.first': 'Erstellen'
        }
      }
    },

    computed: {
      user: {
        get () {
          return this.$store.state.user
        }
      },

      name: {
        get () {
          return this.$store.state.user.name
        },

        /**
         * @param name
         */
        set (name) {
          this.$store.commit('SET_USER_NAME', name)
        }
      },

      password: {
        get () {
          return this.$store.state.user.password
        },

        /**
         * @param password
         */
        set (password) {
          this.$store.commit('SET_USER_PASSWORD', password)
        }
      }
    },

    methods: {
      create () {
        this.$store.dispatch('saveUser', this.user)
      }
    }
  }
&lt;/script&gt;
</code></pre>
",https://stackoverflow.com/questions/45184859/vue-js-avoriaz-unit-test-produces-translation-warnings-when-vue-i18n-is-used,"['javascript', 'unit-testing', 'vue.js', 'vue-i18n', 'avoriaz']",934,TRUE,3,1
Jasmine and spy method,"<pre><code>angular.module('mine', []).factory('MyFactory', ['$http', '$q', function
    MyFactory($http, $q) {
        return {
            getData: function() {
                var deferred = $q.defer(),
                    url = ""http://..."";
                $http.jsonp(url)
                    .then(
                        function(response) {
                            deferred.resolve(response.data);
                        },
                        function(error) {
                            return $q.reject('Error retrieving data');
                        }
                    );
                return deferred.promise;
            }
        };
    }
]);

function MyController(MyFactory) {
    var self = this;
    self.getData = function() {
        MyFactory.getData().then(
            function(result) {
                self.contacts = result;
            },
            function(error) {
                console.log('Error retrieving data: ', error);
            }
        );
    };
}
</code></pre>

<p>I am trying to unit test if data from factory go correctly to controller. Here is my unit testing code using Jasmine:</p>

<pre><code>describe('component', () =&gt; {
  let $componentController,contactsList,ctrl,$q,$rootScope;      

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


  beforeEach(inject((_$componentController_,_MyFactory_, _$q_, _$rootScope_) =&gt; {
    $componentController = _$componentController_;

    ctrl = $componentController('myComponent',null);
    $q = _$q_;
    contactsList = _MyFactory_; 
    $rootScope = _$rootScope_;    
  }));


it('should ... ', function() {    
       spyOn(contactsList, ""getData"").and.returnValue(
          $q.when({
            message: 'awesome message'
          }));

     ctrl.getData();
     $rootScope.$apply();
     expect(ctrl.contacts.message).toBe('awesome message');
    });  
});
</code></pre>

<p>However, I am doing something wrong and I am getting the error: I am getting the following error:  <code>Possibly unhandled rejection: Error retrieving data thrown</code>.I guess the problem lies on spy method. I'd appreciate any help.</p>
",https://stackoverflow.com/questions/42352675/jasmine-and-spy-method,"['angularjs', 'unit-testing', 'jasmine']",88,FALSE,0,0
How to compare two intent using assertj-android,"<p>Hi I am using roboelectric for unit testing of my android application. I want to compare expected intent and actual intent using <code>assertj-android</code>. I have added required dependency of <code>assertj-android</code>, even though I have done Gradle sync multiple times but still unable to import <code>org.assertj.android.api.content.IntentAssert</code>.</p>

<p>What could be the issue ? Any idea ? Thanks in advance</p>

<h2>build.gradle</h2>

<pre><code>dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.1'
    testCompile 'junit:junit:4.12'
    testCompile 'org.robolectric:robolectric:3.2.2'
    testCompile 'org.khronos:opengl-api:gl1.1-android-2.1_r1'
    androidTestCompile 'com.squareup.assertj:assertj-android:1.1.1'
}
</code></pre>

<p><a href=""https://i.stack.imgur.com/hXuyq.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/hXuyq.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/42432523/how-to-compare-two-intent-using-assertj-android,"['android', 'android-intent', 'robolectric', 'android-assertj']",158,TRUE,0,1
How to unit test pessimistic locking with Spring Boot + Spring Data JPA,"<p>I want to test whether the <strong><code>FooRepository.lock()</code></strong> works, after someone called the <code>lock()</code>, others calling it should be wait.</p>

<p>The following is my best try, it doesn't work. I believe the reason is both <code>entityManger</code> and <code>fooRepository</code> are participating in the same transaction.</p>

<p>How to call the <code>lock()</code> from another transaction? Or any suggestion for unit-testing the pessimistic lock? Thanks!!</p>

<p>FooRepositoryTest:</p>

<pre><code>package com.example.demo;

import java.util.UUID;

import javax.persistence.LockModeType;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.context.junit4.SpringRunner;

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

    @Autowired
    private TestEntityManager entityManager;    

    @Autowired
    private FooRepository fooRepository;

    @Test
    public void lockTest() {
        // given
        Foo foo = new Foo();
        foo.setName(""foo-name"");

        UUID fooId = fooRepository.save(foo).getFooId();
        entityManager.flush();
        entityManager.clear();

        // when
        Foo savedFoo = fooRepository.findOne(fooId);
        fooRepository.lock(savedFoo);

        // then
        // I want something like this to be lock wait,
        // something to confirm the above fooRepository.lock() work
        entityManager.getEntityManager().lock(savedFoo, LockModeType.PESSIMISTIC_WRITE);
    }

}
</code></pre>

<p>class Foo:</p>

<pre><code>package com.example.demo;

import java.util.UUID;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Foo {  
    @Id
    @GeneratedValue
    private UUID fooId;

    private String name;

    public UUID getFooId() {
        return fooId;
    }

    public void setFooId(UUID fooId) {
        this.fooId = fooId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}
</code></pre>

<p>class FooApplication:</p>

<pre><code>package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class FooApplication {

    public static void main(String[] args) {
        SpringApplication.run(FooApplication.class, args);
    }
}
</code></pre>

<p>class FooRepository:</p>

<pre><code>package com.example.demo;

import java.util.UUID;

import org.springframework.data.jpa.repository.JpaRepository;

public interface FooRepository extends JpaRepository&lt;Foo, UUID&gt;, FooRepositoryCustom {  
}
</code></pre>

<p>class FooRepositoryCustom:</p>

<pre><code>package com.example.demo;

public interface FooRepositoryCustom {  
    public void lock(Foo foo);  
}
</code></pre>

<p>class FooRepositoryImpl:</p>

<pre><code>package com.example.demo;

import javax.persistence.EntityManager;
import javax.persistence.LockModeType;

import org.springframework.beans.factory.annotation.Autowired;

public class FooRepositoryImpl implements FooRepositoryCustom {

    @Autowired
    private EntityManager entityManager;

    @Override
    public void lock(Foo foo) {
        entityManager.lock(foo, LockModeType.PESSIMISTIC_WRITE);
    }   
}
</code></pre>
",https://stackoverflow.com/questions/45477459/how-to-unit-test-pessimistic-locking-with-spring-boot-spring-data-jpa,"['java', 'unit-testing', 'spring-boot', 'spring-data-jpa']",4350,TRUE,9,2
Mocked HttpClient wrapper returning null with xunit,"<p>I'm trying to get used to unit testing with .net core. Unfortunately I'm stuck on getting my <code>HttpClient</code> wrapper to return a failed <code>HttpResponseMessage</code>.</p>

<p>Here's my test that I'm trying to get working:</p>

<pre><code>[Fact]
public async void TestHttpExceptionOnBadRequest()
{
    using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(""Test"")))
    {
        var xmlSerializer = new Mock&lt;IXmlSerializer&gt;();
        xmlSerializer.Setup(serializer =&gt; serializer.Deserialize(stream)).Returns(new object());

        var httpClient = new Mock&lt;IHttpHandler&gt;();
        httpClient.Setup(client =&gt; client.GetAsync(""Test""))
            .Returns(Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadRequest)));

        var postcodeLookup = new PostcodeLookupService(xmlSerializer.Object, httpClient.Object, """", """");
        await Assert.ThrowsAsync&lt;HttpRequestException&gt;(async () =&gt; await postcodeLookup.SearchAsync("""", """"));
    }
}
</code></pre>

<p>Following is my service code. The issue is that <code>response.EnsureSuccessStatusCode();</code> returns null.</p>

<pre><code>public async Task&lt;PostcodeContainer&gt; SearchAsync(string text, string container)
{
    // add the query parameters to the query string
    var query = _baseQueryString + ""&amp;text="" + WebUtility.UrlEncode(text);
    query += ""&amp;container="" + WebUtility.UrlEncode(container);

    // initiate client &amp; response
    var response = await _httpClient.GetAsync(query);
    response.EnsureSuccessStatusCode();

    return (PostcodeContainer)_serializer.Deserialize(await response.Content.ReadAsStreamAsync());
}
</code></pre>

<p>And for completeness here is my <code>IHttpHandler</code> definition for the purposes of mocking.</p>

<pre><code>public interface IHttpHandler
{
    HttpResponseMessage Get(string url);
    HttpResponseMessage Post(string url, HttpContent content);
    Task&lt;HttpResponseMessage&gt; GetAsync(string url);
    Task&lt;HttpResponseMessage&gt; PostAsync(string url, HttpContent content);
}
</code></pre>
",https://stackoverflow.com/questions/43251198/mocked-httpclient-wrapper-returning-null-with-xunit,"['c#', '.net', 'unit-testing', 'moq', 'xunit']",1524,TRUE,1,1
"React test with Enzyme, cannot read property &#39;route&#39; of undefined","<p>In my React App (No flux / redux), I'm trying to do unit testing to a component using <code>enzyme</code>, the <strong>shallow rendering</strong> works well, I am able to retrieve it's state etc, but <strong>mount rendering</strong> throw me an error of <code>cannot read property 'route' of undefined</code>.</p>

<p>my <code>App.js</code> looks like this</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>class App extends Component {
  render() {
    return (
      &lt;BrowserRouter&gt;
        &lt;Switch&gt;
          &lt;MyCustomLayout&gt;
            &lt;Route path=""/mypath"" component={myComponent} /&gt;
          &lt;/MyCustomLayout&gt;
        &lt;/Switch&gt;
      &lt;/BrowserRouter&gt;
    )
  }</code></pre>
</div>
</div>
</p>

<p>Here is the code for <code>myComponent</code></p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>import React, { Component } from 'react';
import './index.css';
import { getList } from './apiService.js';
 
class myComponent extends Component {
  constructor(props) {
      super(props);
      this.state = {
        myList: [],
      };
  }
  
  componentDidMount() {
  // get list ajax call
    getList().then(response =&gt; {
      this.setState({
        myList: response.data
      })
    });
  }
  
  handleClick = () =&gt; {
    this.props.history.push('/home');
  }
  
  renderMyList() {
    /*
      Code for rendering list of items from myList state
    */
  }
  
  render() {
    return (
      &lt;div&gt;
        &lt;h1&gt;Hello World&lt;/h1&gt;
        &lt;button onClick={this.handleClick}&gt;Click me&lt;/button&gt;
        {this.renderMyList()}
      &lt;/div&gt;
    )
  }
}

export default myComponent</code></pre>
</div>
</div>
</p>

<p>Here is the code for my test</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>import React from 'react';
import myComponent from './myComponent';
import renderer from 'react-test-renderer';
import { shallow, mount } from 'enzyme';
import sinon from 'sinon';

test('Initial state of myList should be empty array ', () =&gt; {
  const component = shallow(&lt;myComponent/&gt;);
  expect(component.state().myList).toEqual([]);
});

test('Make sure the componentDidMount being called after mount', () =&gt; {
  sinon.spy(myComponent.prototype, 'componentDidMount');
  const component = mount(&lt;myComponent/&gt;);
  expect(myComponent.prototype.componentDidMount.calledOnce).toEqual(true);
});</code></pre>
</div>
</div>
</p>

<p>What does the error ?</p>
",https://stackoverflow.com/questions/45010814/react-test-with-enzyme-cannot-read-property-route-of-undefined,"['unit-testing', 'reactjs', 'enzyme']",2204,TRUE,3,1
laravel - phpunit - mock network calls,"<p>I have a Laravel (5.4) app that I am unit/feature testing. I am relatively new to unit testing.</p>

<p>The procedure I am testing makes a network call (using Guzzle), and I perform some actions on the result.</p>

<p>What would be the suggested way of mocking the network call, and returning a predefined response?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/47192758/laravel-phpunit-mock-network-calls,"['laravel', 'mocking', 'phpunit']",155,FALSE,1,0
How can I write Unit Test for persist and flush exceptions,"<p>I have the following code:</p>

<pre><code>try {
  em.persist(myObject);
  em.flush();
}
catch (Exception e) {
  System.out.println(""An Exception occur when trying to persist and flush"");
}
</code></pre>

<p>In test I have mock my EntityManager with Mockito:</p>

<pre><code>    @Mock
EntityManager mockEm;
</code></pre>

<p>but as persist and flush are void methods, I'm not able able to write something like:</p>

<pre><code>when(mockEm.persist(anObject).then(doSomeThing);
</code></pre>

<p>How can I write unit testing (with JUnit)to mock em.persist and em.flush in order to test both cases with and without exception?
Thanks.</p>
",https://stackoverflow.com/questions/46428503/how-can-i-write-unit-test-for-persist-and-flush-exceptions,"['java', 'unit-testing', 'persistence']",1581,TRUE,1,1
Check @RequestMapping - unit test,"<p>I have a task to do:
This controller should have its own unit test to verify, that <code>@RequestMapping</code> is set to <code>/ api / report / article_pairs</code>.</p>

<pre><code> @RestController
 @RequestMapping(""/api/report/article_pairs"")
 public class ArticlePairsController extends ReportController&lt;ArticlePairs&gt;{

public ArticlePairsController(HttpReportExecutor&lt;ArticlePairs&gt; articlePairs) {
    super(articlePairs);
}

@PostMapping()
public HttpEntity&lt;Void&gt; proceed(@RequestBody ArticlePairs articlePairs) {

    articlePairs.setDbconn(schemaName + ""."" + CENTRALA);

    return executeReport(articlePairs, ""report.articlePairs"");
  }
}
</code></pre>

<p>If someone in the future would change this value, a unit test should show this.</p>

<p>Unit testing is a new issue for me, so could I ask for some advice? thank you in advance.</p>
",https://stackoverflow.com/questions/44970438/check-requestmapping-unit-test,"['java', 'unit-testing', 'spring-mvc', 'tdd']",3864,TRUE,1,1
"C++ Boost Test, package structure, and Eclipse project settings","<p>I'm using C++98, and besides the standard library, I only have access to an old version of Boost (which thankfully has Boost Test). The documentation though is daunting, long, and I just don't know where to begin.</p>

<p>I have some experience doing unit testing in Java (and I'm looking for unit testing in C++), and I've seen <code>test</code> packages that contain the unit test code separate from the <code>src</code> package, and I also saw <a href=""https://stackoverflow.com/questions/2843795/where-do-you-put-your-unit-test"">Where do you put your unit test?</a> as well as <a href=""https://stackoverflow.com/questions/12297476/unit-testing-with-boost-and-eclipse"">Unit Testing with Boost and Eclipse</a>. Their suggestions vary, and present reasoning for different packaging structures for separating test code from production code, or having them together.</p>

<p>Before I even started looking into Boost Test, I created this structure within Eclipse (perhaps erroneously):</p>

<pre><code>-- ProjectName
   |-- Debug
   |-- src
   |-- test
</code></pre>

<p>and I wrote another main method to run test functions. Eclipse didn't like that, because I had two main methods in the same project. I fumbled around through Project Properties and didn't find anything useful for separating my production code from test code when building (linking, really). My temporary fix was to just use <code>g++</code> in the terminal and ad hoc compile just my ""test"" code.</p>

<p>I found something suggesting on <a href=""https://stackoverflow.com/questions/1251147/boosttest-generation-of-main"">Boost::Test -- generation of Main()?</a> that Boost actually generated its own main method, so this is currently my plan of attack for unit testing, especially for having a library of testing tools already available.</p>

<blockquote>
  <ul>
  <li>What is the conventional way of organizing unit tests for C++?</li>
  <li>How do I get started with Boost Test? (Boost is already installed)</li>
  <li>Is there anything I need to change in Eclipse to be able to run my Boost unit tests separate from my production code within the IDE? (One of the nice things about IntelliJ, with Java, is how it'll automatically run any main method you like with a click) -- The goal here to be able to build and run my tests within Eclipse.</li>
  <li>Should my tests be in a separate Eclipse project? (this was suggested in an answer to the second SO question I linked)</li>
  </ul>
</blockquote>

<p><strong>Edit</strong>: I found <a href=""http://www.alittlemadness.com/2009/03/31/c-unit-testing-with-boosttest/"" rel=""nofollow noreferrer"">this</a> article for an introduction to Boost Test, but it doesn't discuss how it can be handled within an IDE setting.</p>
",https://stackoverflow.com/questions/44788731/c-boost-test-package-structure-and-eclipse-project-settings,"['eclipse', 'package', 'program-entry-point', 'c++98', 'boost-test']",1748,TRUE,4,1
xUnit and multiple data records for a test,"<p>I'm fairly new to Unit Testing and have the following code:</p>
<pre><code>public class PowerOf
{
    public int CalcPowerOf(int @base, int exponent) {
        if (@base == 0) { return 0; }
        if (exponent == 0) { return 1; }
        return @base * CalcPowerOf(@base, exponent - 1);
    }
}
</code></pre>
<p>The unit test (with xUnit) I wrote for it first was this one, but I'm not quite sure if it's the right approach, or if I should use another pattern?
<strong>What I wanted to know</strong> is whether this is the correct usage for passing multiple sets of data into a &quot;unit test&quot; - as I didn't see any docs or reference examples on xUnit's docs?</p>
<pre><code>    [Fact]
    public void PowerOfTest() {
        foreach(var td in PowerOfTestData()) {
           Assert.Equal(expected, CalcPowerOf(@base, exponent));
        }
    }

    public class TestData {
      int Base {get;set;}
      int Exponent {get;set;}
      int ExpectedResult {get;set;}
    }

    public List&lt;TestData&gt; PowerOfTestData() {
        yield return new TestData { Base = 0, Exponent = 0, TestData = 0 };
        yield return new TestData { Base = 0, Exponent = 1, TestData = 0 };
        yield return new TestData { Base = 2, Exponent = 0, TestData = 1 };
        yield return new TestData { Base = 2, Exponent = 1, TestData = 2 };
        yield return new TestData { Base = 5, Exponent = 2, TestData = 25 };
    }
</code></pre>
",https://stackoverflow.com/questions/42467244/xunit-and-multiple-data-records-for-a-test,"['c#', 'unit-testing', 'xunit']",16171,TRUE,15,3
Angular Translate Unit Test - Can&#39;t inject $translateProvider,"<p>I'm using ES6, AngularJS, Karma/Jasmine, and angular-translate. Can't seem to get my unit test to pass. Not really too sure how to work with 3rd party modules, like angular-translate, when it comes to unit testing. The code and the error I'm getting are below. $translateProvider is not loading.</p>

<pre><code>import CatalogueModule from './catalogue.module'
import CatalogueService from './catalogue.service'

let service,
    _$translateProvider;

describe('CatalogueService', () =&gt; {
  beforeEach(angular.mock.module(CatalogueModule));

  beforeEach(() =&gt; {
    angular.mock.module({
      $translateProvider: jasmine.createSpyObj('$translateProvider',
        ['translations', 'preferredLanguage']
      ),
      $translate: jasmine.createSpyObj('$translate',
        ['use']
      )
    });
  })

  beforeEach(inject(($translateProvider) =&gt; {
    _$translateProvider = $translateProvider;

    _$translateProvider.translations('en', {});
    _$translateProvider.preferredLanguage('en');

    // service = new CatalogueService();
  }));

  it('should set the config object after initialization', inject(($translateProvider, CatalogueService) =&gt; {
    // $translateProvider.use.and.returnValue();
    // expect(service.config.headers).to.equal(null);
  }));
});
</code></pre>

<p>This is the error:</p>

<pre><code>✖ ""before each"" hook: WorkFn for ""should set the config object after initialization""
      Chrome 59.0.3071 (Mac OS X 10.12.3)
    Error: [$injector:unpr] Unknown provider: $translateProviderProvider &lt;- $translateProvider
</code></pre>

<p>UPDATE - Adding catalogue.service.js</p>

<pre><code>class CatalogueService {
  constructor($http, $q, $translate) {
    'ngInject';

    this._$http      = $http;
    this._$q         = $q;
    this._$translate = $translate;

    this.config = {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': '******',
        'P3-APP-ID': '*****',
        'P3-Date': '*****'
      }
    };

    this.catalogue = this.getCatalogue();
  }

  getCatalogue() {
    const lang = this._$translate.use();
    const url = `https://somedomain.com/catalog?language_code=${lang}`;
    const deferred = this._$q.defer();

    this._$http
      .get(url, this.config)
      .then(
        (res) =&gt; deferred.resolve(res.data.characters),
        (err) =&gt; deferred.reject(err)
      );

    return deferred.promise;
  };

  getCharacterByCharId(charId) {
    return this.catalogue
      .then((res) =&gt; {
        return res.find((character) =&gt; {
          return character.link_name === charId;
        });
      });
  };
}

export default CatalogueService;
</code></pre>
",https://stackoverflow.com/questions/44954265/angular-translate-unit-test-cant-inject-translateprovider,"['javascript', 'angularjs', 'unit-testing', 'es6-modules']",1242,TRUE,2,2
What is the purpose of @Rule in Android Espresso UI Test?,"<p>New to Android Unit Testing with Espresso, under @Rule, what is the purpose of creating a member variable? Does the name of the variable matter? I get the inkling that I need to tell the test unit which activity (or service, class) I'm testing, but is the variable and its scope used anywhere I need to care about?</p>

<pre><code>    @Rule
    public ActivityTestRule&lt;MenuActivity&gt; mActivityTestRule = new ActivityTestRule&lt;&gt;(MenuActivity.class);
</code></pre>
",https://stackoverflow.com/questions/46208247/what-is-the-purpose-of-rule-in-android-espresso-ui-test,"['android', 'android-espresso']",1848,TRUE,2,1
karma-remap-istanbul is generating the coverage htmls next to source,"<p>I am trying to setup unit testing for my Aurelia (+ webpack + TypeScript) website. My <code>karma.conf.js</code> looks as follows (similar to what is done in aurelia-navigation skeleton):</p>

<pre><code>""use strict"";
const path = require('path');

module.exports = function (config) {
  config.set({
    basePath: __dirname,
    frameworks: ['jasmine'],
    exclude: [],

    files: [{
      pattern: 'spec-bundle.js',
      watched: false
    } ],

    preprocessors: {
      'spec-bundle.js': ['coverage', 'webpack', 'sourcemap']
    },

    webpack: require('../webpack.config'),

    coverageReporter: {
      reporters: [
        {
          type: 'json',
          subdir: '.',
          file: 'coverage-final.json'
        },
        {
          type: 'html',
          dir: path.join(__dirname, 'coverage/'),
          subdir: '.'
        }
      ]
    },

    remapIstanbulReporter: {
      src: path.join(__dirname, 'coverage/coverage-final.json'),
      reports: {
        html: path.join(__dirname, 'coverage/remapped/')
      }
      // ,
      // timeoutNotCreated: 1000,
      // timeoutNoMoreFiles: 1000
    },

    webpackServer: { noInfo: true },

    reporters: ['mocha', 'coverage', 'karma-remap-istanbul'],    

    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: false,
    browsers: [
      // 'Chrome',
      'SlimerJS'
    ],
    singleRun: true
  });


  console.log(config);
};
</code></pre>

<p>My folder structure is as follows:</p>

<pre><code>Website
|-src
|-test
| |-coverage
| |-unit 
| | |-*.spec.ts
| |-karma.conf.js
| |-spec.bundle.js //as given by aurelia-navigation skeleton
|-webpack.config.js
</code></pre>

<p>The problem is that <code>karma-remap-istanbul</code> is dumping the coverage htmls next to the source, instead of outputting everything in <code>test/coverage/remapped/</code>. </p>

<p>Am I missing any configuration for this?</p>
",https://stackoverflow.com/questions/42296192/karma-remap-istanbul-is-generating-the-coverage-htmls-next-to-source,"['javascript', 'karma-runner', 'aurelia', 'istanbul', 'karma-coverage']",674,FALSE,2,1
EF reverse POCO generator Unit Test,"<p>I am using <a href=""https://marketplace.visualstudio.com/items?itemName=SimonHughes.EntityFrameworkReversePOCOGenerator"" rel=""nofollow noreferrer"">EntityFramework Reverse POCO Generator</a> which has a flag</p>

<pre><code>AddUnitTestingDbContext = true; // Will add a FakeDbContext and FakeDbSet for easy unit testing
</code></pre>

<p>It creates <strong>FakeDbContext</strong> and <strong>FakeDbSet</strong> for unit testing, but inside <strong>FakeDbContext</strong> some of the methods are not implemented. </p>

<pre><code> public System.Data.Entity.Infrastructure.DbEntityEntry&lt;TEntity&gt; Entry&lt;TEntity&gt;(TEntity entity) where TEntity : class
    {
        throw new System.NotImplementedException();
    }
    public System.Data.Entity.Infrastructure.DbEntityEntry Entry(object entity)
    {
        throw new System.NotImplementedException();
    }
    public System.Collections.Generic.IEnumerable&lt;System.Data.Entity.Validation.DbEntityValidationResult&gt; GetValidationErrors()
    {
        throw new System.NotImplementedException();
    }
    public System.Data.Entity.DbSet Set(System.Type entityType)
    {
        throw new System.NotImplementedException();
    }
    public System.Data.Entity.DbSet&lt;TEntity&gt; Set&lt;TEntity&gt;() where TEntity : class
    {
        throw new System.NotImplementedException();
    }
    public override string ToString()
    {
        throw new System.NotImplementedException();
    }
</code></pre>

<p>What would be the correct way to overwrite them or implement them so that I can use those calls in my unit tests. </p>

<p>Thank you for your time. </p>
",https://stackoverflow.com/questions/46696189/ef-reverse-poco-generator-unit-test,"['c#', 'entity-framework', 'unit-testing', 'poco']",529,TRUE,2,1
PHP Post Request Sending,"<p>I use PHP5.3 with CodeIgniter framework, also using TOAST  - CodeIgniter Unit Testing library.</p>

<p>I need to test my controllers, it requires POST for variable passing. I tried cUrl and stream_context_create, both failed. (curl is enabled) However I can do it succesfully using POSTMAN with same body data. So, receiver works well, i have problem on sender.</p>

<pre><code>curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, 'http://localhost:8080/myApp/index.php?/systemAdministration/runScheduledETL');
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_POST, 1);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, array('id' =&gt; $id));

$buffer = curl_exec($curl_handle);
curl_close($curl_handle);
</code></pre>

<p>Also, i tried:</p>

<pre><code>url = 'http://localhost:8080/myApp/index.php?/systemAdministration/runScheduledETL';
$data = array('id' =&gt; $id);

$options = array(
    'http' =&gt; array(
       'header'  =&gt; ""Content-type: application/x-www-form-urlencoded"",
       'method'  =&gt; 'POST',
       'content' =&gt; http_build_query($data)
    )
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
</code></pre>
",https://stackoverflow.com/questions/42415268/php-post-request-sending,"['php', 'codeigniter', 'curl', 'post']",156,FALSE,2,1
Flask: testing with unittest - how to get .post json from response,"<p>I am doing unit testing in flask with python3.
I have method that returns json:</p>

<pre><code>@app.route('/doctor/book_appointment', methods=['POST'])
def some_method():
  resp = {
          ""status"": """",
          ""message"": """"
        }
  return jsonify(resp)
</code></pre>

<p>So inside my unittest I try this:</p>

<pre><code>headers = {
        'ContentType': 'application/json',
        'dataType': 'json'
}
data = {
    'key1': 'val1',
    'key2': 'val2'
}
response = self.test_app.post('/doctor/book_appointment',
                                      data=json.dumps(data),
                                      content_type='application/json',
                                      follow_redirects=True)
        self.assertEqual(response.status_code, 200)
# hot to get json from response here
# I tried this, but doesnt work
json_response = json.loads(resp.data)
</code></pre>

<p>My response object is of Response streamed type. How do I get json from it. Since some_method returns jsonified data. BTW it works when some javascript framework consumes my api, i.e I could get json from response. But now I need to test code in python here.</p>
",https://stackoverflow.com/questions/42855144/flask-testing-with-unittest-how-to-get-post-json-from-response,"['python', 'flask', 'python-unittest']",6509,TRUE,11,1
Programmatically add values to Angular 2 NgForm object,"<p>I have a form that works great. It's built with 
<code>@ViewChild('f') formData: NgForm;</code> so that I can fully access to each input value.</p>

<p>I submit the form data like this:
<code>this.postJobService.sendPost(this.formData.value)</code></p>

<p>and the object sent is </p>

<pre><code>Object {groupDat: Object}
    groupData:Object
        category:""tags""
        city:""Boston""
        description:""Awesome article""
        state:""MA""
        title: ""An article title""
        ...
</code></pre>

<p>Now for many reasons, including unit testing, how do you add new values to <code>NgForm</code> and or specifically <code>formData.value.groupData</code> object before I submit the form?</p>
",https://stackoverflow.com/questions/43396660/programmatically-add-values-to-angular-2-ngform-object,"['forms', 'angular']",481,FALSE,0,0
UNIT TEST: How can I use Unit Test for Database?,"<p>If whole of my codes only distribute data to database or get data from database, how can I use Unit Test for that?
While on <a href=""https://codeutopia.net/blog/2015/03/01/unit-testing-tdd-and-bdd/"" rel=""nofollow noreferrer"">https://codeutopia.net/blog/2015/03/01/unit-testing-tdd-and-bdd/</a> says :</p>

<blockquote>
  <p>A Unit Test should be isolated from dependencies – for example, no network access and no database access.</p>
</blockquote>
",https://stackoverflow.com/questions/46930112/unit-test-how-can-i-use-unit-test-for-database,"['c#', 'asp.net', 'visual-studio', 'unit-testing']",90,TRUE,-4,1
DataSet not saving the data,"<p>This is the first time I am using DataSet. Below is my code</p>

<pre><code>var transactionSet = new ModelExecutionContext()
        {
            TransactionSet = new DataSet()
            {
                Tables = { new DataTable()
                {
                    TableName = ""transaction_history""
                }
                }
            }
        };

        transactionSet.TransactionSet.Tables[""transaction_history""].Columns.Add().ColumnName = ""retailer_reference_id"";
        var retailerReferenceIdRow = transactionSet.TransactionSet.Tables[""transaction_history""].NewRow();
        retailerReferenceIdRow[""retailer_reference_id""] = 8;

        transactionSet.TransactionSet.AcceptChanges();
</code></pre>

<p>I am unit testing a method in a class which has the datasets. I am trying to mock those datasets. I thought <code>transactionSet.TransactionSet.AcceptChanges();</code> will save the changes into the <code>DataSet</code>, but in the execution, I am getting <code>context?.TransactionSet?.Tables[""transaction_history""]?.Rows.Count</code> = <strong>0</strong> </p>

<p>Is anything incorrect with my code?</p>
",https://stackoverflow.com/questions/42590715/dataset-not-saving-the-data,['c#'],39,TRUE,0,1
phpunit tutorial is not showing the correct number of assertions,"<p>I'm currently doing this tutorial</p>

<p><a href=""https://jtreminio.com/2013/03/unit-testing-tutorial-part-2-assertions-writing-a-useful-test-and-dataprovider/"" rel=""nofollow noreferrer"">https://jtreminio.com/2013/03/unit-testing-tutorial-part-2-assertions-writing-a-useful-test-and-dataprovider/</a></p>

<p>After I create the phpunit test</p>

<pre><code>&lt;?php

namespace phpUnitTutorial\Test;

class URLTest extends \PHPUnit_Framework_TestCase
{
//
}
</code></pre>

<p>I run it and predictably, I get an error.  However, I should be getting
Tests: 2 and Assertions: 1   instead, I'm getting 1 test and 0 assertions.  </p>
",https://stackoverflow.com/questions/44172639/phpunit-tutorial-is-not-showing-the-correct-number-of-assertions,"['unit-testing', 'testing', 'phpunit', 'backend']",53,FALSE,0,0
Angular Material 2 MdMenu unit test case failing. Error: Cannot read property &#39;unsubscribe&#39; of undefined,"<p>I am using angular-cli to create my component and working with Material2.</p>

<p>In test.component.html</p>

<pre><code>&lt;md-toolbar&gt;
&lt;button md-icon-button [mdMenuTriggerFor]=""anchorMenu"" aria-label=""Open anchor menu""&gt;
  &lt;md-icon&gt;more_vert&lt;/md-icon&gt;
&lt;/button&gt;
&lt;/md-toolbar&gt;

&lt;md-menu #anchorMenu=""mdMenu""&gt; //getting error on this line
&lt;a md-menu-item *ngFor=""let item of items"" href=""http://www.google.com"" [disabled]=""item.disabled""&gt;
  {{ item.text }}
&lt;/a&gt;
&lt;/md-menu&gt;
</code></pre>

<p>While Unit Testing:</p>

<blockquote>
  <p>Error: Error in ./TestCompComponent class TestCompComponent - inline
  template:7:4 caused by: Cannot read property 'unsubscribe' of
  undefined</p>
</blockquote>

<p>Everyhing works fine when I run <strong>ng serve</strong> but getting above error on <strong>ng test</strong></p>

<p>In test.component.spec.ts</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import 'hammerjs';
import { MaterialModule } from '@angular/material';
import { TestComponent } from './test.component';

describe('TestComponent', () =&gt; {
  let component: TestComponent;
  let fixture: ComponentFixture&lt;TestComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [MaterialModule],
      declarations: [TestComponent]
    })
      .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p>Some answers said ""fixture.detectChanges();"" will work but this is already present and not working for me. Some more answers said need to add Observable but I am not using any service. This is simple MdMenu from Material2.</p>

<p>Debugging:</p>

<ol>
<li>When I remove [mdMenuTriggerFor]=""anchorMenu"" and md-menu reference
I am not getting any error in Unit testing.</li>
<li>When I am removing ""ui-test-comp"" tag from
app.component.html I am not getting this error and all test cases
are getting pass.</li>
</ol>

<p>Please find plnkr link for all related file reference. (Please note that this is not working plnkr and just for reference purpose.)</p>

<p><a href=""https://plnkr.co/edit/AFzHWG28ZYgLZTs5aZgF"" rel=""nofollow noreferrer"">https://plnkr.co/edit/AFzHWG28ZYgLZTs5aZgF</a></p>
",https://stackoverflow.com/questions/42665350/angular-material-2-mdmenu-unit-test-case-failing-error-cannot-read-property-u,"['angular', 'karma-jasmine', 'angular-cli', 'angular-material2']",908,FALSE,2,0
Research in Angular 2 Testing,"<p>I have been told to make an investigation of the different options for Angular Testing out there, specifically Angular 2. I would like to confirm with you whether my conclusions are right or not.</p>

<p><strong>Can I write unit testing using Vanilla Javascript?</strong></p>

<p>The answer is yes and also you can write Unit Testing using Jasmine.</p>

<p><strong>Unit testing vs TDD</strong></p>

<p>TDD is the approach of writing the test cases before development and then the developer write the necessary code to make this failing test pass.</p>

<p>You cannot do TDD without using unit testing.</p>

<p>With TDD the code is fully tested in advance. Following TDD approach is easy than write unit tests after development.</p>

<p><strong>BDD</strong></p>

<p>BDD is a set of best practices for writing great tests. BDD can, and should be, used together with TDD and unit testing methods.</p>

<p>That’s why Jasmine and other testing frameworks say  they are BDD frameworks on its documentation.</p>

<p><strong>Which are the mainstream testing frameworks?</strong></p>

<p><strong>Mocha</strong> is one of the most used libraries for testing purposes out there. But It only provides you with the basic structure you need to do testing. When you need more flexibility or functionality such as assertions, spies, mocks… you must add third party libraries: ChaiJS, SinonJS, ShouldJS. Which makes it difficult to start. No much documentation for using them for Angular 2, either.</p>

<p><strong>Jasmine</strong> is also a very popular framework for testing purposes. With Jasmine, you have all the functionality you are going to need out-of-the-box. And have great compatibility with Angular 2.</p>

<p>e2e tests should be written using Protractor (which is wrapper of selenium).</p>

<p>As a rule: All test that can be written down as instructions for a human interacting with your application should be e2e.</p>

<p><strong>In Brief:</strong></p>

<p><strong>Jasmine</strong> - Focus on BDD. Easy for newcomers. Code easy to read. It is a library that covers almost every part of the testing development. You can write unit testing, use it for TDD/BDD. Created by Angular People.</p>

<p><strong>Mocha</strong> - Hard for beginners, easy for TDD/BDD. It does not include any library for assertions, expects. Flexible but difficult.
Mocha is considered the best library for Javascript testing even though being hard to learn and put into practise.</p>

<p><strong>Jest</strong> - Created by Facebook, not as popular as the other ones. This tries to keep things as simple as possible. No much considered for Angular 2 world.</p>

<p><strong>Cucumber</strong> - Focus on BDD</p>

<p><strong>More:</strong></p>

<p>Also, browser environment feature which is not available in either (Mocha, Jasmine). For this you will need to use Protractor (wrapper of Selenium) which is well-documented in Angular 2 testing section or others such as: Nightwatch, Phanton, Casper, etc).</p>

<p>Karma Test Runner is used to run your tests in different browsers and show the results in it. (Good for TDD approach).</p>

<p>Jasmine has a great support from Angular community which is definitely a positive point.</p>

<p>Jasmine also allows you to use different libraries for getting more flexibility in the case of assertions for example.</p>

<p>Selenium is a library that run tests on the browser in order to simulate user behavior.</p>

<p>Protractor (e2e, BDD) wraps selenium and add improved syntax and special hooks for Angular.</p>

<p>There is no much information out there to start using Angular 2 Webpack with MochaJS.</p>
",https://stackoverflow.com/questions/46317864/research-in-angular-2-testing,"['javascript', 'angular', 'unit-testing', 'testing', 'jasmine']",288,FALSE,3,0
Fake Linux System Time Within a Unit Test,"<p>I am unit testing a function that uses the current time. Because of this, I am looking for a way to fake the system time. I understand there are libraries that change the system time, but I am looking for any less invasive, simple alternatives for a small unit test.</p>

<p>Does anything similar to this exist?:</p>

<pre><code>TEST_T(MyUnitTest, example_test){

    startFakeSystemDate(""2017-3-13T18:12:49Z"");

    //perform time based unit test

    endFakeSystemDate();
}
</code></pre>
",https://stackoverflow.com/questions/43399852/fake-linux-system-time-within-a-unit-test,"['c++', 'linux', 'unit-testing', 'datetime']",575,FALSE,1,0
C#: How can I instantiate a List of private inner class?,"<p>everybody. I'm doing unit-testing now, while I have a problem I can not solve it by my own. 
The problem is listed below:</p>

<pre><code>public class A {
    private class B{ }
    private List&lt;B&gt; list = new List&lt;B&gt;;
}
</code></pre>

<p>I want to test whether <code>list[i]</code> is <code>null</code> or not? Now I can use Reflection to get the list, But the question is how can I add a instance of <code>B</code> into the list? 
Thanks for your help!</p>
",https://stackoverflow.com/questions/42709791/c-how-can-i-instantiate-a-list-of-private-inner-class,"['c#', 'unit-testing', 'reflection']",135,TRUE,1,2
mocha run npm test no error details,"<p>Might be a stupid issue:</p>

<p>I'm running a command to do unit-testing, and found that whenever there're some errors, the error message won't be printed which makes debugging really difficult. Here's the command I ran</p>

<p>and here's the package.json:</p>

<pre><code>cp app/models/conversations/default_group_avatar.png built/models/conversations/default_group_avatar.png &amp;&amp; NODE_ENV=test mocha --timeout 20000 --compilers ts:ts-node/register,tsx:ts-no    de/register app/**/index-test.ts --reporter nyan
</code></pre>

<p>tsconfig:</p>

<pre><code>  1 {
  2   ""compilerOptions"": {
  3     ""outDir"": ""./built"",
  4     ""allowJs"": true,
  5     ""target"": ""es5""
  6   },
  7   ""include"": [
  8     ""./app/**/*.ts""
  9   ]
 10 }
</code></pre>

<p>when I run it, it shows:</p>

<pre><code>➜  GhostFaceRestful git:(exie/robot) ✗ npm test

&gt; ghostface@1.0.0 test /Users/exie/workspace/GhostFaceRestful
&gt; cp app/models/conversations/default_group_avatar.png built/models/conversations/default_group_avatar.png &amp;&amp; NODE_ENV=test mocha --timeout 20000 --compilers ts:ts-node/register,tsx:ts-node/register app/**/index-test.ts --reporter nyan

npm ERR! Test failed.  See above for more details.
</code></pre>

<p>without showing any details at all... How shall I do this correctly?</p>
",https://stackoverflow.com/questions/42570216/mocha-run-npm-test-no-error-details,"['javascript', 'node.js', 'unit-testing', 'npm']",652,FALSE,1,1
Integration Testing Approach for Code C/C++,"<p>I have seen this <a href=""https://stackoverflow.com/questions/1439172/testing-code-in-c-c"">post</a> about Unit Testing for C/C++. I have heard that gtest can be used for Integration Testing. What is the best approach to do Integration Tests? I am afraid that this could replicate Unit/System tests so I am not sure what test technique should I use for C embedded systems.</p>
",https://stackoverflow.com/questions/45989699/integration-testing-approach-for-code-c-c,"['c', 'integration-testing', 'googletest']",4137,FALSE,1,0
"Angular 4 Karma Unit Testing, not detecting the tests","<p>I am trying to introduce unit testing to my Angular 4 project. I am using Karma for it. I have done the configuration. It shows a connected screen. But it shows not tests! I have one test under <code>src/app/</code> directory.</p>

<p>This error appears in console.</p>

<pre><code>{
   ""originalErr"": {
     ""__zone_symbol__currentTask"": {
       ""type"": ""microTask"",
       ""state"": ""notScheduled"",
       ""source"": ""Promise.then"",
       ""zone"": ""&lt;root&gt;"",
       ""cancelFn"": null,
       ""runCount"": 0
     }
   },
   ""__zone_symbol__currentTask"": {
     ""type"": ""microTask"",
     ""state"": ""notScheduled"",
     ""source"": ""Promise.then"",
     ""zone"": ""&lt;root&gt;"",
     ""cancelFn"": null,
     ""runCount"": 0
   }
}
</code></pre>

<p>1st.spec.ts</p>

<pre><code>describe('1st tests', () =&gt; {
  it('true is true', () =&gt; expect(true).toBe(true));
});
</code></pre>

<p>karma.config.js</p>

<pre><code>module.exports = function(config) {

  var appBase    = 'src/';       // transpiled app JS and map files
  var appAssets  = '/base/app/'; // component assets fetched by Angular's compiler

  // Testing helpers (optional) are conventionally in a folder called `testing`
  var testingBase    = 'src/testing/'; // transpiled test JS and map files
  var testingSrcBase = 'src/testing/'; // test source TS files

  config.set({
    basePath: '',
    frameworks: ['jasmine'],

    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter')
    ],

    client: {
      builtPaths: [appBase, testingBase], // add more spec base paths as needed
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },

    customLaunchers: {
      // From the CLI. Not used here but interesting
      // chrome setup for travis CI using chromium
      Chrome_travis_ci: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    },

    files: [
      // System.js for module loading
      'node_modules/systemjs/dist/system.src.js',

      // Polyfills
      'node_modules/core-js/client/shim.js',

      // zone.js
      'node_modules/zone.js/dist/zone.js',
      'node_modules/zone.js/dist/long-stack-trace-zone.js',
      'node_modules/zone.js/dist/proxy.js',
      'node_modules/zone.js/dist/sync-test.js',
      'node_modules/zone.js/dist/jasmine-patch.js',
      'node_modules/zone.js/dist/async-test.js',
      'node_modules/zone.js/dist/fake-async-test.js',

      // RxJs
      { pattern: 'node_modules/rxjs/**/*.js', included: false, watched: false },
      { pattern: 'node_modules/rxjs/**/*.js.map', included: false, watched: false },

      // Paths loaded via module imports:
      // Angular itself
      { pattern: 'node_modules/@angular/**/*.js', included: false, watched: false },
      { pattern: 'node_modules/@angular/**/*.js.map', included: false, watched: false },

      { pattern: appBase + '/systemjs.config.js', included: false, watched: false },
      { pattern: appBase + '/systemjs.config.extras.js', included: false, watched: false },
      'karma-test-shim.js', // optionally extend SystemJS mapping e.g., with barrels

      // transpiled application &amp; spec code paths loaded via module imports
      { pattern: appBase + '**/*.js', included: false, watched: true },
      { pattern: testingBase + '**/*.js', included: false, watched: true },


      // Asset (HTML &amp; CSS) paths loaded via Angular's component compiler
      // (these paths need to be rewritten, see proxies section)
      { pattern: appBase + '**/*.html', included: false, watched: true },
      { pattern: appBase + '**/*.css', included: false, watched: true },

      // Paths for debugging with source maps in dev tools
      { pattern: appBase + '**/*.ts', included: false, watched: false },
      { pattern: appBase + '**/*.js.map', included: false, watched: false },
      { pattern: testingSrcBase + '**/*.ts', included: false, watched: false },
      { pattern: testingBase + '**/*.js.map', included: false, watched: false}
    ],

    // Proxied base paths for loading assets
    proxies: {
      // required for modules fetched by SystemJS
      '/base/src/node_modules/': '/base/node_modules/'
    },

    exclude: [],
    preprocessors: {},
    reporters: ['progress', 'kjhtml'],

    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  })
}
</code></pre>

<p>Karma Connection Screen:
<a href=""https://i.stack.imgur.com/iZQC5.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/iZQC5.png"" alt=""enter image description here""></a>
Any lead to help, will be helpful.</p>
",https://stackoverflow.com/questions/44081447/angular-4-karma-unit-testing-not-detecting-the-tests,"['angularjs', 'unit-testing', 'karma-jasmine']",932,FALSE,1,0
How to unit test a component that depends ActivatedRoute unsubscribe?,"<p>I have a similar question as <a href=""https://stackoverflow.com/questions/38356084/how-to-unit-test-a-component-that-depends-on-parameters-from-activatedroute"">How to unit test a component that depends on parameters from ActivatedRoute?</a></p>

<p>Basically I'm unit testing a component which has <code>ActivatedRoute</code> dependency. I also have <code>unsubscribe</code> method in my component:</p>

<pre><code>ngOnDestroy() {
this.subscription.unsubscribe();
</code></pre>

<p>}</p>

<p>I'm getting the following error:</p>

<pre><code>TypeError: Cannot read property 'unsubscribe' of undefined
</code></pre>

<p>I have tried mocking ActiveRoot as below, but subscription is <code>void</code> so I'm not sure how to test this!</p>

<pre><code>let mockActivatedRoute = {
data: {
  subscribe: (fn: (value: Data) =&gt; void) =&gt; fn({
    yourData: 'yolo'
  })
},
params: {
  next: Observable.of([0]),
  subscribe: () =&gt; { Observable.of([]); }
}
</code></pre>

<p>};</p>
",https://stackoverflow.com/questions/42009081/how-to-unit-test-a-component-that-depends-activatedroute-unsubscribe,"['unit-testing', 'angular', 'components', 'observable', 'unsubscribe']",366,FALSE,1,0
Error with EXPECT_EQ for create table,"<p>During unit Testing of Create Table API, I'm getting the below mentioned error :</p>

<p><strong>pankaj:~/Downloads/googletest-release-1.8.0/src$ ./Test.out</strong> </p>

<pre><code>[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from AdditionTest
[ RUN      ] AdditionTest.twoValues
in sqliteDB constructor
in sqliteDB destructor

Pure virtual destructor is called from DBManager()
unknown file: Failure
C++ exception with description ""basic_string::erase"" thrown in the test body.
[  FAILED  ] AdditionTest.twoValues (0 ms)
[----------] 1 test from AdditionTest (0 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (2 ms total)
[  PASSED  ] 0 tests.
[  FAILED  ] 1 test, listed below:
[  FAILED  ] AdditionTest.twoValues

 1 FAILED TEST

result: 1
</code></pre>

<p>Below mentioned is code to test <strong>createTable</strong> API ::</p>

<pre><code>TEST_F(AdditionTest,twoValues){
    sqliteDB obj_sql;  
    std::vector&lt;std::string&gt; colNames;
    colNames.push_back(""id"");
    colNames.push_back(""name"");    
    pair&lt;std::string, int&gt; p1, p2;
    map&lt;std::string, pair&lt;string, int&gt; &gt; m1;
    p1 = make_pair(""varchar"", 10);
    p2 = make_pair(""varchar"", 10);
    m1[""id""] = p1;
    m1[""name""] = p2;
    tableData[""table1""] = m1;
    EXPECT_EQ(9,obj_sql.createTable(colNames,tableData));
    //EXPECT_EQ(6,addition.twoValues(2,3));
}
</code></pre>

<p>Testing below mentioned API :::::</p>

<pre><code>int sqliteDB::createTable(std::vector&lt;std::string&gt; tableName, tableStructure &amp;tableContents)
{
    for(unsigned int i=0; i&lt;tableName.size(); i++)
    {
        string s4;
        string query;

        for(auto it : tableContents[tableName[i]])
        {
            s4.append(it.first);
            s4.append("" "");
            s4.append(it.second.first);
            if(it.second.first == ""varchar"")
            {
                s4.append(""("");
                s4.append(to_string(it.second.second));
                s4.append("")"");
            }
            s4.append("","");
        }

        s4.pop_back();
        query.append(""CREATE TABLE "");
        query.append(tableName[i]);
        query.append("" ("");
        query.append(s4);
        query.append("")"");
        cout&lt;&lt;""Create Query: ""&lt;&lt;query&lt;&lt;endl;

        executeQuery(m_db, query);
    }
    return 0;   
}
</code></pre>

<p>What changes should I do in EXPECT_EQ(9,obj_sql.createTable(colNames,tableData)) to pass this test, or should I do changes somewhere else in code.</p>
",https://stackoverflow.com/questions/44897829/error-with-expect-eq-for-create-table,"['c++', 'sqlite', 'unit-testing', 'googletest']",149,FALSE,1,0
How to unit test the catch body of my Observable,"<p>In my <code>Angular</code> application, I'm using <code>Observables</code> in the following way:</p>

<pre><code>getItem(id): Observable&lt;Object&gt; {
  return this.myApi.myMethod(...).catch(e =&gt; {
    /* CATCH BODY */
    return Observable.throw(e);
  });
}
</code></pre>

<p>and I unit test it:</p>

<pre><code>it('getItem(...) should correctly do its job',
  inject([MyService], (service: MyService) =&gt; {

    const spy = spyOn(myApi, 'myMethod').and.returnValue(mockObservable);

    const mockData = 'mock'; // can be anything
    const mockObservable = Observable.of(mockData);


    service.getItems().subscribe((data) =&gt; {
      expect(data).toEqual(mockData);
    });

    expect(spy).toHaveBeenCalledWith(...);
  })
);
</code></pre>

<p>However, I don't know how to unit test the <code>CATCH BODY</code>, how can I mock the <code>observable</code> to throw an error?</p>

<p>I know similar questions have been asked already, but my case is slightly different and I couldn't succeed in unit testing the catch part.</p>
",https://stackoverflow.com/questions/47512174/how-to-unit-test-the-catch-body-of-my-observable,"['javascript', 'unit-testing', 'jasmine', 'rxjs', 'angular-observable']",478,TRUE,1,1
First time JUnit user: Why eclipse always shows error (Red indicator),"<p>This is my first time doing/learning unit testing using JUnit eclipse.</p>

<ul>
<li>I've added <code>JUnit 4.12.jar</code> via <em>right clicking</em> on the project</li>
</ul>

<p>Now : I've 2 classes:</p>

<pre><code>public class Calculate {
    public int sum(int var1, int var2) {
        System.out.println(""Adding values: "" + var1 + "" + "" + var2);
        return var1 + var2;
    }
}
</code></pre>

<hr>

<pre><code>import org.junit.*;
import static org.junit.Assert.*;
import org.junit.Test;

public class CalculateTest {
    Calculate calculation = new Calculate();
    int sum = calculation.sum(2, 5);
    int testSum = 7;

    @Test
    public void testSum() {
        System.out.println(""@Test sum(): "" + sum + "" = "" + testSum);
        assertEquals(sum, testSum);
    }
}
</code></pre>

<p>Finally, every time (Every examples) I right click at, then</p>

<p><strong>CalculateTest.java->Run as->JUnit Test</strong></p>

<p>It shows me this instead:</p>

<p><a href=""https://i.stack.imgur.com/ZA0Te.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ZA0Te.png"" alt=""enter image description here""></a></p>

<p>While it should be something like this :</p>

<p><a href=""https://i.stack.imgur.com/WrEuJ.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/WrEuJ.png"" alt=""enter image description here""></a></p>

<p>How to do it in the right way?</p>
",https://stackoverflow.com/questions/42605979/first-time-junit-user-why-eclipse-always-shows-error-red-indicator,"['java', 'eclipse', 'junit']",488,TRUE,0,2
How to test for a propety of a class after promise resolution with mocha and chai,"<p>I am trying out a bit of unit testing with Mocha + Chai as promised</p>

<pre><code>'use strict';
var chai = require('chai').use(require('chai-as-promised'))
var should = chai.should();


describe('Testing how promises work', () =&gt; {
    it(""should work right"", function(){
        class SomeClass {
            constructor() {
                this.x = 0;
            }
            getSomething(inputVal) {
                let self = this;
                return new Promise((resolve, reject) =&gt; {
                    setTimeout(function(){
                        if(inputVal){
                            self.x = 1;
                            resolve();
                        }
                        else{
                            self.x = -1;
                            reject();
                        }

                    }, 10);
                });
            }
        }

        var z = new SomeClass();

        return z.getSomething(true).should.eventually.be.fulfilled
    });
});
</code></pre>

<p>Test does pass. But I would like to check if the value of <code>z.x equals 1</code> after the promise has been resolved. How do I do that?</p>

<p>this is just a prototype. I would like to test more that one property in my real case</p>
",https://stackoverflow.com/questions/47767279/how-to-test-for-a-propety-of-a-class-after-promise-resolution-with-mocha-and-cha,"['mocha.js', 'chai', 'chai-as-promised']",126,TRUE,0,1
Assertion not executing in Python Mock,"<p>I'm trying to implement some unit testing on some code I am building but I'm seeing this weird behavior where even though I set the return value of a function call to be <strong>False</strong>, the related code does not execute and thus the assertion <code>instance.fail_json.assert_called_with(msg='Not enough parameters specified.')</code>fails.</p>

<p><a href=""https://i.stack.imgur.com/qwbFv.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/qwbFv.png"" alt=""Console Output""></a></p>

<p>Is there something else I need to be setting?</p>

<p>project.py:</p>

<pre><code>def main():
   # define the available arguments/parameters that a user can pass
   # to the module
   module_args = dict(
      name=dict(type='str', required=True),
      ticktype=dict(type='str'),
      path=dict(type='str'),
      dbrp=dict(type='str'),
      state=dict(type='str', required=True, choices=[""present"", ""absent""]),
      enable=dict(type='str', default=""no"", choices=[""yes"",""no"",""da"",""net""])
   )

   required_if=[
      [ ""state"", ""present"", [""name"", ""type"", ""path"", ""dbrp"", ""enabled""] ],
      [ ""state"", ""absent"", [""name""]]
   ]

   # seed the result dict in the object
   # we primarily care about changed and state
   # change is if this module effectively modified the target
   # state will include any data that you want your module to pass back
   # for consumption, for exampole, in a subsequent task
   result = dict(
      changed=False,
      original_message='',
      message=''
   )

   # the AnsibleModule object will be our abstraction working with Ansible
   # this includes instantiation, a couple of common attr would be the
   # args/params passed to the execution, as well as if the module
   # supports check mode
   module = AnsibleModule(
      argument_spec=module_args,
      supports_check_mode=False
   )

   # if the user is working with this module in only check mode we do not
   # want to make any changes to the environment, just return the current
   # state with no modifications
   if module.check_mode:
      return result

   return_val = run_module(module)
   return_val = True
   if return_val is True:
      module.exit_json(changed=True, msg=""Project updated."")
   else:
      module.fail_json(changed=True, msg=""Not enough parameters found."")
</code></pre>

<p>test_project.py:</p>

<pre><code>@patch('library.project.run_module')
@patch('library.project.AnsibleModule')
def test_main_exit_functionality_failure(mock_module, mock_run_module):
   """"""
   project - test_main_exit_functionality - failure
   """"""
   instance = mock_module.return_value

   # What happens when the run_module returns false
   # that is run_module fails
   mock_run_module.return_value = False

   project.main()

   # AnsibleModule.exit_json should not activated
   assert_equals(instance.fail_json.call_count, 0)

   #AnsibleModule.fail_json should be called
   instance.fail_json.assert_called_with(msg='Not enough parameters 
   specified.')
</code></pre>
",https://stackoverflow.com/questions/46260390/assertion-not-executing-in-python-mock,"['python', 'python-2.7', 'unit-testing', 'python-mock']",172,FALSE,-1,1
Code Coverage not listed in VS2008 - c#,"<p>I'm trying to do unit testing in visual studio 2008 (Proffesional Edition). I've create a class library solution for this topic. Now, I want to use the feature of ""Code coverage"" but this is not listed in my local test config.</p>

<p>local config:</p>

<p><a href=""https://i.stack.imgur.com/PqxAc.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/PqxAc.png"" alt=""enter image description here""></a></p>

<p><a href=""https://i.stack.imgur.com/1LyxU.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/1LyxU.png"" alt=""enter image description here""></a></p>

<p>Does anyone knows how to listed and enable?
I'd appreciate any comments/suggestions.</p>

<p>Thank you.</p>
",https://stackoverflow.com/questions/47290624/code-coverage-not-listed-in-vs2008-c,"['c#', 'visual-studio-2008', 'code-coverage']",27,TRUE,0,1
How can I test if code has debuggers?,"<p>I am working with a team and we are constantly putting <code>console.log</code> and <code>debugger</code> or <code>binding.pry</code> (Ruby) into our code. What is the appropriate strategy for going about to write a unit test for this? We currently do not have unit testing (I know, it's ridiculous) but this is something we need to handle, because we are accidentally pushing <code>console.log</code> and <code>binding.pry</code> into production. </p>
",https://stackoverflow.com/questions/44638835/how-can-i-test-if-code-has-debuggers,"['javascript', 'unit-testing', 'rspec']",20,FALSE,0,1
DatabaseMigrations Not Found In Laravel 5.0,"<p>I was watching a video of Unit Testing of <strong>Laravel 5.4</strong>, and the tutor uses</p>

<pre><code>use Illuminate\Foundation\Testing\DatabaseMigrations;
</code></pre>

<p>and </p>

<pre><code>use DatabaseMigrations;
</code></pre>

<p>inside the testing file</p>

<p>In <strong>Laravel 5.0</strong>, there are no such files and I cannot use DatabaseMigrations in my testing file.</p>

<p>I get error like </p>

<blockquote>
  <p>Fatal error: Trait 'Illuminate\Foundation\Testing\DatabaseMigrations'
  not found</p>
</blockquote>

<p>Are there any replacements in <strong>Laravel 5.0</strong></p>
",https://stackoverflow.com/questions/45936881/databasemigrations-not-found-in-laravel-5-0,"['laravel-5', 'laravel-5.4']",294,TRUE,0,1
Issue when testing Spring framework,"<p>I need to add unit testing to my Spring project. I'm currently using spring framework within JAX-RS, but I'm unable to test it.</p>

<p>My pom.xml is as follows:</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;project xmlns=""http://maven.apache.org/POM/4.0.0""
     xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
     xsi:schemaLocation=""http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd""&gt;
&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;

&lt;groupId&gt;com.zcd2&lt;/groupId&gt;
&lt;artifactId&gt;helloworldapi&lt;/artifactId&gt;
&lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;

&lt;dependencies&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework&lt;/groupId&gt;
        &lt;artifactId&gt;spring-web&lt;/artifactId&gt;
        &lt;version&gt;5.0.1.RELEASE&lt;/version&gt;
        &lt;scope&gt;compile&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.glassfish.jersey.test-framework.providers&lt;/groupId&gt;
        &lt;artifactId&gt;jersey-test-framework-provider-inmemory&lt;/artifactId&gt;
        &lt;version&gt;2.26&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.glassfish.jersey.inject&lt;/groupId&gt;
        &lt;artifactId&gt;jersey-hk2&lt;/artifactId&gt;
        &lt;version&gt;2.26&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.glassfish.jersey.containers&lt;/groupId&gt;
        &lt;artifactId&gt;jersey-container-servlet&lt;/artifactId&gt;
        &lt;version&gt;2.26&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
&lt;/dependencies&gt;
</code></pre>

<p></p>

<p>My java file:</p>

<pre><code>@Path(""/external-spring-hello"")
public class ExternalSpringRequestResource {

@Autowired
private GreetingService greetingService;

@GET
@Produces(MediaType.TEXT_PLAIN)
public String getHello() {
    return greetingService.getMessage();
}
</code></pre>

<p>}</p>

<p>And my test file is:</p>

<pre><code>public class ExternalSpringRequestResourceTest extends JerseyTest {

@Override
protected Application configure() {
    return new ResourceConfig(ExternalSpringRequestResource.class);
}

@Override
protected DeploymentContext configureDeployment() {
    ResourceConfig config = new ResourceConfig(ExternalSpringRequestResource.class);
    config.packages(""com.trial"");
    return ServletDeploymentContext
            .forServlet(new ServletContainer(config))
            .addListener(ContextLoaderListener.class)
            .contextParam(""contextConfigLocation"", ""classpath:applicationContext.xml"")
            .build();

}

@Test
public void first() throws Exception {
    final String response = target(""/external-spring-hello"").request().get(String.class);

    Assert.assertEquals(response, ""Hello"");
}
}
</code></pre>

<p>However, I'm getting that error:</p>

<pre><code>java.lang.NullPointerException
at org.glassfish.jersey.server.ApplicationConfigurator.createApplication(ApplicationConfigurator.java:131)
at org.glassfish.jersey.server.ApplicationConfigurator.init(ApplicationConfigurator.java:104)
at org.glassfish.jersey.server.ApplicationHandler.lambda$initialize$0(ApplicationHandler.java:313)
at java.util.Arrays$ArrayList.forEach(Arrays.java:3880)
at org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:313)
at org.glassfish.jersey.server.ApplicationHandler.&lt;init&gt;(ApplicationHandler.java:282)
at org.glassfish.jersey.server.ApplicationHandler.&lt;init&gt;(ApplicationHandler.java:257)
at org.glassfish.jersey.test.inmemory.InMemoryTestContainerFactory$InMemoryTestContainer.&lt;init&gt;(InMemoryTestContainerFactory.java:78)
at org.glassfish.jersey.test.inmemory.InMemoryTestContainerFactory$InMemoryTestContainer.&lt;init&gt;(InMemoryTestContainerFactory.java:64)
at org.glassfish.jersey.test.inmemory.InMemoryTestContainerFactory.create(InMemoryTestContainerFactory.java:112)
at org.glassfish.jersey.test.JerseyTest.createTestContainer(JerseyTest.java:278)
at org.glassfish.jersey.test.JerseyTest.setUp(JerseyTest.java:608)
</code></pre>

<p>It looks like an issue with jersey server library. How can I solve that?</p>

<p>Thanks a lot</p>
",https://stackoverflow.com/questions/47258553/issue-when-testing-spring-framework,"['spring', 'spring-mvc', 'jax-rs', 'spring-test', 'spring-web']",135,FALSE,0,0
Static method is thread-safe if new instances are returned allways it gets called?,"<p>I have the following classes:</p>

<pre><code>public class SesionPasoProxy
{
    private static EntitySerializer _serializer = EntitySerializer.Create();

    public static string Obtener(Guid idSesion, int orden)
    {
        SesionPaso item = new SesionPaso();
        item.Orden = orden;
        item.IdSesion = idSesion;
        return _serializer.ToXml(item);

    }        
}


 public class EntitySerializer
 {
      private EntitySerializer(){}  
      public static EntitySerializer Create()
      {
         return EntitySerializer.Create(""Test"");
      }

       public static EntitySerializer Create(string serializationContextName)
       {
            EntitySerializer  instance = new EntitySerializer();
            instance.Name = serializationContextName;
            return instance;
       }
       public ToXml(SesionPaso x){ return x.toString();}
}
</code></pre>

<p>Is that code thread-safe? SessionPasoProxy is used inside a ASP.NET WebForms aspx page. So it can get called concurrently.
As you see EntitySerializer is static but is returns new instances (not Singleton)
What do you think?
My unit testing is showing is thread.safe, but i am not sure at all.</p>

<p>Many thanks</p>
",https://stackoverflow.com/questions/45977236/static-method-is-thread-safe-if-new-instances-are-returned-allways-it-gets-calle,"['asp.net', 'multithreading', 'thread-safety', 'threadpool', 'application-pool']",142,TRUE,0,1
What is a real-world way of allowing a mocha test to stub/mock fs so I can test a function without it accessing the disk?,"<p>So my code looks like this:</p>

<pre><code>import FsAsyncFactory from '../fs/FsAsyncFactory'
import ObjectHelper from '../utils/ObjectHelper'
import Config from './Config'

export class ConfigHelper {

    // this is the function under test
    public static async primeCacheObj(): Promise&lt;void&gt; {

        const configFileObj: any = await ConfigHelper.getConfigFileObj()

    }

    private static configCacheObj: Config = null

    private static async getConfigFileObj(): Promise&lt;any&gt; {
        const fsAsync: any = FsAsyncFactory.getFsAsync()
        const fileContents: string = await fsAsync.readFileAsync('./config/hubnodeConfig.json')

        return JSON.parse(fileContents)
    }

}

export default ConfigHelper
</code></pre>

<p>What's the best way to allow my unit testing code to stop it from actually hitting the disk?</p>

<p>Should I be using something like InversifyJS to allow dependency injection? I'd have an init script that would setup the ""defaults"" for when the app is running normally then ""override"" those defaults in the tests?</p>
",https://stackoverflow.com/questions/47821674/what-is-a-real-world-way-of-allowing-a-mocha-test-to-stub-mock-fs-so-i-can-test,"['node.js', 'unit-testing', 'dependency-injection', 'mocha.js', 'inversifyjs']",1320,TRUE,0,1
Karma/Jasmine test failing on undefined scope,"<p>I'm trying to create first unit testing for one of my controllers.</p>

<p>My Karma/Jasmine simple test for a controller looks like</p>

<pre><code>describe('RegistrationController', function() {

    beforeEach(module('myApp'));

    var $controller, $rootScope;

    beforeEach(inject(function(_$controller_, _$rootScope_){
        // The injector unwraps the underscores (_) from around the parameter names when matching
        $controller = _$controller_;
        $rootScope = _$rootScope_;
    }));

    describe('Registration $scope.submit', function() {
        it('submits registration and sets step to 1', function() {
            var $scope = $rootScope.$new();

            var controller = $controller('RegistrationController', { $scope: $scope });
            $scope.submit();
            expect($scope.step).toEqual(1);
        });
    }); 

});
</code></pre>

<p>which tests that part of the controller</p>

<pre><code>$scope.submit = function () {

    $scope.step = 1; //wizard started
    var userName = $scope.user.name;
    var userNick = $scope.user.nick;        
    $location.path('localization');
}
</code></pre>

<p>but when I run that unit test it fails on <code>user.name</code> and <code>user.nick</code> with an error</p>

<p><code>TypeError: Cannot read property 'name' of undefined</code></p>

<p>or</p>

<p><code>TypeError: Cannot read property 'nick' of undefined</code></p>

<p>when both values are captured by the form and works fine on the controller side.</p>
",https://stackoverflow.com/questions/47186597/karma-jasmine-test-failing-on-undefined-scope,"['javascript', 'angularjs', 'unit-testing', 'karma-jasmine']",198,FALSE,0,0
Testing Values in a Dictionary with Jasmine,"<p>I am unit testing my email checking function. I tried writing a dictionary of test string, description, and expected results and executing tests with for loops but it did not work. 
Now, I am making changes to my spec file one by one to see where it is getting wrong.</p>

<pre><code>describe(""Email"", function() {
  var email;

  beforeEach(function() {
    email = undefined;
    console.log('new test');
  });

 it(""should reject undefined"", function() {
    console.log('test 0');
    email = undefined;
    console.log(email);
    expect(checkEmail(email)).toEqual({'result':false});
  });

 it(""should reject numbers"", function() {
    console.log('test 1');
    email = 123456;
    console.log(email);
    expect(checkEmail(email)).toEqual({'result':false});
  });
});
</code></pre>

<p>This works.</p>

<pre><code>describe(""Email"", function() {
  var email;
  **var emails = [undefined, 123456];**

  beforeEach(function() {
    email = undefined;
    console.log('new test');
  });

 it(""should reject undefined"", function() {
    console.log('test 1');
    **email = emails[0];**
    console.log(email);
    expect(checkEmail(email)).toEqual({'result':false});
  });

 it(""should reject numbers"", function() {
    console.log('test 2');
    **email = emails[1];**
    console.log(email);
    expect(checkEmail(email)).toEqual({'result':false});
  });
});
</code></pre>

<p>This works.</p>

<pre><code>describe(""Email"", function() {
  var email;
  **var tests = {{'email':undefined}, {'email':123456}};**

  beforeEach(function() {
    email = undefined;
    console.log('new test');
  });

 it(""should reject undefined"", function() {
    console.log('test 1');
    **email = tests[0].email;**
    console.log(email);
    expect(checkEmail(email)).toEqual({'result':false});
  });

 it(""should reject numbers"", function() {
    console.log('test 2');
    **email = tests[1].email;**
    console.log(email);
    expect(checkEmail(email)).toEqual({'result':false});
  });
});
</code></pre>

<p>This does not work. Why?</p>
",https://stackoverflow.com/questions/46919367/testing-values-in-a-dictionary-with-jasmine,"['javascript', 'unit-testing', 'dictionary', 'jasmine', 'automated-tests']",617,TRUE,0,1
Can&#39;t run service in Angular2 test (code copy pasted from the docs),"<p>I have the following error <strong>(unit testing Angular2)</strong>:</p>

<blockquote>
  <p>Cannot configure the test module when the test module has already been
  instantiated. Make sure you are not using <code>inject</code> before
  <code>TestBed.configureTestingModule</code></p>
</blockquote>

<p>Here is my code (it's basically a copy paste from the angular docs) which throws the above error:</p>

<pre><code>import { TestBed, async } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { AppModule } from './app.module';
import { AppComponent } from './app.component'
import { MyServiceService } from './my-service.service'

beforeEach(() =&gt; {
  // stub UserService for test purposes
  let userServiceStub = {
    isLoggedIn: true,
    user: { name: 'Test User'}
  };

  TestBed.configureTestingModule({

     declarations: [ AppComponent],
     providers:    [ {provide: MyServiceService, useValue: userServiceStub } ]
  });

  let fixture = TestBed.createComponent(AppComponent);
  let comp    = fixture.componentInstance;
  // UserService from the root injector
  let userService = TestBed.get(MyServiceService);
  //  get the ""welcome"" element by CSS selector (e.g., by class name)
  let de = fixture.debugElement.query(By.css('.nesto'));
  let el = de.nativeElement;

  it('should welcome ""Bubba""', () =&gt; {
    userService.user.name = 'something'; // welcome message hasn't been shown yet
    fixture.detectChanges();
    expect(el.textContent).toContain('some');
  });
});
</code></pre>

<p>I want to run a service but it seems that I just can't do that.</p>
",https://stackoverflow.com/questions/46365262/cant-run-service-in-angular2-test-code-copy-pasted-from-the-docs,"['javascript', 'angular']",1053,TRUE,3,2
Mockito not mocking simple class,"<p>I use moсkito in my application for unit testing
Here is the class which mockito not mocking : </p>

<pre><code>@Parcel(implementations = {TrainingRealmProxy.class},
        value = Parcel.Serialization.BEAN,
        analyze = Training.class)

public class Training extends RealmObject {

@PrimaryKey
private int id;

private Date trainingDate;
private int trainingDurationSeconds;

private boolean finished;

private RealmList&lt;Exercise&gt; exerciseList;

public Training(Date trainingDate, int trainingDurationSeconds) {
    this.trainingDurationSeconds = trainingDurationSeconds;
    this.trainingDate = trainingDate;
    finished = false;
}

public Training(Date trainingDate, RealmList&lt;Exercise&gt; exerciseList) {
    this.trainingDate = trainingDate;
    this.exerciseList = exerciseList;
    finished = false;
}


public Training() {
    finished = false;
}

@ParcelProperty(""exerciseList"")
@ParcelPropertyConverter(TrainingListParcelConverter.class)
public void setExerciseList(List&lt;Exercise&gt; exerciseList) {
    this.exerciseList = convertListToRealmList(exerciseList);
}

....
</code></pre>

<p>Code where im trying to mock this class :</p>

<pre><code>Training training = mock(Training.class);
</code></pre>

<p>And error that is thrown after trying:</p>

<pre><code>org.mockito.exceptions.base.MockitoException: 
Mockito cannot mock this class: class com.gangstagym.model.models.Training.
Mockito can only mock non-private &amp; non-final classes.

Java               : 1.8

JVM vendor name    : JetBrains s.r.o

JVM vendor version : 25.112-b06
</code></pre>

<p>JVM name           : OpenJDK 64-Bit Server </p>

<p>JVM version        : 1.8.0_112-release-b06</p>

<p>I did not find similar questions and I have no idea why this error is thrown out.</p>
",https://stackoverflow.com/questions/47458400/mockito-not-mocking-simple-class,"['java', 'android', 'unit-testing', 'testing', 'mocking']",270,FALSE,3,0
Ways to mock SignalR Clients.Group in unit test,"<p>I'm writing mock test cases for SignalR application. I just started with the help of <a href=""https://learn.microsoft.com/en-us/aspnet/signalr/overview/testing-and-debugging/unit-testing-signalr-applications"" rel=""nofollow noreferrer"">Unit Testing SignalR Applications</a>, but my requirement is little bit different that example shown there.
Following is the code I have done after googling.</p>

<h1>SignalRHub</h1>

<pre><code>public class HubServer : Hub
{
    [HubMethodName(""SendNofication"")]
    public void GetNofication(string message)
    {
        try
        {
            Clients.Group(""Manager"").BroadCast(message);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }        
}
</code></pre>

<h1>Unit Test</h1>

<pre><code>public interface IClientContract { }

[TestMethod]
public void GetNoficationTest()
{
    var hub = new HubServer();
    var mockClients = new Mock&lt;IHubCallerConnectionContext&lt;dynamic&gt;&gt;();
    hub.Clients = mockClients.Object;
    var all = new Mock&lt;IClientContract&gt;();
    string message = ""Message to send"";

    mockClients.Setup(m =&gt; m.Group(""Manager"")).Returns(message);
    mockClients.Setup(m =&gt; m.All).Returns(all.Object);

    hub.GetNofication(""Mock call to SingalR hub"");
    all.VerifyAll();
}
</code></pre>

<p>I'm beginner in Unit Test application, just want to confirm if this is right way to mock SignalR Groups.</p>
",https://stackoverflow.com/questions/44182665/ways-to-mock-signalr-clients-group-in-unit-test,"['c#', 'unit-testing', 'signalr', 'moq']",6097,TRUE,3,1
C - Build/Compile/Deploy success but on other machine its failing,"<p>I have C code for reading ID card reader, it compiled/build/executes fine in my development PC (Windows 10), where i have my Visual studio 2015.</p>

<p>But when i am running the <code>eid.exe</code> to a brand new (Windows 10) machine for unit testing, there its keep showing following error (also installed <a href=""https://www.microsoft.com/en-us/download/details.aspx?id=48145"" rel=""nofollow noreferrer"">https://www.microsoft.com/en-us/download/details.aspx?id=48145</a> ):</p>

<p><a href=""https://i.stack.imgur.com/wqQ4p.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/wqQ4p.png"" alt=""enter image description here""></a>
<a href=""https://i.stack.imgur.com/t8rb6.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/t8rb6.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/42356066/c-build-compile-deploy-success-but-on-other-machine-its-failing,"['c', 'windows', 'visual-studio', 'eid']",47,TRUE,0,1
InitialContext.lookup(&quot;path&quot;) throws javax.naming.NamingException,"<p>I am new to java and learning how to implement stateful ejb, I couldn't do that- (I wanted to maintain a list by adding and removing element in a arrayList) and unit testing is working fine, initializing the object throws the <code>javax.naming.NamingException</code> </p>

<p>Is there anything that i am missing.</p>

<pre><code> &lt;%!
     private static ListElementRemoteForStateful itemIds;
     public void jspInit()
     {
          try
          {
            InitialContext ic = new InitialContext();
            // next line of code always throw
            // here EjbPrototype is the name of the project
            // StatefulEjb is the class name which resides in package ejb
            // I tested with java:global/EjbPrototype/StatefulEjb
            // I tested with java:global/EjbPrototype/ejb.StatefulEjb 
            // I tested with java:app/EjbPrototype/StatefulEjb 
            // I tested with java:module/EjbPrototype/StatefulEjb
            // I tested with java:comp/EjbPrototype/StatefulEjb but no luck
            itemIds = (ListElementRemoteForStateful)ic.lookup(""java:global/EjbPrototype/StatefulEjb"");

           }
           catch(Exception e)
           {
               System.out.println(e);
           }
    }
%&gt;
</code></pre>

<p>I have following result produced by accepted answer of <a href=""https://stackoverflow.com/questions/2324937/code-to-list-all-the-entries-in-jndi-on-remote-machine"">SOQ</a>
<a href=""https://i.stack.imgur.com/tK1ks.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/tK1ks.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/42942602/initialcontext-lookuppath-throws-javax-naming-namingexception,"['java', 'stateful-session-bean']",151,FALSE,0,0
how to writing junit test for opengl es2.0 android app,"<p>i was new to this android testing. What i want is to write a junit(with Mockito) test for my fragment which is a GLSurfaceView with one Custom GLRenderer.</p>

<pre><code>public class SuefaceViewFragment extends Fragment{

private View mRootView;

private GLSurfaceView mSurfaceView;
private CustomRenderer mRenderer;


public SurfaceViewFragment() {

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mRootView = inflater.inflate(R.layout.fragment_surface_view, container, false);
    initView();
    return mRootView;
}


private void initView() {
    mSurfaceView = (GLSurfaceView) mRootView.findViewById(R.id.surface_view);

    mSurfaceView .setRenderer(mRenderer);
    mSurfaceView .setZOrderMediaOverlay(true);        
    mSurfaceView .setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
}


@Override
public void onResume() {
    super.onResume();
    mSurfaceView.onResume();
}

@Override
public void onPause() {
    super.onPause();
    mSurfaceView.onPause();
}
</code></pre>

<p>}</p>

<p>this is the GLSurfaceView </p>

<pre><code>public class CustomRenderer implements GLSurfaceView.Renderer {




public CustomRenderer() {

}



private void init() {

    GLES20.glDisable(GLES20.GL_BLEND);
    GLES20.glClearColor(1.0f, 1.0f, 1.0f, 1.0f);

}

@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
    init();
}

@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
    GLES20.glViewport(0, 0, width, height);

}

@Override
public void onDrawFrame(GL10 gl) {

    render();
}

private void render() {
    GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT);

   // To Do Rendering code

}
</code></pre>

<p>I want to write unit testing for this above fragment using using Junit and Mockito. is it possible? if possible how to write?</p>
",https://stackoverflow.com/questions/45035251/how-to-writing-junit-test-for-opengl-es2-0-android-app,"['android', 'junit', 'opengl-es', 'mockito', 'opengl-es-2.0']",499,TRUE,0,1
Hyperledger Fabric unit test cross-chaincode invocation without collapsing vendor folder,"<p>I have been running into compilation issues when I tried to perform unit testing in golang locally, when trying to instantiate and invoke another chaincode through the MockStub object. Below is my file hierarchy:</p>

<pre><code>├── transaction-chaincode
│   ├── transaction.go
│   ├── transaction_test.go
│   └── vendor
└── user-chaincode
    ├── user.go
    ├── user_test.go
    └── vendor
</code></pre>

<p>The scenario here basically involves one of the chaincode, for example user.go, calling the other chaincode transaction.go. The vendor folders in both directories contain the exact same content.</p>

<p>The problem occurs when I try to instantiate a new instance of the transaction chaincode thru shim.NewMockStub in user_test.go, as the transaction mock object looks for the init method from within transaction-chaincode/vendor/ instead of user-chaincode/vendor/, despite the vendor folders having the same packages (and thus the same method).</p>

<p>I was able to get rid of this error by having a single vendor folder at the parent directory of transaction-chaincode &amp; user-chaincode, but I cannot do so for developmental purposes.  How would you suggest I solve this unit testing problem while keeping the vendor folders in their respective locations?</p>
",https://stackoverflow.com/questions/45196860/hyperledger-fabric-unit-test-cross-chaincode-invocation-without-collapsing-vendo,"['go', 'hyperledger', 'hyperledger-fabric']",521,FALSE,1,1
JUnit testing with KOTLIN android studio [Basic Calculator],"<p>I am very new to android developing and recently did my first project. It is only a basic calculator with addition, subtraction, multiplication and division.</p>

<p>Now, I am looking to go into Unit testing using JUnits with KOTLIN. How should I go about doing this? I've been searching around and have no idea.</p>

<p>Calculator Java Codes:</p>

<pre><code>package com.example.zhiwen.calculator;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity{

Button plus,minus,times,divide;
TextView textview3;
EditText first, second;
double no1 = 0, no2 = 0;
double answer = 0;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    plus = (Button) findViewById(R.id.plus);
    minus = (Button) findViewById(R.id.minus);
    times = (Button) findViewById(R.id.times);
    divide = (Button) findViewById(R.id.divide);
    textview3 = (TextView) findViewById(R.id.textview3);
    first = (EditText) findViewById(R.id.editText);
    second = (EditText) findViewById(R.id.editText2);


}

public void ClickMeButton(View view){
    if(first.getText().toString().isEmpty() || second.getText().toString().isEmpty())
    {
        textview3.setText(""Answer: -"");
        Toast.makeText(getApplicationContext(),""Please fill up both numbers"",Toast.LENGTH_SHORT).show();
    }
    else
    {
        no1 = Integer.parseInt(first.getText().toString());
        no2 = Integer.parseInt(second.getText().toString());
        textview3.setText(""Answer: "" + Functions.addFunction(no1,no2));
    }

}



public void ClickMeButton2(View view){
    if(first.getText().toString().isEmpty() || second.getText().toString().isEmpty())
    {
        textview3.setText(""Answer: -"");
        Toast.makeText(getApplicationContext(),""Please fill up both numbers"",Toast.LENGTH_SHORT).show();
    }
    else
    {
        no1 = Integer.parseInt(first.getText().toString());
        no2 = Integer.parseInt(second.getText().toString());
        textview3.setText(""Answer: "" + Functions.minusFunction(no1,no2));
    }

}
public void ClickMeButton3(View view){
    if(first.getText().toString().isEmpty() || second.getText().toString().isEmpty())
    {
        textview3.setText(""Answer: -"");
        Toast.makeText(getApplicationContext(),""Please fill up both numbers"",Toast.LENGTH_SHORT).show();
    }
    else
    {
        no1 = Integer.parseInt(first.getText().toString());
        no2 = Integer.parseInt(second.getText().toString());
        textview3.setText(""Answer: "" + Functions.multiFunction(no1,no2));
    }

}
public void ClickMeButton4(View view){
    if(first.getText().toString().isEmpty() || second.getText().toString().isEmpty())
    {
        textview3.setText(""Answer: -"");
        Toast.makeText(getApplicationContext(),""Please fill up both numbers"",Toast.LENGTH_SHORT).show();
    }
    else
    {
        no1 = Integer.parseInt(first.getText().toString());
        no2 = Integer.parseInt(second.getText().toString());
        textview3.setText(""Answer: "" + Functions.divFunction(no1,no2));
    }

}
</code></pre>

<p>}</p>

<p>Function Class Codes:</p>

<pre><code>package com.example.zhiwen.calculator;

/**
 * Created by Zhiwen on 5/25/2017.
 */

public class Functions {

public static double addFunction(double no1, double no2){
    double answer;
    answer = no1 + no2;
    return answer;
}

public static double minusFunction(double no1, double no2){
    double answer;
    answer = no1 - no2;
    return answer;
}

public static double multiFunction(double no1, double no2){
    double answer;
    answer = no1 * no2;
    return answer;
}

public static double divFunction(double no1, double no2){
    double answer;
    answer = no1 / no2;
    return answer;
}
</code></pre>

<p>}</p>
",https://stackoverflow.com/questions/44176585/junit-testing-with-kotlin-android-studio-basic-calculator,"['java', 'android', 'junit', 'kotlin']",936,TRUE,0,1
Wipe all tables in a schema - sequelize nodejs,"<p>To perform unit testing on a mysql database using sequelize as ORM, I need to refresh my database when each test start to run.
Actually I wrote a solution like this:</p>

<pre><code>beforeEach(() =&gt; {
   table1.destroy({ where: {} })
   table2.destroy({ where: {} })
   table3.destroy({ where: {} })
})
</code></pre>

<p>but every time I create tables I have to add another instruction.
I would implement a single instruction to perform a complete wipe of the entire schema</p>

<p>Something like:</p>

<pre><code>beforeEach(() =&gt; db.clean())
</code></pre>
",https://stackoverflow.com/questions/47816162/wipe-all-tables-in-a-schema-sequelize-nodejs,"['javascript', 'mysql', 'sql', 'node.js']",4133,TRUE,3,2
angular 2 unit test my component is not updated after async service call,"<p>I'm new to angular 2 and unit testing with jasmine, I'm trying to test that my async service is called by my ng-on-init and that the value is set in my componenent </p>

<p>here is my component : </p>

<pre><code>@Component({
  selector: 'fragment-overlay',
  templateUrl: './fragment-overlay.component.html',
  styleUrls: ['./fragment-overlay.component.css']
})
export class FragmentOverlayComponent implements OnInit {

  @Input()
  fragmentOverlay:FragmentOverlay;

  @Input()
  index: Number;

  fragmentDefinition:FragmentDefinition;


  constructor(private fragmentService:FragmentService) {
  }

  ngOnInit():void {
    let fragmentId = this.fragmentOverlay.fragmentId;

    this.fragmentService.getFragmentDefinitionByConfigurationId(fragmentId).subscribe(function (fragmentDefinition:FragmentDefinition) {
      this.fragmentDefinition = fragmentDefinition;
      console.log(""blablabla ""+fragmentDefinition);
    });
  }

  ngOnChanges(changes) {
    if (changes.hasOwnProperty(""index"") &amp;&amp; !changes.index.firstChange ){
      console.log(this.fragmentOverlay.fragmentId +""previous ""+ changes.index.previousValue +""after ""+changes.index.currentValue);
    }
  }
}
</code></pre>

<p>here is my test : </p>

<pre><code>describe('Fragment overlay ', () =&gt; {

  let comp:    FragmentOverlayComponent;
  let fixture: ComponentFixture&lt;FragmentOverlayComponent&gt;;
  let de:      DebugElement;
  let el:      HTMLElement;
  let spy ;


  class FragmentServiceMock {
    private fragmentDefinitionTest = new FragmentDefinition(""id"", ""label"", false, true, [], ""location"");

    getFragmentDefinitionByConfigurationId(id:string):Observable&lt;FragmentDefinition&gt; { return Observable.of(this.fragmentDefinitionTest) }
  }


  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [HttpModule],
      declarations: [FragmentOverlayComponent],// declare the test component
      providers: [FragmentService, { provide: XHRBackend, useClass: MockBackend },]
    })
      .compileComponents();  // compile template and css
    fixture = TestBed.createComponent(FragmentOverlayComponent);



    comp = fixture.componentInstance;

    let fragService = fixture.debugElement.injector.get(FragmentService);

    let fragmentDefinitionTest = new FragmentDefinition(""id"", ""label"", false, true, [], ""location"");

    spy = spyOn(fragService, 'getFragmentDefinitionByConfigurationId')
      .and.returnValue(Observable.of(fragmentDefinitionTest));

    comp.fragmentOverlay = new FragmentOverlay();
    comp.fragmentOverlay.fragmentId = ""idFragment"";


    // query for the title &lt;h1&gt; by CSS element selector
    de = fixture.debugElement.query(By.css('.fragment-overlay'));
    el = de.nativeElement;

  });



  it('should get a definition avec init async call resolved', async(() =&gt; {
    fixture.detectChanges();
    fixture.whenStable().then(() =&gt; { // wait for async getFragmentDefinitionByConfigurationId
      fixture.detectChanges();        // update view with quote
      expect(fixture.componentInstance.fragmentDefinition).toBeDefined();

    });
  }));


  it('should show quote after getQuote promise (fakeAsync)', fakeAsync(() =&gt; {
    fixture.detectChanges();
    tick();                  // wait for async getQuote
    fixture.detectChanges(); // update view with quote

  }));


});
</code></pre>

<p>expect(fixture.componentInstance.fragmentDefinition).toBeDefined(); --> fail</p>

<p>I've been stuck for a couple of hours, any help would be welcome </p>
",https://stackoverflow.com/questions/43997411/angular-2-unit-test-my-component-is-not-updated-after-async-service-call,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",1082,TRUE,0,1
Unit test AWS S3 functions with Mocha in Node,"<p>How can I mock S3 calls when unit testing in Node. I want to make sure the function is unit tested without making actual calls to S3. I would like to test what happens if everything goes as expected and if there are errors. I think Sinon is the tool of choice but I'm not sure how?</p>

<p>My s3 file is:</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>const AWS = require('aws-sdk');

AWS.config.region = 'ap-southeast-2';
const s3 = new AWS.S3();
const { S3_BUCKET } = process.env;
const propertyCheck = require('./utils/property-check');

module.exports.uploadS3 = (binary, folderName, fileName) =&gt; new Promise((resolve, reject) =&gt; {
    if (!propertyCheck.valid(binary) ||
        !propertyCheck.validString(folderName) ||
        !propertyCheck.validString(fileName)) {
        const error = '[uploadS3] Couldn\'t upload to S3 because of validation errors.';
        console.error(error);
        return reject(new Error(error));
    }
    const finalUrl = `${encodeURIComponent(folderName)}/${encodeURIComponent(fileName)}`;
    s3.putObject({
        Body: binary,
        Key: finalUrl,
        Bucket: S3_BUCKET,
        ContentType: 'application/pdf',
        ContentDisposition: 'inline',
        ACL: 'public-read'
    }, (error, data) =&gt; {
        if (error) {
            console.error(error);
            return reject(new Error(`[uploadS3] ${error}`));
        }
        resolve(`https://${S3_BUCKET}.s3.amazonaws.com/${finalUrl}`);
    });
});</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/47089671/unit-test-aws-s3-functions-with-mocha-in-node,"['node.js', 'unit-testing', 'amazon-s3', 'mocha.js']",3165,TRUE,2,1
Conflict with dependency &#39;com.android.support:support-annotations&#39;,"<p>I am trying to set up an Instrumented Unit Tests for my App. and I have added dependency based on the below developer site link.</p>

<p><a href=""https://developer.android.com/training/testing/unit-testing/instrumented-unit-tests.html#build"" rel=""nofollow noreferrer"">https://developer.android.com/training/testing/unit-testing/instrumented-unit-tests.html#build</a></p>

<p>This is my dependency list</p>

<pre><code>dependencies {
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.android.support:support-v4:21.0.3'
    testCompile 'junit:junit:4.12'
    testCompile 'org.mockito:mockito-core:1.10.19'
    androidTestCompile 'com.android.support:support-annotations:24.0.0'
    androidTestCompile 'com.android.support.test:runner:0.5'
    androidTestCompile 'com.android.support.test:rules:0.5'
}
</code></pre>

<p>When I build the project I am getting the below compile error:</p>

<pre><code>Error:Conflict with dependency 'com.android.support:support-annotations' in project ':MyApp'. Resolved versions for the app (21.0.3) and test app (24.0.0) differ. See http://g.co/androidstudio/app-test-app-conflict for details.
</code></pre>

<p>Could anyone please help me to resolve this issue.</p>
",https://stackoverflow.com/questions/46419837/conflict-with-dependency-com-android-supportsupport-annotations,"['android', 'unit-testing', 'android-testing', 'android-instrumentation']",527,TRUE,2,1
Write unit tests with TestNG in Eclipse,"<p>The class <strong>MobileStorage</strong> is the implementation of a retro mobile phone's inbox. The inbox thereby is dened to hold a predened maximum capacity of messages with up to 160 characters per message. The following operations are supported and need to be tested:</p>

<ol>
<li><strong>saveMessage</strong>: Stores a new text message to the inbox at the next free position. In case the
message text is longer than 160 characters, the message is splitted and stored on multiple
storage positions.</li>
<li><strong>deleteMessage</strong>: Removes the oldest (rst) mobile message from the inbox.</li>
<li><strong>listMessages</strong>: Prints a readable representation of all currently stored messages. Messages that were stored in multiple parts are joined together for representation.</li>
</ol>

<p>I need to do some Unit Testing on this code that i attached. Im not very familiar with TestNG and unit testing in general, can you help me with some examples of testing that i can do?</p>

<p><strong>mobile_storage\src\main\java\MobileMessage.java - <a href=""https://pastebin.com/RxNcgnSi"" rel=""nofollow noreferrer"">https://pastebin.com/RxNcgnSi</a></strong></p>

<pre><code>/**
 * Represents a mobile text message.
 */
public class MobileMessage {
    //stores the content of this messages
    private final String text;

    //in case of multi-part-messages, stores the preceding message
    //is null in case of single message
    private MobileMessage predecessor;

    public MobileMessage(String text, MobileMessage predecessor) {
        this.text = text;
        this.predecessor = predecessor;
    }

    public String getText() {
        return text;
    }

    public MobileMessage getPredecessor() {
        return predecessor;
    }

    public void setPredecessor(MobileMessage predecessor) {
        this.predecessor = predecessor;
    }
}
</code></pre>

<p><strong>mobile_storage\src\main\java\MobileStorage.java - <a href=""https://pastebin.com/wuqKgvFD"" rel=""nofollow noreferrer"">https://pastebin.com/wuqKgvFD</a></strong></p>

<pre><code>import org.apache.commons.lang.StringUtils;

import java.util.Arrays;
import java.util.Objects;
import java.util.stream.IntStream;

/**
 * Represents the message inbox of a mobile phone.
 * Each storage position in the inbox can store a message with 160 characters at most.
 * Messages are stored with increasing order (oldest first).
 */
public class MobileStorage {

    final static int MAX_MESSAGE_LENGTH = 160;

    private MobileMessage[] inbox;
    private int occupied = 0;

    /**
     * Creates a message inbox that can store {@code storageSize} mobile messages.
     * @throws IllegalArgumentException in case the passed {@code storageSize} is zero or less
     */
    public MobileStorage(int storageSize) {
        if(storageSize &lt; 1) {
            throw new IllegalArgumentException(""Storage size must be greater than 0"");
        }

        this.inbox = new MobileMessage[storageSize];
    }

    /**
     * Stores a new text message to the inbox.
     * In case the message text is longer than {@code MAX_MESSAGE_LENGTH}, the message is splitted and stored on multiple storage positions.
     * @param message a non-empty message text
     * @throws IllegalArgumentException in case the given message is empty
     * @throws RuntimeException in case the available storage is too small for storing the complete message text
     */
    public void saveMessage(String message) {
        if(StringUtils.isBlank(message)) {
            throw new IllegalArgumentException(""Message cannot be null or empty"");
        }

        int requiredStorage = (int) Math.ceil((double) message.length() / MAX_MESSAGE_LENGTH);

        if(requiredStorage &gt; inbox.length || (inbox.length - occupied) &lt;= requiredStorage) {
            throw new RuntimeException(""Storage Overflow"");
        }

        MobileMessage predecessor = null;
        for(int i = 0; i &lt; requiredStorage; i++) {
            int from = i * MAX_MESSAGE_LENGTH;
            int to = Math.min((i+1) * MAX_MESSAGE_LENGTH, message.length());

            String messagePart = message.substring(from, to);
            MobileMessage mobileMessage = new MobileMessage(messagePart, predecessor);
            inbox[occupied] = mobileMessage;
            occupied++;
            predecessor = mobileMessage;
        }
    }

    /**
     * Returns the number of currently stored mobile messages.
     */
    public int getOccupied() {
        return occupied;
    }

    /**
     * Removes the oldest (first) mobile message from the inbox.
     *
     * @return the deleted message
     * @throws RuntimeException in case there are currently no messages stored
     */
    public String deleteMessage() {
        if(occupied == 0) {
            throw new RuntimeException(""There are no messages in the inbox"");
        }

        MobileMessage first = inbox[0];

        IntStream.range(1, occupied).forEach(index -&gt; inbox[index-1] = inbox[index]);
        inbox[occupied] = null;
        inbox[0].setPredecessor(null);
        occupied--;

        return first.getText();
    }

    /**
     * Returns a readable representation of all currently stored messages.
     * Messages that were stored in multiple parts are joined together for representation.
     * returns an empty String in case there are currently no messages stored
     */
    public String listMessages() {
        return Arrays.stream(inbox)
                .filter(Objects::nonNull)
                .collect(StringBuilder::new, MobileStorage::foldMessage, StringBuilder::append)
                .toString();
    }

    private static void foldMessage(StringBuilder builder, MobileMessage message) {
        if (message.getPredecessor() == null &amp;&amp; builder.length() != 0) {
            builder.append('\n');
        }
        builder.append(message.getText());
    }
}
</code></pre>
",https://stackoverflow.com/questions/47000965/write-unit-tests-with-testng-in-eclipse,"['java', 'eclipse', 'unit-testing', 'testng', 'testcase']",422,TRUE,0,1
How to Unit Test a GlassController Action without SitecoreContext Dependency Injection,"<p>I'm a sitecore developer, and I want to create a sample sitecore helix unit testing project for testing out the <strong>exact</strong> below Index() action method of our ""HomeBottomContentController"" controller, <em>without any dependency injection</em> into a constructor.  Note that the commented-out code is exactly what I do NOT want to do.  </p>

<pre><code>public class HomeBottomContentController : GlassController
{
    // I want to test the EXACT method below
    public override ActionResult Index()
    {
        var context = new SitecoreContext();
        var model = context.GetCurrentItem&lt;Home_Control&gt;();
        return View(""~/Views/HomeBottomContent/HomeBottomContent.cshtml"", model);
    }

    /*
    // I do NOT want to have any of the below code for injecting ISitecoreContext into a constructor and testing the IndexTest() below it.
    private readonly ISitecoreContext _iSitecoreContext;
    public HomeBottomContentController(ISitecoreContext iSitecoreContext)
    {
        _iSitecoreContext = iSitecoreContext;
    }

    public HomeBottomContentController()
    { }

    public ActionResult IndexTest()
    {
        var model = _iSitecoreContext.GetCurrentItem&lt;Home_Control&gt;();
        return View(""~/Views/HomeBottomContent/HomeBottomContent.cshtml"", model);
    }
    */
}
</code></pre>

<p>Here's what I have in my unit testing class.  Again, what I have commented out exactly what I <strong>don't</strong> want to do:</p>

<pre><code>[TestClass]
public class MvcUnitTests
{
    [TestMethod]
    public void Test_HomeBottomContentController_With_ISitecoreContext()
    {
        /*
        // I don't want to do below...
        var model = new Home_Control()
        { Bottom_Content = ""XYZ"" };

        var iSitecoreContext = new Mock&lt;Glass.Mapper.Sc.ISitecoreContext&gt;();
        iSitecoreContext.Setup(_ =&gt; _.GetCurrentItem&lt;Home_Control&gt;(false, false)).Returns(model);

        HomeBottomContentController controllerUnderTest = new HomeBottomContentController(iSitecoreContext.Object);

        var result = controllerUnderTest.IndexTest() as ViewResult;
        */

        //I want to test using the exact constructor below and calling that exact Index() method.  
        HomeBottomContentController controllerUnderTest = new HomeBottomContentController();
        var result = controllerUnderTest.Index() as ViewResult;
        Assert.IsNotNull(result);
        Assert.IsNotNull(result.Model);
        //Assert.AreEqual(((Home_Control)result.Model).Bottom_Content, ""XYZ"");
    }
}
</code></pre>

<p>How can I test my controller's exact Index() method without having to add code to the HomeBottomContentController class that enables dependency injection into a constructor (like the commented-out code above)?  I do not want to have to add code to HomeBottomContentController().</p>

<p>@Aleksey Shevchenko If I try your solution, how do I exactly hook up the model to the iSitecoreContext and then assign that to the controllerUnderTest.FakeContext?  My code below throws compilation error (You cannot convert from Mock of Glass.Mapper.Sc.ISitecoreContext to Glass.Mapper.Sc.ISitecoreContext, how do we accomplish that):</p>

<pre><code>var model = new Home_Control()
{ Top_Content = ""Some Dummy Test Home Top Content"" };
var iSitecoreContext = new Mock&lt;Glass.Mapper.Sc.ISitecoreContext&gt;();
//var iSitecoreContext = new Glass.Mapper.Sc.SitecoreContext();       
iSitecoreContext.Setup(_ =&gt; _.GetCurrentItem&lt;Home_Control&gt;(false, false)).Returns(model);
FakeHomeTopContentController controllerUnderTest = new FakeHomeTopContentController();
controllerUnderTest.FakeContext = (Glass.Mapper.Sc.SitecoreContext)iSitecoreContext;
</code></pre>
",https://stackoverflow.com/questions/46409352/how-to-unit-test-a-glasscontroller-action-without-sitecorecontext-dependency-inj,"['c#', 'unit-testing', 'dependency-injection', 'sitecore-mvc', 'glass-mapper']",610,TRUE,0,2
Can I get Mocha to not show passed tests?,"<p>We just started unit testing at work using Mocha and Karma. We have less than 100 tests, and having to sift through all the passed tests to find the failed ones is already cumbersome. I can't imagine what it'll be like when we have thousands of tests. Is there a way to make it so the passed tests don't show up? </p>
",https://stackoverflow.com/questions/45016271/can-i-get-mocha-to-not-show-passed-tests,"['angular', 'unit-testing', 'karma-jasmine', 'karma-mocha', 'gulp-mocha']",134,TRUE,2,1
Entry point was not found on calling Dispose,"<p>I'm unit testing a piece of code that uses a nested using statement. I've changed it to a <code>using</code> statement in a <code>try/finally</code> block. When I try to call the <code>Dispose</code> method in the <code>finally</code> block I get an <code>EntryPointNotFoundException</code>. I've tried a lot of things but I'm not sure how to solve this problem. Here is my code:</p>

<pre><code>var memoryStream = new MemoryStream(message.FileContent);

try
{
    using (var sftpClient = this.GetSftpClientFromId(message.CustomerId))
    {
        return sftpClient.UploadFileAsync(memoryStream, message.FileName, true);
    }
}
finally
{
    memoryStream?.Dispose();
}
</code></pre>

<p>How can I solve this issue?</p>
",https://stackoverflow.com/questions/42946374/entry-point-was-not-found-on-calling-dispose,"['c#', 'unit-testing', 'entrypointnotfoundexcept']",451,TRUE,2,1
Jest mounting component - Invariant Violation: _registerComponent(...): Target container is not a DOM element,"<p>Having trouble getting enzyme MOUNT to work for my component unit testing. I have a basic component that imports a component from an external package and I would like to do a full render so I can see the children of that external component. This is a small issue but need to get MOUNT working for other smarter components.</p>

<p>Current behavior:
<code>
    Invariant Violation: _registerComponent(...): Target container is not a DOM element at invariant (node_modules/fbjs/lib/invariant.js:42:15)
</code></p>

<p>Code</p>

<pre><code>import { FormattedMessage } from 'react-intl'

class TestMenu extends PureComponent {
 render() {
 return (
  &lt;div className=""container""&gt;
       &lt;FormattedMessage
           defaultMessage={'HELLO'} /&gt;
  &lt;/div&gt;
 )
 }
}export default TestMenu



describe.only('&lt;Test /&gt;', () =&gt; { let testMenu
    beforeEach(() =&gt; {
      testMenu = mount(&lt;TestMenu {...props}/&gt;)
    })
  it('Should render the Formatted Component with &lt;span&gt;'Hello'&lt;/span&gt;', 
     () =&gt; {
      expect(testMenu.find('span').text()).to.equal('Hello')
 })
})
</code></pre>
",https://stackoverflow.com/questions/47022950/jest-mounting-component-invariant-violation-registercomponent-target-c,"['javascript', 'mount', 'enzyme', 'jestjs']",309,FALSE,2,0
Calling function by triggering selectChange event Angular testing,"<p>I started working on a small project in Angular(v4.0.0). In this project, I am adding unit testing. I read the <a href=""https://angular.io/guide/testing"" rel=""nofollow noreferrer"">angular testing documentation</a> and now have basic understanding of how to write unit testing in angular.</p>

<p>In this, I am struggling writing test case for a function which triggers on <code>selectChange</code> event from html.</p>

<p><strong>Code snippet of html</strong></p>

<pre><code>html content
        &lt;div class=""metabs""&gt;
            &lt;md-tab-group (selectChange)=""selectMetabs($event)"" [selectedIndex]=""selectedIndex"" *ngIf=""!showAllMetabs""&gt;
                    &lt;md-tab [label]=""metab.name"" *ngFor=""let metab of dashboards""&gt;&lt;/md-tab&gt;                        
            &lt;/md-tab-group&gt;                    
        &lt;/div&gt;
</code></pre>

<p><strong>code snippet of ts</strong></p>

<pre><code>// Corresponding ts containing selectMetabs function

selectMetabs(event) {
  console.log(""--in select metabos--"");  // this console is not getting printed
  // rest of the code 
}
</code></pre>

<p>Now I wrote the test case for this which is:</p>

<pre><code>describe('DashboardComponent', () =&gt; {
    let fixture: ComponentFixture&lt;DashboardComponent&gt;;
    let comp: DashboardComponent;
    let de: DebugElement;
    let el: HTMLElement;
    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            declarations: [
                DashboardComponent,
            ],
            providers: [
            ],
            imports: [
                BrowserAnimationsModule,
                AppMaterialModule,
            ],
            schemas: [ CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA ],
        }).compileComponents()
        fixture = TestBed.createComponent(DashboardComponent)
        comp = fixture.componentInstance
    }))

it(""should check selectMetabs function call"", async(() =&gt; {
    comp.showAllMetabs = false;
    fixture.detectChanges();
    let de = fixture.debugElement.query(By.css('.metabs &gt; md-tab-group'));
    let spy = spyOn(comp, 'selectMetabs');
    de.triggerEventHandler('selectChange', {index: 0});
    expect(spy).toHaveBeenCalled(); // pass test case
    expect(spy).toHaveBeenCalledTimes(1); // pass test case
    expect(comp.selectMetabolite).toHaveBeenCalledWith({index:0}); // pass test case
}))
</code></pre>

<p>These of my test cases is getting passed, which assures me that triggerEvent is working.</p>

<p>My confusion is that if <code>selectMetabs</code> function is getting called they why that console statement is not getting printed.</p>

<p>Also, this function is not getting covered in test coverage also.</p>

<p>I am not able to understand why this is happening. I am new to angular testing and this issue is confusing me. Please let me know if I am missing something or if I need to provide more info.</p>

<p>Useful suggestions will be appreciated. Thanks!!</p>
",https://stackoverflow.com/questions/46629388/calling-function-by-triggering-selectchange-event-angular-testing,"['angular', 'unit-testing', 'jasmine', 'angular-test']",1123,FALSE,0,1
How to unit test the database code for Sql Server 2014,"<p>I am working on developing a unit test framework for the db code in Sql Server 2014. My requirement is following:</p>

<ul>
<li>The tool should provide enough assertions to check the db schema, positive values, negative values, exceptions and constraints.</li>
<li>The tool should provide mocking and stubbing for the db stored procs</li>
<li>The tool should be able to generate .TRX reports for the passed/failed test cases as I want to pulbish these reports using VSTS/TFS build</li>
<li>Code coverage if possible</li>
<li>The tool should be able to integrate with the TFS build template for the CI purpose.</li>
</ul>

<p>After doing some research, I think i have three options with the help of the tools SSDT with MSTest and tSqlT as:</p>

<ul>
<li>Using SSDT for test database initialization/cleanup and using MsTest for Sql unit testing but it has no mocking feature and the options for assertion are also limited. Cleanup is also manual</li>
<li>Using tSqlT for unit test cases. it is a nice and powerful tool but it does not provide a GUI like SSDT. The redGate GUI is paid which is not possible in my case. Also it seems tougher to integrate it with TFS builds. And this does not produce reports in .TRX format but in .XML format.</li>
<li>Using combination of SSDT and tSqlT as SSDT for db initialization, TFS integration and runnig tSqlT code from the MSTest project and tSqlT for the db unit testing.</li>
</ul>

<p>Can anyone suggest a better approach on the db unit testing?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/43270137/how-to-unit-test-the-database-code-for-sql-server-2014,"['unit-testing', 'tfs', 'mstest', 'sql-server-data-tools', 'tsqlt']",1057,TRUE,0,2
Mock methods on Static Instance,"<p>I have a class as :</p>

<pre><code>public class Factory {
   private static final Factory instance = new Factory();
   private Factory() {
   }
   public static Factory getInstance() {
       return instance;
   }
   private Client client = null;

   //To be mocked
   //Failing at this point 
   //Not actually using mocked method
   public Client getClient(Properties properties) {
      //doSomething
      //...
      return client;
   }
}
</code></pre>

<p>In another class above method is used as:</p>

<pre><code>public class Service {
  protected Client client = null;
  protected void keySetup() {
     //Should be mocked
     client = Factory.getInstance().getClient(properties());

     ...
     ...
  }
}
</code></pre>

<p>For unit testing the keySetup() method, I am trying to mock the <strong>Factory.getInstance().getClient(properties())</strong> but I am failing. </p>

<p>I try doing the following: </p>

<pre><code>@Test
public void testKeySetupTrue(){
    Client client = mock(Client.class); 
    Factory factory = mock(Factory.class);
    ReflectionTestUtils.setField(factory, ""client"", client);    
    Properties properties = mock(Properties.class);

    Mockito.doReturn(client).when(factory)
    .getClient(properties);

    Service service = new Service();

    service.keySetup();
    ...
    ...
}
</code></pre>

<p>When I was running in debug mode I saw it was actually executing the <strong>getClient(Properties properties)</strong> which was mocked. </p>

<p>How to resolve this? </p>
",https://stackoverflow.com/questions/47289612/mock-methods-on-static-instance,"['java', 'unit-testing', 'mockito']",408,TRUE,1,1
Mocking the UnitOfWorkManager.Current in a unit test,"<p>When unit testing, the system cannot resolve <code>UnitOfWorkManager.Current</code> (nullreference exception). The <code>_unitOfWorkManager</code> is of type: <code>IUnitOfWorkManager</code>, and injected via DI.</p>

<p>I'm testing the following web api code:</p>

<pre><code>[HttpPost]
public async Task&lt;IHttpActionResult&gt; Subscription(SubscriptionInputDto model)
{
    if (!await VendorHasAccess(model.OrganizationId))
        return StatusCode(HttpStatusCode.Forbidden);

    var input = new Subscription
    {
        ...
    };

    var data = await _subscriptionRepository.InsertAsync(input);

    await _unitOfWorkManager.Current.SaveChangesAsync();

    return Ok(data.MapTo&lt;SubscriptionDto&gt;());
}
</code></pre>

<p>…with the following unit test:</p>

<pre><code>[Fact]
public async Task Should_Create_New_Subscription()
{
    //Arrange
    var organization = await UsingDbContextAsync(async context =&gt; await context.VendorOrganizations.FirstOrDefaultAsync());
    var input = new SubscriptionInputDto { OrganizationId = organization.Id };

    //Act
    var actionResult = await _vendorController.Subscription(input);
    var response = actionResult as OkNegotiatedContentResult&lt;SubscriptionDto&gt;;

    //Assert
    Assert.NotNull(response);
    Assert.Equal(organization.Id, response.Content.OrganizationId);
}
</code></pre>

<p>I cannot figure out, or find any documentation on, how to resolve the <code>UnitOfWorkManager.Current</code> so that it doesn't fail for the unit test. 
The web API code itself works in production. </p>

<p>Any tips?</p>
",https://stackoverflow.com/questions/46423183/mocking-the-unitofworkmanager-current-in-a-unit-test,"['c#', 'unit-testing', 'xunit', 'aspnetboilerplate']",695,TRUE,1,1
Unable to mock a service to have it throw an exception,"<p>I'm new to using Mockito for unit-testing Spring Rest controllers. Here is my controller and my test code.</p>

<pre><code>@RestController
@RequestMapping(""/api/food/customer"")
public class CustomerController {
    @Autowired
    private CustomerService service;

    @RequestMapping(method=RequestMethod.POST, produces= MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity&lt;Customer&gt; addCustomer(@RequestBody Customer c){
        Logger log = LoggerFactory.getLogger(CustomerController.class.getName());
        try {
            service.addCustomer(c);
        } catch (UserNameException e){
            log.error(""UserNameException"", e);
            return new ResponseEntity(HttpStatus.BAD_REQUEST);
        } catch (Exception e){
            log.error("""", e);
            return new ResponseEntity(HttpStatus.BAD_REQUEST);
        }
        log.trace(""Customer added: "" + c.toString());
        return new ResponseEntity(c, HttpStatus.CREATED);
    }
}

@RunWith(MockitoJUnitRunner.class)
@WebMvcTest
public class CustomerRestTest {
    private MockMvc mockMvc;
    @Mock
    private CustomerService customerService;
    @Mock
    private CustomerDao customerDao;
    @InjectMocks
    private CustomerController customerController;

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

    @Test
    public void testAddDuplicateCustomer() throws Exception {
        Customer myCustomer = mock(Customer.class);
        when(customerService.addCustomer(myCustomer)).thenThrow(UserNameException.class);
        String content = ""{\""lastName\"" : \""Orr\"",\""firstName\"" : \""Richard\"",\""userName\"" : \""Ricky\""}"";
        RequestBuilder requestBuilder = MockMvcRequestBuilders.post(""/api/food/customer"").accept(MediaType.APPLICATION_JSON).
                content(content).contentType(MediaType.APPLICATION_JSON);
        MvcResult result = mockMvc.perform(requestBuilder).andReturn();
        MockHttpServletResponse response = result.getResponse();
        assertEquals(HttpStatus.BAD_REQUEST.value(), response.getStatus());
    }
}
</code></pre>

<p>I'm attempting to mock my service layer and have it throw my custom exception when <em>addCustomer</em> is called. I'm getting back HttpStatus.CREATED instead of BAD_REQUEST. What can I do differently with the service mock line (the one with thenThrow) that may work properly?</p>
",https://stackoverflow.com/questions/45526951/unable-to-mock-a-service-to-have-it-throw-an-exception,"['java', 'spring-mvc', 'spring-boot', 'junit', 'mockito']",4998,TRUE,1,1
How to test using Jest,"<p>I am new to Jest. Looking Jest as a unit testing framework, How can it be used for testing a website. I could found Jest examples applies to validation of Java script business functionalities but how can it be used for a website testing similar to Selenium.  It would be really great if somebody could  provide an update.</p>

<p>Thanks in Advance.</p>

<p>gtlkanth</p>
",https://stackoverflow.com/questions/45156646/how-to-test-using-jest,['jestjs'],318,TRUE,1,1
Golang: Mock a multiple http requests using gock,"<p>I am trying to mock a multiple http requests using gock for unit testing but I am getting this error:</p>

<pre><code>    Error:  Get https://192.64.23.33/q1/status: gock: cannot match any request
    Error:  Get https://194.55.5.6/q1/status: gock: cannot match any request
</code></pre>

<p>Code:</p>

<pre><code>func GetEmployee(url string, cli *http.Client) *Response {
    //Do something
    return Response
}

func company(url []string, cli *http.Client) []string {

    for employee := range url {
        resultList := GetEmployee(employee, cli)
        //Process and return an array
        return resultList
    }
}
</code></pre>

<p>Unittest:</p>

<pre><code>func TestCompany(t *Testing.t){
  Convey(""testing function company"",t,func() {
  expected := &amp;Response: {
                Name:     ""xyz"",
                ID:       1"",
                Status:   ""active"",

            }
  MockCli := &amp;http.Client{}
  testemployees := []string{""192.64.23.33"",""194.55.5.6""}
  for _, testempl := range testemployees {
        gock.New(fmt.Sprintf(""https://%s"", testempl)).
            Get(""/q1/status"").
            Reply(200).
            JSON(expected) 
        gock.InterceptClient(MockCli)
        response, err = company(testemployees, MockCli)

        //some assertions
       }
    })

  }
</code></pre>

<p>Unit tests failed when I am passing testemployees := []string{""192.64.23.33"",""194.55.5.6""} more than one element in a list otherwise if there is only one element then it  passes as expected.</p>

<p>How to mock a multiple URLs here so that gock can match a request?</p>
",https://stackoverflow.com/questions/45470862/golang-mock-a-multiple-http-requests-using-gock,"['unit-testing', 'go']",2528,FALSE,4,0
Laravel - PHPUnit - Model Factory - Many to Many relationships,"<p>Consider the following entites</p>

<pre><code>Students
Subjects
Exams
</code></pre>

<p>and following relationships</p>

<pre><code>Student belongsToMany Subjects (Many-to-Many)
Student hasMany Exams

Subject belongsToMany Students (Many-to-Many)
Subject hasMany Exams

Exam belongsTo Student
Exam belongsTo Subject
</code></pre>

<p>So I am writing some test cases for the models and its relationships using ModelFactory (I am new to unit testing). I need to test a case where the Student and Subject for a Exam is related. So I did the following in test and factory.</p>

<p>Test</p>

<pre><code>public function testStudentAndSubjectIsRelated()
{
    $exam = factory(Exam::class)-&gt;create();

    // We need to know whether the student and subject is related

    $this-&gt;assertTrue($exam-&gt;student-&gt;subjects()-&gt;pluck('id')-&gt;contains($exam-&gt;student_id));

    // And viceversa
    $this-&gt;assertTrue($exam-&gt;subject-&gt;students()-&gt;pluck('id')-&gt;contains($exam-&gt;subject_id));
}
</code></pre>

<p>Factory</p>

<pre><code>$factory-&gt;define(App\Exam::class, function (Faker\Generator $faker) {
    return [
        'student_id' =&gt; function () {
            return factory(App\Student::class)-&gt;create()-&gt;id;
        },
        'subject_id' =&gt; function ($exam) {
            $subject = factory(App\Subject::class)-&gt;create();

            $student = App\Student::find($exam['student_id']);

            $subject-&gt;students()-&gt;save($student);

            return $subject-&gt;id;
        },

        ....
    ];
});
</code></pre>

<p>Is this the right way of doing it?</p>
",https://stackoverflow.com/questions/47712203/laravel-phpunit-model-factory-many-to-many-relationships,"['laravel-5', 'phpunit', 'many-to-many', 'factory']",654,FALSE,1,0
TestThat cannot locate the file,"<p>I am building a plumber app, and plan to use TestThat for my unit testing. However, when I run <code>devtools::test()</code>, it says <code>File does not exist: test.R</code>.</p>

<p>My file name is test.R and my test file is already test-test.R.</p>

<p>Here is my testthat.R file:</p>

<pre><code>library(testthat)

test(""finalproject"")
test_check(""finalproject"")
</code></pre>

<p>And I also put: <code>source(""../../R/test.R"")</code> on my test-test.R already.</p>

<p>My question is how does TestThat define the code path? Can we define it manually? </p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/47024453/testthat-cannot-locate-the-file,"['r', 'testthat']",1203,TRUE,4,1
Unable to setup Jasmine for my Javascript project,"<p>I have created a JavaScript project and need to use Jasmine for unit testing. I have followed following steps : <br>
1. <b>npm install jasmine --save-dev</b> -  from project root directory<br>
2. Now when I try to initilize it using  <br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b> jasmine init</b><br>
It is giving me the below error. 
<b>'jasmine' is not recognized as an internal or external command,
operable program or batch file.</b>
<br>
Any lead to solve the issues will be appreciated.</p>
",https://stackoverflow.com/questions/41845745/unable-to-setup-jasmine-for-my-javascript-project,['jasmine'],3380,TRUE,7,3
java.lang.VerifyError: Bad type on operand stack when trying to run HttpServer provided by JDK,"<p>I am trying to do some unit testing by trying to mock the HttpServer. When i run this code it gives me errors:-     </p>

<pre><code>@RunWith(PowerMockRunner.class)
@PowerMockIgnore({""javax.net.ssl.*"", ""javax.management.*""})

public class POSTServerTest {
private String endPoint = ""http://localhost:30310/api/endpoint/"";
private String connectionTimeOut = ""3000"";
private String readTimeOut = ""3000"";

private HttpServer server;

@Captor
ArgumentCaptor&lt;Logger&gt; loggerArgumentCaptor;

@Captor
ArgumentCaptor&lt;String&gt; stringArgumentCaptor;

@Before
public void setUp() throws IOException {
    MockitoAnnotations.initMocks(this);
    server = HttpServer.create(new InetSocketAddress(8080), 0);
    server.start();

}

@Test
public void testReadTimeOutException() throws Exception {
    setConnectionTimeOut(""3000"");
    setReadTimeOut(""1"");
    //some code here 
}
}
</code></pre>

<p>and i get this error:-</p>

<pre><code>""C:\Program Files\Java\jdk1.8.0_131\bin\java"" 
java.lang.VerifyError: Bad type on operand stack
Exception Details:
  Location:
com/sun/net/httpserver/spi/HttpServerProvider$1.run()Ljava/lang/Object; @27: 
invokestatic
Reason:
Type 'sun/net/httpserver/DefaultHttpServerProvider' (current frame, 
stack[0]) is not assignable to 
'com/sun/net/httpserver/spi/HttpServerProvider'
Current Frame:
bci: @27
flags: { }
locals: { 'com/sun/net/httpserver/spi/HttpServerProvider$1' }
stack: { 'sun/net/httpserver/DefaultHttpServerProvider' }
Bytecode:
0x0000000: b800 2599 0007 b800 27b0 b800 2699 0007
0x0000010: b800 27b0 bb00 1b59 b700 2ab8 0028 57b8
0x0000020: 0027 b0                                
Stackmap Table:
same_frame(@10)
same_frame(@20)
at com.sun.net.httpserver.spi.HttpServerProvider.provider(HttpServerProvider.java:165)
at com.sun.net.httpserver.HttpServer.create(HttpServer.java:129)
at no.bbs.tt.oalarmer.vos.POSTServerTest.setUp(POSTServerTest.java:65)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.internal.runners.MethodRoadie.runBefores(MethodRoadie.java:132)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:95)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:310)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:131)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.access$100(PowerMockJUnit47RunnerDelegateImpl.java:59)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner$TestExecutorStatement.evaluate(PowerMockJUnit47RunnerDelegateImpl.java:147)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.evaluateStatement(PowerMockJUnit47RunnerDelegateImpl.java:107)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:298)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:86)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:218)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:160)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:134)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:33)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:45)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:136)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:121)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:57)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
</code></pre>

<p>I am trying to build it with maven and here is the maven output of the java version it is using:-</p>

<pre><code>Picked up JAVA_TOOL_OPTIONS: -Djava.net.preferIPv4Stack=true
Apache Maven 3.5.0 (ff8f5e7444045639af65f6095c62210b5713f426; 2017-04-
03T21:39:06+02:00)
Maven home: C:\Users\tshak\Downloads\apache-maven-3.5.0-bin\apache-maven-
3.5.0\bin\..
Java version: 1.8.0_131, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk1.8.0_131\jre
Default locale: en_US, platform encoding: Cp1252
OS name: ""windows 10"", version: ""10.0"", arch: ""amd64"", family: ""windows""
</code></pre>

<p>Can anyone help me in running this sample code of HttpServer?
Any help you be really appreciated. :)</p>
",https://stackoverflow.com/questions/47180532/java-lang-verifyerror-bad-type-on-operand-stack-when-trying-to-run-httpserver-p,"['java', 'maven', 'mockito', 'powermock']",1850,TRUE,4,2
Mocking forms in view unit tests,"<p>I can't seem to be able to mock the behaviour of a form when unit testing views.</p>

<p>My form is a simple ModelForm and resides in <code>profiles.forms</code>. The view is (again) a simple view that checks whether the form is valid and then redirects.</p>

<p>views.py</p>

<pre><code>from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from profiles.forms import ProfileForm

def home(request):
    form = ProfileForm()

    if request.method == 'POST':
        form = ProfileForm(request.POST)

        if form.is_valid():
            profile = form.save()
            return HttpResponseRedirect(reverse(""thanks""))
</code></pre>

<p>My test looks like this:</p>

<pre><code>class TestViewHomePost(TestCase):
    def setUp(self):
        self.factory = RequestFactory()

    def test_form(self):
        with mock.patch('profiles.views.ProfileForm') as mock_profile_form:
            mock_profile_form.is_valid.return_value = True
            request = self.factory.post(reverse(""home""), data={})
            response = home(request)
            logger.debug(mock_profile_form.is_valid.call_count)    # ""0""
</code></pre>

<p><code>is_valid</code> is not being called on the mock, which means ProfileForm is not patched.</p>

<p>Where did I make a mistake?</p>
",https://stackoverflow.com/questions/43570920/mocking-forms-in-view-unit-tests,"['django', 'django-forms', 'mocking', 'django-unittest']",1989,TRUE,7,1
React assert css property on component,"<p>I have a react component like</p>

<pre><code>const classNames = require('classNames/bind');
const someStyle = require('somestyle.scss');
const cx = classNames.bind(this);
const style = cx('someClass');
class Something extends React.Componenet {
   render() {
     return(&lt;div className={style} /&gt;);
     }
}
</code></pre>

<p>My scss file is like </p>

<pre><code>.someClass {
   width: 10px
}
</code></pre>

<p>I am trying to write a spec for unit testing this component to see if the width of that div tag is 10px or not. I am using enzyme+karma to shallow render my component. I am not able to find a way to assert this. Any help is much appreciated</p>
",https://stackoverflow.com/questions/43602546/react-assert-css-property-on-component,"['css', 'node.js', 'reactjs', 'jasmine', 'enzyme']",68,FALSE,1,0
Angular/Karma/Jasmine - undefined is not an object (evaluating &#39;commLogger.SetLogLevel&#39;),"<p>I'm trying to learn Karma and Jasmine Unit Testing but I'm currently encountering an error here. I tried to research all of the answers in this site but came up with no answers.</p>

<p>Below is my unit test file.</p>

<pre><code>describe('CommLogger', function() {
    var commLogger;

    beforeEach(module('FileLoggerManager'));

    beforeEach(inject(function (CommLogger) {
        commLogger = CommLogger;
    }));

    describe('SetLogLevel', function() {
       it('SetLogLevel Spec', function () {
            var logLevel = 0;
            commLogger.SetLogLevel(logLevel);
            expect(commLogger.SetLogLevel).toHaveBeenCalledWith(logLevel);
       });
    });
});
</code></pre>

<p>This is the the js file that I want to unit test.</p>

<pre><code>(function() {
    'use strict';
    angular
        .module('FileLoggerManager')
        .service('CommLogger', Body);

        function Body(LocalData, $q, $timeout) {
            var service = {
                writeLog: writeLog,
                SetFilePath: SetFilePath,
                SetMaxLogSize: SetMaxLogSize,
                DeleteLogFiles: DeleteLogFiles
            };

            var maxloglevel = 2;

            function SetLogLevel (logLevel) {
                console.log(""Comm Logger: Set log level to "" + logLevel);
                maxloglevel = logLevel;
            }

            return service;
        }
})();   
</code></pre>

<p>I would gladly appreciate any help. Thanks in advance!</p>
",https://stackoverflow.com/questions/43624855/angular-karma-jasmine-undefined-is-not-an-object-evaluating-commlogger-setlo,"['angularjs', 'jasmine', 'karma-runner']",252,TRUE,0,1
Jasmine : How to SpyOn a method callback : method.then(),"<p>within my Angular 4.0.0 app , i have this method , called in my component.</p>

<p>This method is called within a service :</p>

<pre><code>    this.myService.myMethod(param).then(any =&gt; {
        console.log(""success case"")
    })
      .catch(error =&gt; {
            console.log(""error"");
        }
      });
  };
</code></pre>

<p>Since i'm working on unit testing , i'm isolating my component via mocking the service : i'm mocking then this method , like the following :</p>

<pre><code>myMethodSpy= spyOn(service, 'myMethod').and.callFake((reg) =&gt; {
    return Observable.of('always error message');
});
</code></pre>

<p>But when executing , its seems that my spyMethod isn't called:</p>

<blockquote>
  <p>TypeError: this.service.myMethod(...).then is not a function</p>
</blockquote>

<p><em>Any ideas , about the problem's origin ?</em></p>
",https://stackoverflow.com/questions/47163269/jasmine-how-to-spyon-a-method-callback-method-then,"['angular', 'unit-testing', 'typescript', 'jasmine', 'spyon']",6304,TRUE,3,1
ELM model and Data from Rest Json,"<p>In most examples models are build with existing field/ data we are aware of as example, </p>

<pre><code>type alias Model =
  { topic : String
  , gifUrl : String
  }
</code></pre>

<p>Supposed i m building an application where i need to perform CRUD operations via REST and some of the fields are not know before hand which is more handy for Unit testing and Rapid development. </p>

<p>How do we model dynamic fields generated from REST/JSON ? </p>
",https://stackoverflow.com/questions/46278201/elm-model-and-data-from-rest-json,"['python', 'json', 'rest', 'elm']",118,TRUE,0,2
Mock.Verify throws errors but Mock.Setup actually has data,"<p>I'm new to unit testing and Mocking data.  I have 2 mocked repo's that I've set up like this :</p>

<pre><code>        [Test]
    public void TestRun()
    {

        _UserRepo.Setup(x =&gt; x.GetById(RequestCache, It.IsAny&lt;Guid&gt;())).Returns(new User
        {
            Id = Guid.NewGuid()
        });

        _repo.Setup(x =&gt; x.GetById&lt;Company&gt;(RequestCache, It.IsAny&lt;Guid&gt;())).Returns(new Company
        {
            Id = Guid.NewGuid()
        });


        var result = _query.Run(RequestCache);
        Assert.NotNull(result);
        Assert.IsFalse(result.HasErrorsOrWarnings());

        _UserRepo.Verify(x=&gt; x.GetById(RequestCache, It.IsAny&lt;Guid&gt;()), Times.Once);
        _repo.Verify(x=&gt; x.GetById&lt;Company&gt;(RequestCache, _id), Times.Once);
    }
</code></pre>

<p>When I debug I show that I do have a new user with a random guid and same with company.  Problem is when I verify that the repo's have been called I get an error expected 1 but was 0.</p>

<pre><code>        _UserRepo.Verify(x=&gt; x.GetById(RequestCache, It.IsAny&lt;Guid&gt;()), Times.Once);
        _repo.Verify(x=&gt; x.GetById&lt;Company&gt;(RequestCache, It.IsAny&lt;Guid&gt;()), Times.Once);
</code></pre>

<p>Any suggestions?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/44685693/mock-verify-throws-errors-but-mock-setup-actually-has-data,"['unit-testing', 'mocking']",21,FALSE,0,0
How to mock a helper method for errbot,"<p>I'm trying to complete my unit tests for the errbot plugin I am writing. Can anyone tell me how to mock out a helper method which is used by a <code>botcmd</code> method?</p>

<p>Example:</p>

<pre><code>class ChatBot(BotPlugin):

    @classmethod
    def mycommandhelper(cls):
        return 'This is my awesome commandz'

    @botcmd
    def mycommand(self, message, args):
        return self.mycommandhelper()
</code></pre>

<p>How can I mock the mycommandhelper class when executing the my command class? In my case this class is performing some remote operations which should not be executed during unit testing.</p>
",https://stackoverflow.com/questions/41848973/how-to-mock-a-helper-method-for-errbot,"['python', 'errbot']",141,FALSE,0,2
How to write IOS unit test case with Python?,"<p>Recently in the study of iOS unit testing framework XCTest, would like to package XCTest through Python to reduce the difficulty of writing unit test cases, to achieve the purpose of writing IOS unit test case with Python, but the relevant information is too small, so ask you big god there is What ideas or framework recommended, thank you very much!</p>
",https://stackoverflow.com/questions/46617108/how-to-write-ios-unit-test-case-with-python,"['python', 'ios', 'unit-testing']",343,FALSE,0,0
How To Java Unit Test a Complex Class,"<p>I'm experiencing a difficult time on figuring out how to approach a problem with unit testing. I have little to no 'unit testing' experience. I am trying to change the <strong>classUnderTest</strong> only if absolutely necessary with minimal changes.</p>

<p>I am using <a href=""http://junit.org/junit4/"" rel=""nofollow noreferrer"">JUnit 4</a>, and I am willing to try to use <a href=""http://site.mockito.org/"" rel=""nofollow noreferrer"">Mockito</a>, <a href=""http://jmockit.org/"" rel=""nofollow noreferrer"">JMockit</a> or any other libraries that would help with efficient and effectively unit testing. I am using <strong>JDBC</strong> for the database.</p>

<h1><strong>Problem:</strong></h1>

<p>Within the <strong>classUnderTest</strong>, I'm accessing a <em>static</em> database.</p>

<pre><code>SpecializedDao specializedDao = SpecializedDao.getSpecializedDao();
ObjectX objectResult = specializedDao.currentObjectXByTimestamp(x, x, x, x, x, x);
</code></pre>

<p>and I am trying to use do unit test cases with a valid config, and an invalid config. What is the correct way to approach this problem.</p>

<p>Some <em>possible</em> solutions I have researched are:</p>

<ol>
<li>Somehow passing in, or 'injecting' a fake <em>ObjectXResult</em> of class <em>ObjectX</em></li>
<li>Mock a database (if even possible with static db reference, use separate unit-test servlet that references a fake SpecializedDao class?)</li>
<li>Use <a href=""http://site.mockito.org/"" rel=""nofollow noreferrer"">Mockito</a> with <em>injectMocks</em>, <em>spy</em>, <em>when(methodcallwithparameters) thenReturn result</em>, or some other implementation <a href=""http://site.mockito.org/"" rel=""nofollow noreferrer"">Mockito</a> provides.</li>
<li>Open to any other solution.</li>
</ol>

<h1><strong>Problem:</strong></h1>

<p>Within the <strong>classUnderTest</strong>, I am using another complex processing <strong>class2</strong> that does a lot of the work like so:</p>

<pre><code>result = class2.execute(x, x, x, x, x, x);
</code></pre>

<p><strong>class2</strong> does processing stuff and returns a result ENUM or some exceptions. How do I handle this with keeping the <em>scope</em> of this specific Unit Test on <strong>classUnderTest</strong>. <strong>class2</strong> accesses the database, and does a lot of the work which is why it is its own class but I think the final three test cases are dependent upon the processing to thoroughly test <strong>classUnderTest</strong>.</p>

<p>Thanks for bearing with me, I tried to make the question with as much clarity as possible.</p>
",https://stackoverflow.com/questions/46492468/how-to-java-unit-test-a-complex-class,"['java', 'unit-testing', 'junit', 'mocking', 'junit4']",3406,TRUE,2,6
Qt-Designer costumn widgets and relative path,"<p>I am trying to create unit testing for my project but struggle with costumn widgets.
While compiling the test unit, <code>ui_mainwindow.h</code> cannot find my <code>widget.h</code> anymore.
My project structure looks like this:</p>

<pre><code>Project
    scr
        scr.pro
        scr.pri
        mainwindow.ui
        CostumnWidgets
            widget.h
    test
        test.pro
</code></pre>

<p>In Qt-Designer i refer to my widget with <code>./CostumnWidgets/widget.h</code></p>

<p>scr.pri</p>

<pre><code>QT       += core gui
TEMPLATE = app
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

SOURCES += $$PWD/mainwindow.cpp \
    $$PWD/CostumnWidgets/widget.cpp

HEADERS  += $$PWD/mainwindow.h \
    $$PWD/CostumnWidgets/widget.h

FORMS    += $$PWD/mainwindow.ui
</code></pre>

<p>test.pro</p>

<pre><code>TARGET = Test
include(../scr/scr.pri)

QT += widgets
QT += testlib

SOURCES += $$PWD/test.cpp
</code></pre>

<p>How can I solve that without making a copy of my CostumnWidget-folder to my test directory?
Thank you!</p>
",https://stackoverflow.com/questions/43669198/qt-designer-costumn-widgets-and-relative-path,"['qt', 'widget', 'qt-designer']",481,TRUE,0,1
Error running testAction on CakePHP 2.4.6 error Undefined index: REMOTE_ADDR,"<p>I am attempting to write tests for CakePHP 2.4.6 controllers. I am following the documentation which suggests that I can use testAction to product output to test against.</p>

<pre><code>&lt;?php
App::uses('UsersController', 'Controller');      

class UsersControllerTest extends ControllerTestCase {
    public $fixtures = array(
      'app.user',
    );

    public function testIndex() {
      $result = $this-&gt;testAction('/users/view/10');
      debug($result);
    }
  }
</code></pre>

<p>When I run this test I receive the following error message:</p>

<pre><code>UsersControllerTest::testIndex
Undefined index: REMOTE_ADDR
</code></pre>

<p>Please can you advise what I can do to initialise the controller and gain access to its methods for unit testing.</p>
",https://stackoverflow.com/questions/45419421/error-running-testaction-on-cakephp-2-4-6-error-undefined-index-remote-addr,"['unit-testing', 'cakephp', 'cakephp-2.0']",82,TRUE,0,1
How to test the whole process from UI layer to database entry in Angular using unit testing or other testing?,"<p>Here I am checking the validation and input values which was send through the form when I clicked the submit button. Up to this my testing is fine but how to send the input values to the database to check whether the whole process is working properly or not. Is it possible the to do with unit testing? Or any other testing? </p>



<pre class=""lang-ts prettyprint-override""><code>describe('CategoryAddComponent', () =&gt; {

    let fixture: ComponentFixture&lt;CategoryAddComponent&gt;;
    let component: CategoryAddComponent;
    let categoryService: CategoryService;
    let de: DebugElement;
    let el: HTMLElement;

    beforeEach(async(() =&gt; {

        TestBed.configureTestingModule({
            imports: [ReactiveFormsModule, FormsModule, SharedModule, UiSwitchModule, AlertModule.forRoot(), NgaModule, HttpModule, RouterModule.forRoot([]), CookieModule.forRoot()],

            declarations: [CategoryAddComponent],
            //providers:    [ {provide: CustomerService, useValue: customerServiceStub }, CustomerService,CustomerModelService,AppState,BaThemeConfigProvider ]
            providers: [{ provide: APP_BASE_HREF, useValue: '/' }, CategoryService, CategoryModelService, AppState, BaThemeConfigProvider],
        })
            .compileComponents();

    }));

    beforeEach(() =&gt; {

        fixture = TestBed.createComponent(CategoryAddComponent);
        component = fixture.componentInstance;
        de = fixture.debugElement.query(By.css('h1'));
        el = de.nativeElement;
        categoryService = TestBed.get(CategoryService);

        component.ngOnInit();
        fixture.detectChanges();

    });


    it('form invalid when empty', () =&gt; {
        expect(component.form.valid).toBeFalsy();
    });

    it('submitting the form by clicking the button', () =&gt; {

        expect(component.form.valid).toBeFalsy();
        component.form.controls['code'].setValue('1234');

        expect(component.form.controls['code'].valid).toBeTruthy();

        spyOn(component, 'onSubmit');
        de = fixture.debugElement.query(By.css('#buto'));
        el = de.nativeElement;

        el.click();
        fixture.detectChanges();

        expect(component.onSubmit).toHaveBeenCalledWith({
            code: '1234',
            name:new Object(),
            status: true,
            remarks: ''
        });

    });

    it('dom ', () =&gt; {
        fixture.detectChanges();
        expect(el.textContent).toContain('Add Category');
    });


 });
</code></pre>
",https://stackoverflow.com/questions/45854256/how-to-test-the-whole-process-from-ui-layer-to-database-entry-in-angular-using-u,"['angular', 'unit-testing']",80,FALSE,0,0
React native: Warning for Shallow renderer,"<p>I am using JEST framework for unit testing. I am using Shallow from enzyme for DOM testing. I am getting the following warning after running jest command. </p>

<p>PASS <strong>tests</strong>/CheckboxWithLabel-test.js</p>

<p>● Console
    console.error node_modules/fbjs/lib/warning.js:36
      Warning: Shallow renderer has been moved to react-test-renderer/shallow. Update references to remove this warning.</p>

<p>My test is</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>import React from 'react';
import {shallow} from 'enzyme';
import CheckboxWithLabel from '../app/Component8/CheckboxWithLabel';

test('CheckboxWithLabel changes the text after click', () =&gt; {
  // Render a checkbox with label in the document
  const checkbox = shallow(
    &lt;CheckboxWithLabel labelOn=""On"" labelOff=""Off"" /&gt;
  );
    
  expect(checkbox.text()).toEqual('Off');

  checkbox.find('input').simulate('change');

  expect(checkbox.text()).toEqual('On');
});</code></pre>
</div>
</div>
</p>

<p>My package.json
<div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-css lang-css prettyprint-override""><code>{
  ""name"": ""myapp"",
  ""version"": ""0.0.1"",
  ""private"": true,
  ""scripts"": {
    ""start"": ""node node_modules/react-native/local-cli/cli.js start"",
    ""test"": ""jest""
  },
  ""dependencies"": {
    ""linkify-it"": ""^2.0.3"",
    ""prop-types"": ""^15.5.8"",
    ""react"": ""16.0.0-alpha.6"",
    ""react-dom"": ""^15.4.2"",
    ""react-native"": ""0.43.1""
  },
  ""devDependencies"": {
    ""babel-jest"": ""19.0.0"",
    ""babel-preset-es2015"": ""^6.24.0"",
    ""babel-preset-react-native"": ""1.9.1"",
    ""enzyme"": ""^2.8.2"",
    ""jest"": ""19.0.2"",
    ""react-addons-test-utils"": ""~15.1.0"",
    ""react-test-renderer"": ""16.0.0-alpha.6""
  },
  ""jest"": {
    ""preset"": ""react-native""
  }
}</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/43494661/react-native-warning-for-shallow-renderer,"['react-native', 'jestjs']",707,TRUE,0,1
System.Xml.XmlException occurs with dotnet test,"<p>Using .NET Core's unit testing functionality and the MSTest Framework and Adapter, I am trying to run this simple unit test:</p>

<pre><code>using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TESTFull
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            Assert.AreEqual(1, 2);
        }
    }
}
</code></pre>

<p>However even with the scaffolded dependencies:</p>

<pre><code>&lt;Project Sdk=""Microsoft.NET.Sdk""&gt;

  &lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;netcoreapp1.1&lt;/TargetFramework&gt;
  &lt;/PropertyGroup&gt;

  &lt;ItemGroup&gt;
    &lt;PackageReference Include=""Microsoft.NET.Test.Sdk"" Version=""15.0.0"" /&gt;
    &lt;PackageReference Include=""MSTest.TestAdapter"" Version=""1.1.11"" /&gt;
    &lt;PackageReference Include=""MSTest.TestFramework"" Version=""1.1.11"" /&gt;
  &lt;/ItemGroup&gt;
&lt;/Project&gt;
</code></pre>

<p>I get this following error when using the <code>dotnet test</code> command:</p>

<pre><code>Test run for F:\Onedrive\Uni\2-1\Dev Project 1 - Tools &amp; Practices\RESTFull\TESTFull\bin\Debug\netcoreapp1.1\TESTFull.dll(.NETCoreApp,Version=v1.1)
Microsoft (R) Test Execution Command Line Tool Version 15.0.0.0
Copyright (c) Microsoft Corporation.  All rights reserved.

Starting test execution, please wait...

Unhandled Exception: System.Xml.XmlException: An error occurred while parsing EntityName. Line 1, position 44.
   at System.Xml.XmlTextReaderImpl.Throw(Exception e)
   at System.Xml.XmlTextReaderImpl.Throw(String res, Int32 lineNo, Int32 linePos)
   at System.Xml.XmlTextReaderImpl.HandleEntityReference(Boolean isInAttributeValue, EntityExpandType expandType, Int32&amp; charRefEndPos)
   at System.Xml.XmlTextReaderImpl.ParseText(Int32&amp; startPos, Int32&amp; endPos, Int32&amp; outOrChars)
   at System.Xml.XmlTextReaderImpl.FinishPartialValue()
   at System.Xml.XmlTextReaderImpl.get_Value()
   at System.Xml.XmlLoader.LoadNode(Boolean skipOverWhitespace)
   at System.Xml.XmlLoader.ParsePartialContent(XmlNode parentNode, String innerxmltext, XmlNodeType nt)
   at System.Xml.XmlLoader.LoadInnerXmlElement(XmlElement node, String innerxmltext)
   at System.Xml.XmlElement.set_InnerXml(String value)
   at Microsoft.VisualStudio.TestPlatform.Utilities.XmlUtilities.AppendOrModifyChild(XPathNavigator parentNavigator, String nodeXPath, String nodeName, String innerXml)
   at Microsoft.VisualStudio.TestPlatform.Utilities.InferRunSettingsHelper.UpdateRunConfiguration(XPathNavigator navigator, Architecture effectivePlatform, Framework effectiveFramework, String resultsDirectory)
   at Microsoft.VisualStudio.TestPlatform.Utilities.InferRunSettingsHelper.UpdateRunSettingsWithUserProvidedSwitches(XPathNavigator runSettingsNavigator, Architecture architecture, Framework framework, String resultsDirectory)
   at Microsoft.VisualStudio.TestPlatform.CommandLine.Processors.Utilities.RunSettingsUtilities.GetEffectiveRunSettings(String runSettings, CommandLineOptions commandLineOptions)
   at Microsoft.VisualStudio.TestPlatform.CommandLine.Processors.Utilities.RunSettingsUtilities.GetRunSettings(IRunSettingsProvider runSettingsProvider, CommandLineOptions commandlineOptions)
   at Microsoft.VisualStudio.TestPlatform.CommandLine.Processors.RunTestsArgumentExecutor.RunTests(IEnumerable`1 sources)
   at Microsoft.VisualStudio.TestPlatform.CommandLine.Processors.RunTestsArgumentExecutor.Execute()
   at Microsoft.VisualStudio.TestPlatform.CommandLine.Executor.ExecuteArgumentProcessor(IArgumentProcessor processor, Int32&amp; exitCode)
   at Microsoft.VisualStudio.TestPlatform.CommandLine.Executor.Execute(String[] args)
   at Microsoft.VisualStudio.TestPlatform.CommandLine.Program.Main(String[] args)
</code></pre>

<p>Note that this error occurs with an empty <code>TestMethod1()</code> and also when using the built in xUnit project template. I am using .NET Core 1.1.</p>
",https://stackoverflow.com/questions/43674282/system-xml-xmlexception-occurs-with-dotnet-test,"['c#', '.net', 'unit-testing', '.net-core', 'xunit']",309,FALSE,0,2
Testing List&lt;byte[]&gt; for equality,"<p>I'm using TestNG for unit testing and now I have a method to test which return <code>List&lt;byte[]&gt;</code>. Here is how my test looks like now:</p>

<pre><code>public List&lt;byte[]&gt; methodToTest(){
   //...
}

@Test
public void test(){
    List&lt;byte[]&gt; expected;
    //...
    Assert.assertEquals(methodToTest(), expected); //now fails
}
</code></pre>

<p>The question is if it possible to tell TestNG to perform <code>List</code> content comparison (<code>byte[]</code> in my case) with not just <code>equals</code>, but with <code>Arrays.equals</code>? </p>

<p>Or I will have to iterate through the <code>List</code> and perform comparison of every element myself?</p>
",https://stackoverflow.com/questions/44086152/testing-listbyte-for-equality,"['java', 'testing', 'testng']",1401,TRUE,0,3
Spock JUnit testing: NullPointer cannot invoke method persist() on null object,"<p>Im trying to do some unit testing on my SpringBootApplication. When i attempt to test the class ""UserRepository"" the it keeps telling me that its null. Im not sure whats going on.</p>

<pre><code>Running com.bestech.spec.SpockTestSpec
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.047 sec &lt;&lt;&lt; FAILURE! - in com.bestech.spec.SpockTestSpec
find by email(com.bestech.spec.SpockTestSpec)  Time elapsed: 0.047 sec  &lt;&lt;&lt; ERROR!
java.lang.NullPointerException: Cannot invoke method persist() on null object
    at com.bestech.spec.SpockTestSpec.find by email(SpockTestSpec.groovy:28)


Results :

Tests in error: 
  SpockTestSpec.find by email:28 NullPointer Cannot invoke method persist() on n...

Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
</code></pre>

<p>Here is my test class</p>

<pre><code>@DataJpaTest
class SpockTestSpec extends Specification {

    @Autowired
    TestEntityManager em 

    @Autowired
    UserRepository userRepository

    def ""find by email""() {
        given: ""a user""
        User user = new User(""Admin"",""9999"",""admin@admin.com"")
        em.persist(user)
        em.flush()
        when:""that user is then found by email""
        User found = userRepository.findByEmail(user.email)
        then: ""found equals user""
        found == user
    }
}
</code></pre>

<p>here is my pom.xml</p>

<pre><code>    &lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;project xmlns=""http://maven.apache.org/POM/4.0.0"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
    xsi:schemaLocation=""http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd""&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;

    &lt;groupId&gt;com.bestech&lt;/groupId&gt;
    &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
    &lt;parent&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
        &lt;version&gt;1.5.6.RELEASE&lt;/version&gt;
    &lt;/parent&gt;

    &lt;properties&gt;
        &lt;java.version&gt;1.8&lt;/java.version&gt;
    &lt;/properties&gt;

    &lt;dependencies&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.plugin&lt;/groupId&gt;
            &lt;artifactId&gt;spring-plugin-core&lt;/artifactId&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.hateoas&lt;/groupId&gt;
            &lt;artifactId&gt;spring-hateoas&lt;/artifactId&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.security.oauth&lt;/groupId&gt;
            &lt;artifactId&gt;spring-security-oauth2&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.plugin&lt;/groupId&gt;
            &lt;artifactId&gt;spring-plugin-core&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-orm&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.h2database&lt;/groupId&gt;
            &lt;artifactId&gt;h2&lt;/artifactId&gt;
        &lt;/dependency&gt;

        &lt;!-- Test only dependencies --&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.jayway.jsonpath&lt;/groupId&gt;
            &lt;artifactId&gt;json-path&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;mysql&lt;/groupId&gt;
            &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
            &lt;scope&gt;runtime&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-data-rest&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.jsoup&lt;/groupId&gt;
            &lt;artifactId&gt;jsoup&lt;/artifactId&gt;
            &lt;version&gt;1.10.2&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.mindrot&lt;/groupId&gt;
            &lt;artifactId&gt;jbcrypt&lt;/artifactId&gt;
            &lt;version&gt;0.4&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.h2database&lt;/groupId&gt;
            &lt;artifactId&gt;h2&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;!-- Servlet --&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;javax.servlet&lt;/groupId&gt;
            &lt;artifactId&gt;javax.servlet-api&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;!-- Hibernate --&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
            &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
            &lt;artifactId&gt;hibernate-entitymanager&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;!-- Javassist --&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.javassist&lt;/groupId&gt;
            &lt;artifactId&gt;javassist&lt;/artifactId&gt;
            &lt;version&gt;3.20.0-GA&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;!-- Spock --&gt;
        &lt;dependency&gt; &lt;!-- enables mocking of classes (in addition to interfaces) --&gt;
            &lt;groupId&gt;net.bytebuddy&lt;/groupId&gt;
            &lt;artifactId&gt;byte-buddy&lt;/artifactId&gt;
            &lt;version&gt;1.6.5&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;cglib&lt;/groupId&gt;
            &lt;artifactId&gt;cglib&lt;/artifactId&gt;
            &lt;version&gt;3.1&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt; &lt;!-- enables mocking of classes without default constructor (together with 
                CGLIB) --&gt;
            &lt;groupId&gt;org.objenesis&lt;/groupId&gt;
            &lt;artifactId&gt;objenesis&lt;/artifactId&gt;
            &lt;version&gt;2.5.1&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.spockframework&lt;/groupId&gt;
            &lt;artifactId&gt;spock-core&lt;/artifactId&gt;
            &lt;version&gt;1.1-groovy-2.4&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.spockframework&lt;/groupId&gt;
            &lt;artifactId&gt;spock-spring&lt;/artifactId&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;
    &lt;build&gt;
        &lt;plugins&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.codehaus.gmavenplus&lt;/groupId&gt;
                &lt;artifactId&gt;gmavenplus-plugin&lt;/artifactId&gt;
                &lt;version&gt;1.0&lt;/version&gt;
                &lt;executions&gt;
                    &lt;execution&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;generateStubs&lt;/goal&gt;
                            &lt;goal&gt;compile&lt;/goal&gt;
                            &lt;goal&gt;testGenerateStubs&lt;/goal&gt;
                            &lt;goal&gt;testCompile&lt;/goal&gt;
                        &lt;/goals&gt;
                    &lt;/execution&gt;
                &lt;/executions&gt;
                &lt;dependencies&gt;
                    &lt;dependency&gt;
                        &lt;groupId&gt;org.codehaus.groovy&lt;/groupId&gt;
                        &lt;artifactId&gt;groovy-all&lt;/artifactId&gt;
                        &lt;version&gt;2.4.4&lt;/version&gt;
                        &lt;scope&gt;runtime&lt;/scope&gt;
                    &lt;/dependency&gt;
                &lt;/dependencies&gt;
            &lt;/plugin&gt;
            &lt;!-- Optional --&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
                &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;
                &lt;version&gt;2.16&lt;/version&gt;
                &lt;configuration&gt;
                    &lt;parallel&gt;methods&lt;/parallel&gt;
                    &lt;threadCount&gt;5&lt;/threadCount&gt;
                    &lt;includes&gt;
                        &lt;include&gt;**/*Test.*&lt;/include&gt;
                        &lt;include&gt;**/*Spec.*&lt;/include&gt;
                    &lt;/includes&gt;
                    &lt;excludes&gt;
                        &lt;exclude&gt;**/Abstract*.java&lt;/exclude&gt;
                    &lt;/excludes&gt;
                &lt;/configuration&gt;
            &lt;/plugin&gt;
        &lt;/plugins&gt;
    &lt;/build&gt;

    &lt;repositories&gt;
        &lt;repository&gt;
            &lt;id&gt;spring-releases&lt;/id&gt;
            &lt;url&gt;https://repo.spring.io/libs-release&lt;/url&gt;
        &lt;/repository&gt;
    &lt;/repositories&gt;

    &lt;pluginRepositories&gt;
        &lt;pluginRepository&gt;
            &lt;id&gt;spring-releases&lt;/id&gt;
            &lt;url&gt;https://repo.spring.io/libs-release&lt;/url&gt;
        &lt;/pluginRepository&gt;
    &lt;/pluginRepositories&gt;

    &lt;artifactId&gt;praze&lt;/artifactId&gt;
&lt;/project&gt;
</code></pre>

<p>Im not sure exactly why its telling me userRepository is null, any help is appreciated. This is my first time using spock</p>
",https://stackoverflow.com/questions/47480061/spock-junit-testing-nullpointer-cannot-invoke-method-persist-on-null-object,"['spring', 'spock']",1199,FALSE,0,0
"Symfony3 : phpunit run from command line returns “&#39;phpunit&#39; is not recognized as an internal or external command, operable program or batch file.”","<p>I want to proceed to unit testing on my Symfony3.2 project.</p>

<p>But 'phpunit' command is not working : when I run phpunit, it returns <strong>“'phpunit' is not recognized as an internal or external command, operable program or batch file.”</strong></p>

<p>Though, everything seems to be correctly set up. I searched the internet and didn't find anything.
So, could somebody help me please ?</p>
",https://stackoverflow.com/questions/44004185/symfony3-phpunit-run-from-command-line-returns-phpunit-is-not-recognized-as,"['php', 'symfony', 'phpunit']",910,TRUE,0,3
How to create browser support badges like the ones used in Github?,"<p><a href=""https://i.stack.imgur.com/YPFRe.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/YPFRe.png"" alt=""enter image description here""></a></p>

<p>I have used ava.js to do unit testing, and found that I can generate test coverage report in json or html format through nyc.</p>

<p>For browser support I found <a href=""http://jscc.info/"" rel=""nofollow noreferrer"">http://jscc.info/</a>, it shows detailed browser support for APIs I used, but lacking a global browser support.</p>

<p>Are there any libraries that can automatically run browser support test and generate such badges?
Thanks!</p>
",https://stackoverflow.com/questions/42777092/how-to-create-browser-support-badges-like-the-ones-used-in-github,"['javascript', 'node.js']",262,TRUE,-1,1
$uibModal.open is not a function in karma (AngularJS Factory),"<p>I am trying to test a function that opens a <code>$uibmodal</code>. This is my factory function.</p>

<pre><code>confirmationMessage: function (message) {
    var modalInstance = $uibModal.open({
      templateUrl: 'views/templates/utilsTemplates/confirmationMessage.html',
      backdrop: 'static',
      controller: function () {
        var messageCtrlVM = this;
        // message to show
        messageCtrlVM.message = message;
        // when yes_button is pressed
        messageCtrlVM.yesPress = function () {
          modalInstance.close(true);
        };
        // when no_button is pressed
        messageCtrlVM.noPress = function () {
          modalInstance.close();
        };
      },
      controllerAs: ""messageCtrlVM""
    });
    return modalInstance.result;
  },
</code></pre>

<p>In its unit testing file, I am first adding provider for it like so.</p>

<pre><code>beforeEach(angular.mock.module('ui.bootstrap'));

beforeEach(function () {
    module(function ($provide) {
      $provide.value('$uibModal', function (value) {
        return value;
      });
    });
  });
</code></pre>

<p>After that I am injecting <code>open</code>, <code>dismiss</code> and <code>close</code> functions with <code>beforeEach</code> like so.</p>

<pre><code>beforeEach(inject(function (_utilsFactory_, _$httpBackend_, _$filter_) {
  utilsService = _utilsFactory_;
  $httpBackend = _$httpBackend_;
  filter = _$filter_;
  uibModal = {
    open: function () {},
    dismiss: function () {},
    close: function () {}
  };

}));
</code></pre>

<p>Finally I am trying to run my unit test by calling factory function.</p>

<pre><code>it('should show a confirmation message', function () {
  var spy = spyOn(uibModal, ""open"").and.callFake(function () {
    return {
      result: {
        then: function () {}
      }
    };
  });
  utilsService.confirmationMessage(""Are you Sure?"");
  expect(spy).toHaveBeenCalled();

});
</code></pre>

<p>It gives me error that <strong><code>$uibModal.open</code> is not a function</strong>.</p>
",https://stackoverflow.com/questions/43202824/uibmodal-open-is-not-a-function-in-karma-angularjs-factory,"['angularjs', 'angular-ui-bootstrap', 'karma-runner']",688,TRUE,0,1
Python unittesting how to test while having db_session.query on my function?,"<p>I am new to python and i'm trying unit test over my python project for a function </p>

<pre><code>def getFundPosition(self, enterprise_id=None, since=None, till=datetime.datetime.today()):
    """"""

    :param enterprise_id:
    :param since:
    :param till:
    :return:
    """"""
bank = self.db_session.query(AccountGroup).filter(
        AccountGroup.enterprise_id == enterprise_id, AccountGroup.name == AccountGroup.BANK_GROUP_NAME).first()
    cash = self.db_session.query(AccountGroup).filter(
        AccountGroup.enterprise_id == enterprise_id, AccountGroup.name == AccountGroup.CASH_GROUP_NAME).first()
    fund = float(
        bank.getBalance(since, till, approved_only=True) + cash.getBalance(since, till, approved_only=True))
</code></pre>

<p>on the other hand testing code like to be below</p>

<pre><code>class AccountsTestCase(TestCase):
    def setUp(self):
        #every test needs a client
    def test_dashboard(self):
        response = AccountsDAO().getFundPosition(121,'2016-01-01','2017-12-01')
</code></pre>

<p>It throws error as below</p>

<pre><code>AttributeError: 'NoneType' object has no attribute 'getBalance'
</code></pre>

<p>I want to know is that im doing is correct way to test or it will not execute self.db_session.query under unit testing case scenario</p>

<p>Pls help me on this</p>
",https://stackoverflow.com/questions/47767298/python-unittesting-how-to-test-while-having-db-session-query-on-my-function,"['python-2.7', 'python-unittest']",20,FALSE,0,0
Load all Components and Providers from one source for Angular Unit Tests,"<p>I have been learning Angular 2 unit testing for the last month or so and have come across a tedious process that I am trying to figure out how to get around. This tedious process has to do with importing every provider that a component uses for a unit test. I was wondering if there is a way to import a single file (maybe the app.module.ts file) that contains all the Components and Providers for my app and then I can pick and choose what Components and Providers I need. </p>

<p>For reference, this is what I am currently doing in my Angular unit tests:</p>

<pre class=""lang-ts prettyprint-override""><code>// Angular and Ionic Dependencies
import { async, TestBed, tick, fakeAsync } from '@angular/core/testing';
import { MockBackend } from '@angular/http/testing';
import { SimpleChange } from '@angular/core';
import { IonicModule, Platform, NavController } from 'ionic-angular';
import { Storage }                              from '@ionic/storage';
import { Observable } from 'rxjs/Rx';
import {
    BaseRequestOptions, ConnectionBackend, RequestOptions, Response,
    ResponseOptions, Http, XHRBackend, HttpModule, RequestMethod
} from '@angular/http';

// My App Dependencies
import { ComponentToTest } from '/location/component-to-test';
import { ComponentProviderOne } from '/location/component-provider-one';
import { ComponentProviderTwo } from '/locaiton/component-provider-two';
import { ComponentProviderThree } from '/location/component-provider-three';

describe('ComponentToTest', () =&gt; {
  let fixture;
  let component;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ComponentToTest], // declare the test component
        imports: [
          IonicModule.forRoot(ComponentToTest)
        ],
        providers: [
          ComponentProviderOne,
          ComponentProviderTwo,
          ComponentProviderThree,
          { provide: XHRBackend, useClass: MockBackend},
          MockBackend,
          BaseRequestOptions,
          {
            provide: Http,
            deps: [MockBackend, BaseRequestOptions],
            useFactory:
              (backend: XHRBackend, defaultOptions: BaseRequestOptions) =&gt; {
                  return new Http(backend, defaultOptions);
              }
          }
        ]
    });
  });
}
</code></pre>

<p>I would love to avoid having to use all those imports for all ComponentProviderX. </p>

<p>Another reference I want to add is, in AngularJS I was able to load all my apps Components and Services the following way:</p>

<pre class=""lang-js prettyprint-override""><code>describe('componentToTest', function() {
  var $httpBackend,
      $q,
      $rootScope,
      componentToTest,
      componentServiceOne,
      componentServiceTwo,
      componentServiceThree;

  // Load the Angular 1 module file that has 
  // a reference of all the apps Components and Services
  beforeEach(module('angular1ModuleFile'));

  beforeEach(inject(function(
    _$httpBackend_,
    _$q_,
    _$rootScope_,
    _componentToTest_,
    _componentServiceOne_,
    _componentServiceTwo_,
    _componentServiceThree_

  ) {
    $httpBackend = _$httpBackend_;
    $q = _$q_;
    $rootScope = _$rootScope_;

    componentToTest = _componentToTest_;
    componentServiceOne = _componentServiceOne_;
    componentServiceTwo = _componentServiceTwo_;
    componentServiceThree = _componentServiceThree_;
  }));
});
</code></pre>

<p>In conclusion, is it possible to do something similar in Angular unit testing? That being, can I have a single import (like the angular1ModuleFile) that loads all my apps Components and Providers for my Angular unit tests?</p>
",https://stackoverflow.com/questions/45617726/load-all-components-and-providers-from-one-source-for-angular-unit-tests,"['angular', 'unit-testing', 'jasmine', 'angular2-testing']",623,FALSE,3,1
Notification.permission is set to denied and not present in blocked,"<p>On my localhost in chrome during unit testing of Notification permission, I have closed the browser native notification permission box by clicking on (x) </p>

<p><a href=""https://i.stack.imgur.com/ROXDf.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ROXDf.png"" alt=""enter image description here""></a></p>

<p>after that I am not able to change / remove it to default from browser Setting > Content Settings > Notifications</p>

<p><strong>localhost</strong> is not visible in blocked list, but when I check on console in chrome <strong>Notification.permission</strong> value is set to ""denied""</p>

<p>Please help!</p>

<p><a href=""https://i.stack.imgur.com/5ozNN.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/5ozNN.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/46783062/notification-permission-is-set-to-denied-and-not-present-in-blocked,"['push-notification', 'web-notifications']",2032,TRUE,2,1
How do I unit test (with JUnit or mockito) recyclerview item clicks,"<p>I am currently trying to unit test recyclerview addonitemclick listner, with either junit or mockito. here's my code:</p>

<pre><code>private void mypicadapter(TreeMap&lt;Integer, List&lt;Photos&gt;&gt; photosMap) {
    List&lt;PhotoListItem&gt; mItems = new ArrayList&lt;&gt;();

    for (Integer albumId : photosMap.keySet()) {
        ListHeader header = new ListHeader();
        header.setAlbumId(albumId);
        mItems.add(header);
        for (Photos photo : photosMap.get(albumId)) {
            mItems.add(photo);
        }


        pAdapter = new PhotoViewerListAdapter(MainActivity.this, mItems);
        mRecyclerView.setAdapter(pAdapter);
        //  set 5 photos per row if List item type --&gt; header , else fill row with header.
        GridLayoutManager layoutManager = new GridLayoutManager(this, 5);
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (mRecyclerView.getAdapter().getItemViewType(position) == PhotoListItem.HEADER_TYPE)
                    // return the number of columns so the group header takes a whole row
                    return 5;
                // normal child item takes up 1 cell
                return 1;
            }
        });
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.addOnItemTouchListener(new PhotoItemClickListener(MainActivity.this,
                new PhotoItemClickListener.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        if (pAdapter.getItemViewType(position) == PhotoListItem.HEADER_TYPE) return;

                        Photos photo = pAdapter.getItem(position);
                        Intent intent = new Intent(MainActivity.this, DetailViewActivity.class);
                        intent.putExtra(PHOTO_DETAILS, photo);
                        ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(
                                MainActivity.this,

                                new Pair&lt;&gt;(view.findViewById(R.id.photoItem),
                                        getString(R.string.transition_name_photo))
                        );
                        ActivityCompat.startActivity(MainActivity.this, intent, options.toBundle());
                    }
                }));
    }
</code></pre>

<p>Is there a way I can unit test : addOnItemTouchListener or OnItemClickListener/onitemclick ,mock the functionality etc. I am pretty new to unit testing and been looking up online at a couple of tutorials and pretty confused. Any step by step tutorial for testing functions or any suggestions would help.Also, any other possible unit testable scenarios in this function would be helpful. Thanks!</p>
",https://stackoverflow.com/questions/42188261/how-do-i-unit-test-with-junit-or-mockito-recyclerview-item-clicks,"['android', 'android-recyclerview', 'mocking', 'android-testing', 'android-junit']",9147,TRUE,14,2
How to add enviroment specific test in travis CI?,"<p>I am developing some project and i am using travis CI for unit testing and I want that using environment variable I can use phantomjs in case of travis (using phantomjs as travis won't support gui) and I can use firefox/chrome in case of desktop usage.<br>
How can i do this in python? I tried to google but i am confused what should i search.</p>
",https://stackoverflow.com/questions/46362802/how-to-add-enviroment-specific-test-in-travis-ci,"['python', 'python-3.x', 'travis-ci']",28,FALSE,2,0
testing if button is disabled,"<p>I have a simple form with 2 input boxes and a submit button.</p>

<pre><code>&lt;div class=""login jumbotron center-block""&gt;
  &lt;h1&gt;Login&lt;/h1&gt;

  &lt;form [formGroup]=""loginForm"" (ngSubmit)=""onSubmit()""&gt;

    &lt;div class=""form-group""&gt;
      &lt;label for=""username""&gt;Username&lt;/label&gt;
      &lt;input type=""text"" class=""form-control"" formControlName=""username"" name=""username"" placeholder=""Username"" required&gt;
      &lt;div *ngIf=""formErrors.username"" class=""alert alert-danger""&gt; {{ formErrors.username }}  &lt;/div&gt;
    &lt;/div&gt;
    &lt;div class=""form-group""&gt;
      &lt;label for=""password""&gt;Password&lt;/label&gt;
      &lt;input type=""password"" class=""form-control"" formControlName=""password"" name=""password"" placeholder=""Password"" required&gt;
      &lt;div *ngIf=""formErrors.password"" class=""alert alert-danger""&gt; {{ formErrors.password }}  &lt;/div&gt;
    &lt;/div&gt;

    &lt;button type=""submit"" class=""btn btn-default"" [disabled]=""!loginForm.valid"" &gt;Submit&lt;/button&gt;
  &lt;/form&gt;
&lt;/div&gt;
</code></pre>

<p>Now when the 2 input boxes are empty , the submit button should be disabled.
Visually it all works as expected, but I'd like to cover this in my unit testing as well. </p>

<p>The below  is shortened example as how I tried checking whether the button element is disabled or not. However it seems the <code>page.submitBtnEl.disabled</code> attribute is always true for some reason.</p>

<pre><code>let InvalidUser = new User({
  username: '',
  password: ''
});

it('form validity should be False when entering invalid credentials', 
fakeAsync(() =&gt; {
    updateForm( InvalidUser );
    expect( page.submitBtnEl.disabled ).toBeTruthy(""submit button is disabled"");
    expect(comp.loginForm.valid).toBeFalsy();
  })); 
</code></pre>
",https://stackoverflow.com/questions/41829113/testing-if-button-is-disabled,"['unit-testing', 'angular', 'karma-jasmine']",9549,FALSE,8,1
Mock an Async Task method returns null using C# and Xamarin,"<p>I've read and test all these answers (<a href=""https://stackoverflow.com/questions/21253523/setup-async-task-callback-in-moq-framework"">this</a>, <a href=""https://stackoverflow.com/questions/20859639/using-moq-to-mock-an-asynchronous-method-for-a-unit-test"">this</a> and <a href=""https://stackoverflow.com/questions/28581322/moq-with-task-await"">this</a>) but didn't help (also it's not my first use of mocking in such a situation, but this case is rare for me).</p>

<p>I'm using <code>moq</code> and <code>xunit</code> for my unit testing purpose. In testing <code>ViewModel</code> I mocked <code>service</code> and <code>page</code> and passed them to it, everything is working but not <code>page.CountDialog</code> that returns null, this is my code:</p>

<p>Page.cs:</p>

<pre><code>public interface IPage
{
    Task&lt;PromptResult&gt; CountDialog(decimal previousCount);
}
</code></pre>

<p>PageViewModel:</p>

<pre><code>public class PageViewModel : ViewModelBase&lt;ObservableRangeCollection&lt;Detail&gt;&gt;
{
    private readonly IPage _page;
    private readonly IService _service;
    private ICommand _editItemCommand;

    public PageViewModel(IService service, IPage page)
    {
        _service = service;
        _page = page;
        Data = new ObservableRangeCollection&lt;Detail&gt;();
    }

    public ICommand EditItemCommand
    {
        get =&gt; _editItemCommand ??
               (_editItemCommand = new Command&lt;Detail&gt;(async (o) =&gt; { await EditItem(o); }));
        set =&gt; _editItemCommand = value;
    }

    public async Task EditItem(Detail detail)
    {
        if (detail == null) return;
        try
        {
            var result = await _page.CountDialog(detail.Count); // It should return PromptResult (from UserDialogs lib) but every time is null, in normal running app, it works and is Not null
            if (result == null) return; //in test is usually null
            if (!result.Ok || string.IsNullOrWhiteSpace(result.Text)) return;
            var newCount = Convert.ToInt32(result.Text);
            var res = await _service.EditItem(detail, newCount);
            if (res.Status)
                UpdatePageItem(detail, newCount);
        }
        catch (RestException exception)
        {
           // nothing
        }
    }
 }
</code></pre>

<p>ViewModelTest.cs:</p>

<pre><code>public class ViewModelTest
{
    Mock&lt;IService&gt; _service = new Mock&lt;IService&gt;();
    Mock&lt;IPage&gt; _page = new Mock&lt;IPage&gt;();
    private PageViewModel _viewModel;

    public PageViewModelTest()
    {
        _viewModel = new PageViewModel(_service.Object, _page.Object);
    }

    [Fact]
    public async Task EditItemTest_SuccessAsync()
    {
        var pageItems = GetItemsFake();
        var result = new PromptResult(true, ""12""); // the result i wish to be returned (but is usually null)
        _page.Setup(x =&gt; x.CountDialog(It.IsAny&lt;int&gt;())).ReturnsAsync(result); // this is mock part that not work
        _service.Setup(x =&gt; x.GetItems(It.IsAny&lt;int&gt;())).ReturnsAsync(pageItems);// works 
        _service.Setup(c =&gt; c.EditItem(It.IsAny&lt;int&gt;(), It.IsAny&lt;Detail&gt;(), It.IsAny&lt;int&gt;())).ReturnsAsync(
            new ActionResponse
            {
                Result = ""OK""
            });//works

        _viewModel.LoadDataCommand.Execute(true);
        await _viewModel.EditItem(pageItems .ElementAt(0)); // after this line code goes to _viewModel class and there is null
        //            _viewModel.EditItemCommand.Execute(pageItems.ElementAt(0)); // Also checked this one too, but not work too

        Assert.Equal(12, _viewModel.Data.ElementAt(0).Count); // not passed due to not working mock
    }
}
</code></pre>
",https://stackoverflow.com/questions/46089260/mock-an-async-task-method-returns-null-using-c-and-xamarin,"['c#', 'unit-testing', 'xamarin']",1324,TRUE,1,1
Testing async (Promise) methods in Angular 2 Services,"<p>This is an interesting problem: I'm trying to test a Service, that uses the Ionic BarcodeScanner.
I have a repo based on the <a href=""https://github.com/ionic-team/ionic-unit-testing-example"" rel=""noreferrer"">ionic unit-testing repository</a> in order to try testing.
I'm mocking the BarcodeScanner.scan method via <code>spyOn(..).and.callFake(..)</code></p>

<p>The Problem: It works when I call the scan method from a component. It throws a timeout when I do the exact same thing in a service.</p>

<p>Component test code:</p>

<pre class=""lang-js prettyprint-override""><code>it(""should be able to set a spy on the scanner and test the component"", done =&gt; {
    const testBC = ""123456"";
    const spy = spyOn(TestBed.get(BarcodeScanner), ""scan"");
    spy.and.callFake(() =&gt; {
        return new Promise((resolve, reject) =&gt; {
            resolve(testBC);
        })
    });

        component.testScanner().then(res =&gt; {
            expect(res).toBe(testBC);
            done();
        }, reason =&gt; {
            expect(true).toBe(false);
            done();
        })
});
</code></pre>

<p>Service test code:</p>

<pre class=""lang-js prettyprint-override""><code>it(""should be able to set a spy on the scanner and test the service"", done =&gt; {
    const testBC = ""123456"";
    const spy = spyOn(TestBed.get(BarcodeScanner), ""scan"");
    spy.and.callFake(() =&gt; {
        return new Promise((resolve, reject) =&gt; {
            resolve(testBC);
        })
    });

    inject([TestService], (service) =&gt; {
        service.testScanner().then(res =&gt; {
            expect(res).not.toBe(testBC);
            done()
        }, reason =&gt; {
            expect(true).toBe(false);
            done();
        })
    })
});
</code></pre>

<p>Is there any known problem of testing services in Angular 2 that way? Any help appreciated!</p>
",https://stackoverflow.com/questions/47632138/testing-async-promise-methods-in-angular-2-services,"['angular', 'ionic3', 'angular2-services', 'angular-services']",1071,TRUE,16,1
Why do `assert_eq` and `assert_ne` exist when a simple `assert` will suffice?,"<p><code>assert!(a == b)</code> takes less characters than <code>assert_eq!(a, b)</code> and, in my opinion, is more readable.</p>

<p>The error messages are more or less the same:</p>

<pre class=""lang-none prettyprint-override""><code>thread 'main' panicked at 'assertion failed: `(left == right)` (left: `1`, right: `2`)', src\main.rs:41
</code></pre>

<p>or</p>

<pre class=""lang-none prettyprint-override""><code>thread 'main' panicked at 'assertion failed: 1 == 2', src\main.rs:41
</code></pre>

<p>Actually, this question is not only about Rust; I keep seeing these different assert macros or functions in unit testing frameworks: </p>

<ul>
<li>Cpputest has <code>CHECK</code> and <code>CHECK_FALSE</code> and <code>CHECK_EQUAL</code> and so on;</li>
<li>Googletest has <code>EXPECT_GT</code> and <code>EXPECT_EQ</code> and so on;</li>
<li>JUnit has <code>assertEquals</code> and <code>assertFalse</code> and do on.</li>
</ul>

<p>Frequently there is also assert for some specific type like string or array. What's the point?</p>
",https://stackoverflow.com/questions/43767552/why-do-assert-eq-and-assert-ne-exist-when-a-simple-assert-will-suffice,"['unit-testing', 'rust', 'assert']",4153,TRUE,10,1
Why should object be passed instead of creating them in Dependency Injection?,"<p>Basic concept in DI is that dependency objects should be passed instead of creating them in the dependent object.</p>

<p>Only reasons I could find for this is in <a href=""https://softwareengineering.stackexchange.com/a/232233/218781)"">this answer</a>:</p>

<ol>
<li>To hide the construction details of dependency from dependent to make code less ugly.</li>
<li>To facilitate mocking in Unit Testing.</li>
</ol>

<p>Are there any other reasons?</p>

<p>If not, can you please explain these reasons more to justify DI?</p>
",https://stackoverflow.com/questions/46022040/why-should-object-be-passed-instead-of-creating-them-in-dependency-injection,"['symfony', 'dependency-injection', 'mocking']",71,TRUE,1,2
Mongodb access in mocha test,"<p>So I would like to cleanup my db (before or) after some unit testing.</p>

<p>Basically the code you will see in my codeblocks is in the <code>afterAll</code> block from mocha. I am using webdriver.io testrunner for running my tests.</p>

<p>What I don't understand is, how to use db stuff from outside the connect scope, see:</p>

<pre><code>function createConnection(){
  MongoClient.connect('mongodb://127.0.0.1:24001/meteor', function(err, db) {
    if (err)
      throw err;
    console.log(""connected to the mongoDB !"");

    let myCollection = db.collection('test_collection');
    // do stuff with myCollection

  });
}
</code></pre>

<p>I would prefer, if possible, something like this:</p>

<pre><code>function createConnection(){
  MongoClient.connect('mongodb://127.0.0.1:24001/meteor', function(err, db){
    if (err)
      throw err;
  }
}

function getCollection(name){
  return db.collection(name) //don't have db at this scope, problem?
}

//app.js
createConnection();
let myCollection = getCollection('data');
...//do stuff with myCollection

closeConnection();
</code></pre>

<p>Is this possible?</p>
",https://stackoverflow.com/questions/46344256/mongodb-access-in-mocha-test,"['javascript', 'node.js', 'mongodb', 'mocha.js', 'webdriver-io']",1144,TRUE,1,2
Resharper. How to run the same NUnit TestFixture class in parallel?,"<p>Has anybody implemented this yet? If I declare <code>[TestFixture]</code> class with <code>[Parallelizable]</code> attribute, I'm unable to run this single test class in parallel with multiple browser instances (Selenium). Added up to 4 assemblies in Resharper -> Options -> Unit Testing, didn't help. However, if I have several different test classes with <code>[Parallelizable]</code> attribute, they run in parallel as expected in R# unit test console. Any important point am I missing?        </p>
",https://stackoverflow.com/questions/42009953/resharper-how-to-run-the-same-nunit-testfixture-class-in-parallel,"['visual-studio-2015', 'nunit', 'resharper']",383,TRUE,1,1
CDI : @Resource inject in junit weld?,"<p>Have a simple Mongo DB Producer to connect to Mongo Database</p>

<pre><code>@SuppressWarnings({ ""deprecation"", ""resource"" })
@ApplicationScoped
public class MongoDBProducer {
    @Resource(name = ""mongoUri"")
    private MongoClientURI mongoClientURI;

    private DB database;

    @PostConstruct
    public void init() throws UnknownHostException {
        MongoClient mongoClient = new MongoClient(mongoClientURI);
        database =  mongoClient.getDB(mongoClientURI.getDatabase());
    }

    @Produces
    public DB createDB() {
        return database;
    }
}
</code></pre>

<p>A resource file in my src/main/resources/META-INF</p>

<pre><code>&lt;resources&gt;
    &lt;Resource id=""mongoUri"" class-name=""com.mongodb.MongoClientURI"" constructor=""uri""&gt;
    uri  mongodb://localhost/ironman
    &lt;/Resource&gt;
&lt;/resources&gt;
</code></pre>

<p>And a simple Junit
@RunWith(WeldJUnit4Runner.class)</p>

<pre><code>public class MongoDBProducerTest {
    @Inject
    DB mongoDb;

    @Test
    public void runSampleTest() {
        assertEquals(mongoDb.collectionExists(""jobs""), true);
    }
}
</code></pre>

<p>getting the following error :
org.jboss.weld.exceptions.WeldException: WELD-000049: Unable to invoke public void test.dingo.query.db.util.MongoDBProducer.init() throws java.net.UnknownHostException on test.dingo.query.db.util.MongoDBProducer@a1cdc6d</p>

<p>Using Weld</p>

<pre><code>&lt;dependency&gt;
    &lt;groupId&gt;org.jboss.weld.se&lt;/groupId&gt;
    &lt;artifactId&gt;weld-se&lt;/artifactId&gt;
    &lt;version&gt;2.2.8.Final&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>

<p>WeldContext and WeldJUnit4Runner are from here - <a href=""http://memorynotfound.com/java-se-unit-testing-cdi-junit-jboss-weld-se/"" rel=""nofollow noreferrer"">http://memorynotfound.com/java-se-unit-testing-cdi-junit-jboss-weld-se/</a></p>
",https://stackoverflow.com/questions/45622800/cdi-resource-inject-in-junit-weld,"['java', 'junit', 'cdi', 'weld']",1373,FALSE,1,1
Getting java.lang.NullPointerException for mvc.perform(),"<p>I am new to unit testing in spring boot. I am trying to test a service and have used Mockito for it. When  I do mvc.perform() I get a null value. I have used when() to specify what to return. But not sure why it fails. Please provide some valuable inputs. Here are fe snippets:</p>

<pre><code>@Test
public void testAll() throws Exception {

    /*Mockito.when(sensorDao.findAll()).thenReturn((Iterable&lt;Sensor&gt;) s2);
    assertEquals(200,expect().statusCode(200));*/

    Collection&lt;Sensor&gt;list =  getEntityListStubData();
    when(sensorserviceimpl.findAll()).thenReturn(list);
    when(sensorService.findAll()).thenReturn(list);
    when(sensorDao.findAll()).thenReturn(list);
    String uri=""/sensor"";
    //System.out.print(""gfnjhkjjhhg"");
    System.out.println(""Helllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllloooooooooooooooooooooooooooooooooooooooooooo"");
    System.out.println(MockMvcRequestBuilders.get(uri).accept(MediaType.APPLICATION_JSON));
    MvcResult result = mvc.perform(MockMvcRequestBuilders.get(uri).accept(MediaType.APPLICATION_JSON)).andReturn();
    String content = result.getResponse().getContentAsString();
    int status = result.getResponse().getStatus();
 }
</code></pre>

<p>Here is the output:</p>

<pre><code>2017-08-18 19:11:45.030  INFO 21424 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test context [DefaultTestContext@35083305 testClass = SensorServiceStandaloneApplicationTests, testInstance = com.bny.sr.sensorservicestandalone.SensorServiceStandaloneApplicationTests@482cd91f, testMethod = testAll@SensorServiceStandaloneApplicationTests, testException = java.lang.NullPointerException, mergedContextConfiguration = [WebMergedContextConfiguration@8e0379d testClass = SensorServiceStandaloneApplicationTests, locations = '{}', classes = '{class com.bny.sr.sensorservicestandalone.SensorServiceStandaloneApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{eureka.client.enabled:false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, server.port=0}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@167fdd33, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@53f65459, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@74650e52, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@80503], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]].

java.lang.NullPointerException
    at com.bny.sr.sensorservicestandalone.SensorServiceStandaloneApplicationTests.testAll(SensorServiceStandaloneApplicationTests.java:163)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

2017-08-18 19:11:45.046  INFO 21424 --- [       Thread-5] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@5386659f: startup date [Fri Aug 18 19:11:34 IST 2017]; root of context hierarchy
2017-08-18 19:11:45.054  INFO 21424 --- [       Thread-5] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'

Process finished with exit code -1
</code></pre>

<p>Here is the debug result:</p>

<p><a href=""https://i.stack.imgur.com/L3J33.png"" rel=""nofollow noreferrer"">Debug results</a></p>
",https://stackoverflow.com/questions/45758429/getting-java-lang-nullpointerexception-for-mvc-perform,"['unit-testing', 'spring-boot', 'nullpointerexception', 'mockito', 'mockmvc']",11140,TRUE,1,2
Test models using Mocha and Sequelize,"<p>I'd like to test CRUD operation on mysql database using Sequelize as ORM and Mocha/Chai for unit testing. I tested the insertion/deleting of record using http routing, but I'd test directly the models without using any http connection. I tried to do it but when I launch the test the record is not added and I don't receive any error.</p>

<p><strong>app/model/article.js</strong></p>

<pre><code>  module.exports = function (sequelize, DataTypes) {

  var Article = sequelize.define('Article', {
    title: DataTypes.STRING,
    url: DataTypes.STRING,
    text: DataTypes.STRING
  }, {
    classMethods: {
      associate: function (models) {
        // example on how to add relations
        // Article.hasMany(models.Comments);
      }
    }
  });

  return Article;
};
</code></pre>

<p><strong>app/model/index.js</strong></p>

<pre><code>var fs = require('fs'),
  path = require('path'),
  Sequelize = require('sequelize'),
  config = require('../../config/config'),
  db = {};

var sequelize = new Sequelize(config.db);

fs.readdirSync(__dirname).filter(function (file) {
  return (file.indexOf('.') !== 0) &amp;&amp; (file !== 'index.js');
}).forEach(function (file) {
  var model = sequelize['import'](path.join(__dirname, file));
  db[model.name] = model;
});

Object.keys(db).forEach(function (modelName) {
  if ('associate' in db[modelName]) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
</code></pre>

<p><strong>test/model/article.js</strong></p>

<pre><code>'use strict';

var expect = require('chai').expect;

var db = require('../../../app/models');
var Article = db.Article;

describe('article', function () {
  it('should load', function (done) {
    Article.create({
      title: 'Titolo',
      url: 'URL',
      text: 'TEXT'
    });
    done();
  });
});
</code></pre>
",https://stackoverflow.com/questions/44585157/test-models-using-mocha-and-sequelize,"['javascript', 'mysql', 'node.js', 'mocha.js', 'sequelize.js']",6370,TRUE,4,1
Jest - TypeError: Cannot read property &#39;projects&#39; of undefined,"<p>So I am starting to do unit testing of my React-Native application. I just wanted to try the first test and I immediately get errors. </p>

<p>Here is what my test looks like: </p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>import 'react-native';
import React from 'react';
import Index from '../index.ios.js';

// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';

it('renders correctly', () =&gt; {
  const tree = renderer.create(
    &lt;Index /&gt;
  ).toJSON();
  expect(tree).toMatchSnapshot();
});</code></pre>
</div>
</div>
</p>

<p>and here is my package JSON </p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>{
  ""name"": ""project"",
  ""version"": ""0.0.1"",
  ""private"": true,
  ""scripts"": {
    ""start"": ""node node_modules/react-native/local-cli/cli.js start"",
    ""test"": ""jest"",
    ""build"": ""npm install &amp;&amp; react-native link &amp;&amp; react-native run-ios""
  },
  ""dependencies"": {
    ""anymatch"": ""^1.3.0"",
    ""native-base"": ""^2.2.0"",
    ""react"": ""16.0.0-alpha.12"",
    ""react-native"": ""0.45.1"",
    ""react-native-datepicker"": ""^1.6.0"",
    ""react-native-elements"": ""^0.13.0"",
    ""react-native-local-notifications"": ""^0.1.0"",
    ""react-native-maps"": ""^0.15.2"",
    ""react-native-notifications"": ""^1.1.11"",
    ""react-native-sound"": ""^0.10.3"",
    ""react-native-swipeout"": ""^2.1.3"",
    ""react-native-vector-icons"": ""^4.2.0"",
    ""react-navigation"": ""^1.0.0-beta.11"",
    ""react-redux"": ""^5.0.5"",
    ""redux"": ""^3.7.1"",
    ""redux-logger"": ""^3.0.6"",
    ""redux-thunk"": ""^2.2.0""
  },
  ""devDependencies"": {
    ""babel-jest"": ""20.0.3"",
    ""babel-preset-react-native"": ""2.0.0"",
    ""jest"": ""20.0.4"",
    ""react-test-renderer"": ""16.0.0-alpha.12""
  },
  ""jest"": {
    ""preset"": ""react-native""
  }
}</code></pre>
</div>
</div>
</p>

<p>The error I get is this : </p>

<pre><code>TypeError: Cannot read property 'projects' of undefined
at /Users/grantherman/Desktop/project/node_modules/jest/node_modules/jest-cli/build/cli/runCLI.js:106:25
at Generator.next (&lt;anonymous&gt;)
at step (/Users/grantherman/Desktop/project/node_modules/jest/node_modules/jest-cli/build/cli/runCLI.js:1:260)
at /Users/grantherman/Desktop/project/node_modules/jest/node_modules/jest-cli/build/cli/runCLI.js:1:490
at Promise (&lt;anonymous&gt;)
at /Users/grantherman/Desktop/project/node_modules/jest/node_modules/jest-cli/build/cli/runCLI.js:1:171
at module.exports (/Users/grantherman/Desktop/project/node_modules/jest/node_modules/jest-cli/build/cli/runCLI.js:139:50)
at Object.run (/Users/grantherman/Desktop/project/node_modules/jest/node_modules/jest-cli/build/cli/index.js:40:3)
at Object.&lt;anonymous&gt; (/Users/grantherman/Desktop/project/node_modules/jest/node_modules/jest-cli/bin/jest.js:14:25)
at Module._compile (module.js:569:30)
</code></pre>

<p>I literally have no idea why. I have looked around and no one has experienced the same error as this. </p>
",https://stackoverflow.com/questions/45039991/jest-typeerror-cannot-read-property-projects-of-undefined,"['javascript', 'react-native', 'jestjs']",1758,FALSE,1,2
In xamarin shared F# project modules are marked as &quot;Not defined&quot; on Console project,"<p>I wanna use shared project. It work fine for the iOS/Android project. Now I wanna create a console project for do the unit testing.</p>

<p>However, despite in the editor the modules are found and the intellisense work for them, when compiled I get:</p>

<pre><code>..Test/TestsClient.fs(6,6): Error FS0039: The namespace or module 'Db' is not defined. (FS0039) (Test)
</code></pre>

<p>And others like that.</p>

<p>I have target .NET 4.6.2 and tested too with 4.5.</p>

<p>This is the project:</p>

<pre><code>&lt;Project DefaultTargets=""Build"" ToolsVersion=""4.0"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""&gt;
  &lt;PropertyGroup&gt;
    &lt;Configuration Condition="" '$(Configuration)' == '' ""&gt;Debug&lt;/Configuration&gt;
    &lt;Platform Condition="" '$(Platform)' == '' ""&gt;iPhoneSimulator&lt;/Platform&gt;
    &lt;ProjectGuid&gt;{90334D33-1842-4D13-8367-069308850F4E}&lt;/ProjectGuid&gt;
    &lt;OutputType&gt;Exe&lt;/OutputType&gt;
    &lt;RootNamespace&gt;Cobros&lt;/RootNamespace&gt;
    &lt;AssemblyName&gt;Test&lt;/AssemblyName&gt;
    &lt;TargetFrameworkVersion&gt;v4.6.2&lt;/TargetFrameworkVersion&gt;
  &lt;/PropertyGroup&gt;
  &lt;PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Debug|iPhoneSimulator' ""&gt;
    &lt;DebugSymbols&gt;true&lt;/DebugSymbols&gt;
    &lt;DebugType&gt;full&lt;/DebugType&gt;
    &lt;Optimize&gt;false&lt;/Optimize&gt;
    &lt;OutputPath&gt;bin\Debug&lt;/OutputPath&gt;
    &lt;DefineConstants&gt;DEBUG&lt;/DefineConstants&gt;
    &lt;ErrorReport&gt;prompt&lt;/ErrorReport&gt;
    &lt;ExternalConsole&gt;true&lt;/ExternalConsole&gt;
    &lt;GenerateTailCalls&gt;true&lt;/GenerateTailCalls&gt;
  &lt;/PropertyGroup&gt;
  &lt;PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Release|iPhoneSimulator' ""&gt;
    &lt;Optimize&gt;true&lt;/Optimize&gt;
    &lt;OutputPath&gt;bin\Release&lt;/OutputPath&gt;
    &lt;DefineConstants&gt;&lt;/DefineConstants&gt;
    &lt;ErrorReport&gt;prompt&lt;/ErrorReport&gt;
    &lt;ExternalConsole&gt;true&lt;/ExternalConsole&gt;
    &lt;GenerateTailCalls&gt;true&lt;/GenerateTailCalls&gt;
  &lt;/PropertyGroup&gt;
  &lt;PropertyGroup&gt;
    &lt;FSharpTargetsPath&gt;$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\FSharp\Microsoft.FSharp.Targets&lt;/FSharpTargetsPath&gt;
  &lt;/PropertyGroup&gt;
  &lt;PropertyGroup Condition=""'$(VisualStudioVersion)' == '10.0' OR '$(VisualStudioVersion)' == '11.0'""&gt;
    &lt;FSharpTargetsPath&gt;$(MSBuildExtensionsPath32)\..\Microsoft SDKs\F#\3.0\Framework\v4.0\Microsoft.FSharp.Targets&lt;/FSharpTargetsPath&gt;
  &lt;/PropertyGroup&gt;
  &lt;ItemGroup&gt;
    &lt;Reference Include=""mscorlib"" /&gt;
    &lt;Reference Include=""System"" /&gt;
    &lt;Reference Include=""System.Core"" /&gt;
    &lt;Reference Include=""System.Numerics"" /&gt;
    &lt;Reference Include=""System.ValueTuple""&gt;
      &lt;HintPath&gt;..\packages\System.ValueTuple.4.3.0\lib\netstandard1.0\System.ValueTuple.dll&lt;/HintPath&gt;
    &lt;/Reference&gt;
    &lt;Reference Include=""Fuchu""&gt;
      &lt;HintPath&gt;..\packages\Fuchu.1.0.3.0\lib\Fuchu.dll&lt;/HintPath&gt;
    &lt;/Reference&gt;
    &lt;Reference Include=""FSharp.Core""&gt;
      &lt;HintPath&gt;..\packages\FSharp.Core.4.2.1\lib\net45\FSharp.Core.dll&lt;/HintPath&gt;
    &lt;/Reference&gt;
    &lt;Reference Include=""System.Data"" /&gt;
    &lt;Reference Include=""Mono.Data.Sqlite"" /&gt;
    &lt;Reference Include=""System.Xml"" /&gt;
  &lt;/ItemGroup&gt;
  &lt;ItemGroup&gt;
    &lt;Compile Include=""AssemblyInfo.fs"" /&gt;
    &lt;None Include=""packages.config"" /&gt;
    &lt;Compile Include=""TestUtils.fs"" /&gt;
    &lt;Compile Include=""TestsClient.fs"" /&gt;
    &lt;Compile Include=""Program.fs"" /&gt;
  &lt;/ItemGroup&gt;
  &lt;Import Project=""..\CobrosDb.projitems"" Label=""Shared"" Condition=""Exists('..\CobrosDb.projitems')"" /&gt;
  &lt;Import Project=""$(FSharpTargetsPath)"" /&gt;
&lt;/Project&gt;
</code></pre>

<p>This is the build log:</p>

<pre><code>Target GenerateTargetFrameworkMonikerAttribute:
  Skipping target ""GenerateTargetFrameworkMonikerAttribute"" because all output files are up-to-date with respect to the input files.
Target CoreCompile:
    /Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/fsharp/fsc.exe -o:obj/iPhoneSimulator/Debug/Test.exe
    -g
    --debug:full
    --noframework
    --define:DEBUG
    --optimize-
    --tailcalls-
    -r:.../Movil/packages/FSharp.Core.4.2.1/lib/net45/FSharp.Core.dll
    -r:.../Movil/packages/Fuchu.1.0.3.0/lib/Fuchu.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Mono.Data.Sqlite.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/mscorlib.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/System.Core.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/System.Data.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/System.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/System.Numerics.dll
    -r:.../Movil/packages/System.ValueTuple.4.3.0/lib/netstandard1.0/System.ValueTuple.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/System.Xml.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Collections.Concurrent.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Collections.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.ComponentModel.Annotations.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.ComponentModel.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.ComponentModel.EventBasedAsync.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Diagnostics.Contracts.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Diagnostics.Debug.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Diagnostics.Tools.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Diagnostics.Tracing.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Dynamic.Runtime.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Globalization.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.IO.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Linq.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Linq.Expressions.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Linq.Parallel.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Linq.Queryable.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Net.NetworkInformation.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Net.Primitives.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Net.Requests.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Net.WebHeaderCollection.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.ObjectModel.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Reflection.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Reflection.Emit.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Reflection.Emit.ILGeneration.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Reflection.Emit.Lightweight.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Reflection.Extensions.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Reflection.Primitives.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Resources.ResourceManager.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Runtime.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Runtime.Extensions.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Runtime.Handles.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Runtime.InteropServices.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Runtime.InteropServices.WindowsRuntime.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Runtime.Numerics.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Runtime.Serialization.Json.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Runtime.Serialization.Primitives.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Runtime.Serialization.Xml.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Security.Principal.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.ServiceModel.Duplex.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.ServiceModel.Http.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.ServiceModel.NetTcp.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.ServiceModel.Primitives.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.ServiceModel.Security.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Text.Encoding.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Text.Encoding.Extensions.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Text.RegularExpressions.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Threading.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Threading.Tasks.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Threading.Tasks.Parallel.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Threading.Timer.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Xml.ReaderWriter.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Xml.XDocument.dll
    -r:/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.6.2-api/Facades/System.Xml.XmlSerializer.dll
    --target:exe
    --warnaserror:76
    --fullpaths
    --flaterrors
    --subsystemversion:6.00
    --highentropyva+
    /var/folders/tm/n9jvsc5s4m72hg8_r47dn4z40000gn/T/.NETFramework,Version=v4.6.2.AssemblyAttributes.fs
    AssemblyInfo.fs
    TestUtils.fs
    TestsClient.fs
    Program.fs
    .../Movil/Db.fs
    .../Movil/DbClient.fs
    .../Movil/Utils.fs


    .../Movil/Test/TestsClient.fs(6,6): error FS0039: The namespace or module 'Db' is not defined.
</code></pre>
",https://stackoverflow.com/questions/44663359/in-xamarin-shared-f-project-modules-are-marked-as-not-defined-on-console-proj,"['.net', 'macos', 'visual-studio', 'xamarin', 'f#']",79,FALSE,1,0
Spying on a method which is being called from the component&#39;s constructor,"<p>I am new to unit testing and I have a component in my project which in its constructor a method is being called</p>

<pre><code>export class myComponent {
constructor(){       
        this.someMethod();
   }

public someMethod(){
 //some code
}
</code></pre>

<p>I want to test if the method is being called with this test suite:</p>

<pre><code>it('should call for the someMethod', () =&gt; {
    spyOn(component, 'someMethod')   //also tried .and.callThrough();

    expect(component.someMethod).toHaveBeenCalled();;
});
</code></pre>

<p>The problem is while with my debugging I can make sure the method is being called, the test will always fail. </p>

<p>would really appreciate it, if someone help.</p>
",https://stackoverflow.com/questions/46830799/spying-on-a-method-which-is-being-called-from-the-components-constructor,"['angularjs', 'typescript', 'ionic-framework', 'ecmascript-6', 'jasmine']",1619,TRUE,1,1
Exclude the specified packages/classes from the jacoco coverage report,"<p>I am working on spring based web application. But, we are using scalatest for unit testing.</p>

<p>We are using jacoco maven plugin for code coverage report generation.
Now i am trying to exclude some packages to increase the code coverage. For that i have done the configuration as below. But specified packages are not excluding from the report. Could you please help me to solve this issue?</p>

<pre><code>        &lt;plugin&gt;
            &lt;groupId&gt;org.jacoco&lt;/groupId&gt;
            &lt;artifactId&gt;jacoco-maven-plugin&lt;/artifactId&gt;
            &lt;version&gt;${maven-jacoco-plugin.version}&lt;/version&gt;
            &lt;inherited&gt;false&lt;/inherited&gt;
            &lt;executions&gt;
                &lt;execution&gt;
                    &lt;id&gt;jacoco-initialize&lt;/id&gt;
                    &lt;goals&gt;
                        &lt;goal&gt;prepare-agent&lt;/goal&gt;
                    &lt;/goals&gt;
                &lt;/execution&gt;
                &lt;execution&gt;
                    &lt;id&gt;jacoco-site&lt;/id&gt;
                    &lt;phase&gt;package&lt;/phase&gt;
                    &lt;goals&gt;
                        &lt;goal&gt;report&lt;/goal&gt;
                    &lt;/goals&gt;

                    &lt;configuration&gt;
                        &lt;excludes&gt;
                            &lt;exclude&gt;**/model/*&lt;/exclude&gt;
                        &lt;/excludes&gt;
                    &lt;/configuration&gt;
                &lt;/execution&gt;
                &lt;execution&gt;
                    &lt;id&gt;default-check&lt;/id&gt;
                    &lt;goals&gt;
                        &lt;goal&gt;check&lt;/goal&gt;
                    &lt;/goals&gt;
                    &lt;configuration&gt;
                        &lt;rules&gt;
                            &lt;rule&gt;
                                &lt;element&gt;BUNDLE&lt;/element&gt;
                                &lt;limits&gt;
                                    &lt;limit&gt;
                                        &lt;counter&gt;LINE&lt;/counter&gt;
                                        &lt;value&gt;COVEREDRATIO&lt;/value&gt;
                                        &lt;minimum&gt;0.45&lt;/minimum&gt;
                                    &lt;/limit&gt;
                                &lt;/limits&gt;
                            &lt;/rule&gt;
                        &lt;/rules&gt;
                    &lt;/configuration&gt;
                &lt;/execution&gt;
            &lt;/executions&gt;
        &lt;/plugin&gt;
        &lt;plugin&gt;
            &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
            &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;
            &lt;version&gt;${maven-surefire-plugin.version}&lt;/version&gt;
            &lt;inherited&gt;false&lt;/inherited&gt;
            &lt;configuration&gt;

                &lt;excludes&gt;
                    &lt;exclude&gt;**/model/*&lt;/exclude&gt;
                &lt;/excludes&gt;
            &lt;/configuration&gt;
        &lt;/plugin&gt;
</code></pre>
",https://stackoverflow.com/questions/48018373/exclude-the-specified-packages-classes-from-the-jacoco-coverage-report,"['maven-plugin', 'jacoco-maven-plugin']",2144,FALSE,1,0
Storing 1024x768 bpp bitmaps in TFS,"<p>We would need to keep a number of *.bmp images (~50 MB) versioned (we do image comparison unit testing). So far I kept these files away from our main product TFS project because I was afraid that they could slow down GET operations, slow down TFS backup, because source control is not optimized for binaries and big files, etc.</p>

<p>Are my concerns legitimate or not?</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/46811122/storing-1024x768-bpp-bitmaps-in-tfs,"['c#', '.net', 'visual-studio', 'tfs', 'version-control']",110,FALSE,0,1
Testing: how to deal with a private variable in a class to test?,"<p>I'm new to Unit Testing. Simple question about private variables.</p>

<p>I have a <code>UIViewController</code> with </p>

<pre><code>private var tableView:UITableView
</code></pre>

<p>I can't access the <code>tableView</code> variable to check the number of rows (to see if the data are loaded correctly).</p>

<p>The best solution I could think of so far is to add a method <code>getRows()</code> to the original implementation of the class.</p>

<pre><code>  func getRows() -&gt; Int {  return tableView.numberOfRows(inSection: 0) }
</code></pre>

<p>Subclassing the class is not a solution, because <code>tableView</code> is private.</p>

<p>Am I correct?</p>
",https://stackoverflow.com/questions/44344777/testing-how-to-deal-with-a-private-variable-in-a-class-to-test,"['swift', 'unit-testing']",36,FALSE,0,0
Error: No provider for InjectionToken USE_DEFAULT_LANG,"<p>I am new to angular 4 jasmine unit testing. </p>

<ol>
<li>Kindly help me to get full test coverage for my component attached.</li>
<li>I have added child dependencies for translate module but still I am getting <strong>Error: No provider for InjectionToken USE_DEFAULT_LANG!</strong> what is the solution for this???</li>
<li>I want to know how to cover variables and methods in the code I attached for full coverage.</li>
</ol>

<p>Thanks for helping.</p>

<p><strong>LOGIN COMPONENT :</strong></p>

<pre><code>   import { Component, OnInit } from '@angular/core';
    import { Router } from '@angular/router';
    import { Http, Headers, RequestOptions, Response } from '@angular/http';
    import { HttpError } from '../core/http-error';
    import { jsonFields } from '../app.constants';
    import { LoggedUserData } from '../shared/model/loggedUserData';
    import { Observable } from 'rxjs/Observable';
    import { FormControl, Validators } from '@angular/forms';
    import { LoginService } from '../shared/login.service';

    @Component({
      selector: 'app-login',
      templateUrl: './login.component.html',
      styleUrls: ['./login.component.scss']
    })
    export class LoginComponent implements OnInit {
      userID: string;
      userPassword: string;
      hide: boolean = true;
      errorMsg: string;
      errorShow: boolean = false;
      showLoad: boolean = false;

      constructor(private router: Router, private _http: Http, private _LoginService: LoginService) { }

      loginFormControl = new FormControl('', [
        Validators.required]);

      ngOnInit() {
      }
      onLogin() {
        this.showLoad = true;
        var loggedUserData = new LoggedUserData();
        var secPayload = {};
        secPayload[jsonFields.login.userId] = this.userID;
        secPayload[jsonFields.login.password] = this.userPassword;
        secPayload[jsonFields.login.businessUnitId] = ""7238"";
        secPayload[jsonFields.login.domainName] = """";

        this._LoginService.authenticate(secPayload).subscribe(
          result =&gt; {
            loggedUserData.userId = result[jsonFields.loggedUserData.userId];
            loggedUserData.token = result[jsonFields.loggedUserData.token];
            loggedUserData.authTypeCode = result[jsonFields.loggedUserData.authTypeCode];
            loggedUserData.businessUnitId = result[jsonFields.loggedUserData.businessUnitId];
            loggedUserData.firstName = result[jsonFields.loggedUserData.firstName];
            loggedUserData.lastName = result[jsonFields.loggedUserData.lastName];
            loggedUserData.links = result[jsonFields.loggedUserData.links];
            loggedUserData.locale = result[jsonFields.loggedUserData.locale];
            loggedUserData.pwdExpired = result[jsonFields.loggedUserData.pwdExpired];
            loggedUserData.securityId = result[jsonFields.loggedUserData.securityId];
            loggedUserData.upn = result[jsonFields.loggedUserData.upn];
            this.errorShow = false;
            const token: string = loggedUserData.token;
            if (token != null) {
              localStorage.setItem(""tokenId"", token);
              this.router.navigate(['delivery']);
            }
            else {
              localStorage.removeItem(""tokenId"");
              this.router.navigate(['login']);
            }
            this.showLoad = false;
          },
          (error: HttpError) =&gt; {
            this.errorShow = true;
            this.errorMsg = error.message;
            this.showLoad = false;
          }
        );
      }
    }
</code></pre>

<p><strong>LOGIN COMPONENT SPEC :</strong> </p>

<pre><code>import { async, ComponentFixture, TestBed, inject } from '@angular/core/testing';

import { LoginComponent } from './login.component';
import { LoginService } from '../shared/login.service';
import { MatProgressBarModule } from '@angular/material';
import { TranslateModule, TranslateService, TranslateLoader, TranslateFakeLoader, TranslateCompiler, TranslateParser, MissingTranslationHandler } from '@ngx-translate/core';
import { MatInputModule } from '@angular/material';
import { FormsModule } from '@angular/forms';
import { Router, RouterModule } from '@angular/router';
import { HttpModule } from '@angular/http';
import { TranslationService } from '../translation/translation.service';
import { TranslateStore } from ""@ngx-translate/core/src/translate.store"";


describe('LoginComponent', () =&gt; {
  let component: LoginComponent;
  let fixture: ComponentFixture&lt;LoginComponent&gt;;

  const mockLoginService = {
    authenticate() { },
    validateLoginToken() { }
  };

  const mockTranslationService = {
    validateLanguage() {
    }
  }

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [LoginComponent],
      imports: [MatProgressBarModule, FormsModule, HttpModule, RouterModule, TranslateModule],
      providers: [
        {
          provide: LoginService, useValue: mockLoginService
        },
        {
          provide: TranslationService, useValue: mockTranslationService
        },
        {
          provide: Router,
          useClass: class { navigate = jasmine.createSpy(""navigate""); }
        },
        {
          provide: TranslateLoader,
          useClass: TranslateFakeLoader
        },
        TranslateService, TranslateStore, TranslateCompiler, TranslateParser, MissingTranslationHandler
      ]
    })
      .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    component.errorMsg = ""dsadsad"";
    component.errorShow = true;
    component.hide = true;
    component.showLoad = true;
    component.userID = '';
    component.userPassword = '';


    expect(component).toBeTruthy();
    expect(component.onLogin).toBeTruthy();

  });

  it('validate Login', inject([LoginService],
    (service: LoginService) =&gt; {
      expect(service.authenticate).toBeTruthy();
      expect(service.validateLoginToken).toBeTruthy();
    }));

  it('should translate the language service', inject([TranslationService],
    (service: TranslationService) =&gt; {
      expect(service).toBeTruthy();
      expect(service.validateLanguage).toBeTruthy();
    }));
});
</code></pre>

<p><strong>TRANSLATION MODULE :</strong> </p>

<pre><code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';

// AoT requires an exported function for factories
export function HttpLoaderFactory(httpClient: HttpClient) {
  return new TranslateHttpLoader(httpClient, ""./assets/i18n/"", "".json"");
}
@NgModule({
  imports: [
    CommonModule,
    HttpClientModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      }
    })
  ],
  declarations: []
})
export class TranslationModule { }
</code></pre>
",https://stackoverflow.com/questions/47712728/error-no-provider-for-injectiontoken-use-default-lang,"['angular', 'jasmine', 'karma-jasmine', 'karma-coverage', 'angular4-router']",12917,TRUE,6,1
Dependency Resolution Exception,"<p>I am doing Unit Testing  In my Project.When I try to unit test my method a browser pops up and suddenly gets stopped after that I get a long exception I pasted following.
How to fix this mess as I have no idea whats the cause?</p>

<p><strong>Exception:</strong></p>

<p><a href=""https://paste.ubuntu.com/24389202/"" rel=""nofollow noreferrer"">https://paste.ubuntu.com/24389202/</a></p>

<p><strong>BrowseHost Class</strong></p>

<pre><code> public static class BrowserHost
    {
        public static readonly SelenoHost Instance = new SelenoHost();
        public static readonly String RootUrl;
         static BrowserHost()
        {
            Instance.Run(""BankingSite"", 1468);
            RootUrl= Instance.Application.Browser.Url;
        }
    }
</code></pre>

<p><strong>UnitTest Class</strong></p>

<pre><code>namespace BankingSite.FunctionalUITests
{
    [TestFixture]
    public class LoanApplicationTest
    {
        [Test]
        public void ShouldAcceptLoanApplication()
        {
            BrowserHost.Instance
                .Application.Browser
                .Navigate()
                .GoToUrl($@""{BrowserHost.RootUrl}\LoanApplication\Apply"");

            var firstNameBox = BrowserHost.Instance.Application
                .Browser
                .FindElement(By.Id(""FirstName""));
            firstNameBox.SendKeys(""Gentry"");

            var lastNameBox = BrowserHost.Instance.
                Application.
                Browser.
                FindElement(By.Id(""LastName""));
            lastNameBox.SendKeys(""Smith"");

            var ageBox = BrowserHost.Instance
                .Application
                .Browser
                .FindElement(By.Id(""Age""));
            ageBox.SendKeys(""40"");

            var incomeBox = BrowserHost.Instance
                .Application
                .Browser
                .FindElement(By.Id(""AnnualIncome""));
            incomeBox.SendKeys(""9999999"");
            Thread.Sleep(10000);

            var applyButton = BrowserHost.Instance
                .Application
                .Browser
                .FindElement(By.Id(""Applt""));

            applyButton.Click();
            Thread.Sleep(10000);

            var acceptMessageText = BrowserHost.Instance
                .Application
                .Browser
                .FindElement(By.Id(""acceptMessage""));

            Assert.That(acceptMessageText, Is.EqualTo(""Congratulations Gentry - Your Application was accepted!""));
            Thread.Sleep(10000);

        }
    }
</code></pre>

<p><strong>Following is the Screen Shot of URL I am browsing directly.</strong></p>

<p><a href=""https://i.stack.imgur.com/sYnYS.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/sYnYS.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/43430332/dependency-resolution-exception,"['c#', 'unit-testing', 'selenium-webdriver']",840,TRUE,0,1
Flask app exception during jwt.decode(),"<p>I get an exception in the following snippet, which constitutes part of an authentication decorator in my flask app:</p>

<pre><code>try:
    token = jwt.decode(
            request.headers.get('Authorization'),
            secret,
            algorithms=['HS256'])
except Exception as e:
    print(str(e))
</code></pre>

<p>The exception being:</p>

<pre><code>Invalid token type. Token must be a &lt;class 'bytes'&gt;
</code></pre>

<p>One of the test cases that causes this looks like:</p>

<pre><code>resp = self.app.get('/api/1.0/environments',
                        headers={""key"": ""Authorization"",
                                 ""value"": self.api_token,
                                 ""description"": """"},
                        content_type='application/json')
</code></pre>

<p>The exceptions occur even when content_type is removed, and appear only during unit testing. </p>

<p>The same decorator works fine when tested via a rest client such as postman, with the same authentication key.</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/45446713/flask-app-exception-during-jwt-decode,"['python', 'flask', 'jwt', 'decode']",2585,FALSE,0,0
Is it acceptable to create unit tests only after qa testing is done?,"<p>I came to know that in some shops, code is developed first, given to QA for testing and then developers write unit tests for that code. Is this approach acceptable ? If yes, then what are the pros &amp; cons ?</p>

<p>I got some clues in answers in an unrelated question : <a href=""https://stackoverflow.com/questions/67299/is-unit-testing-worth-the-effort"">Is Unit Testing worth the effort?</a>
But, I also need answers specifically for my question.</p>
",https://stackoverflow.com/questions/44036984/is-it-acceptable-to-create-unit-tests-only-after-qa-testing-is-done,"['unit-testing', 'testing']",22,TRUE,0,1
mocking injected class method,"<p>I have a Gateway class that has contains an instance of a Resource class.  I've already done my unit testing on Resource, and to simplify testing, Resource is injected into Gateway as a dependency at initialization:</p>

<pre><code>class Gateway:

  def __init__(self, resource):
    self._resource = resource(Master)

  def list_things(self):
    return self._resource.list_resource()
</code></pre>

<p>Now I'd like write unit test for Gateway to verify that <code>resource.list_resource()</code> gets called as a result of calling <code>gateway.list_things()</code>.  My best attempt doesn't work:</p>

<pre><code>class TestGateway(unittest.TestCase):

    def test_list_things(self):
        mock_resource = Mock()
        g = modbus.gateway.Gateway(mock_resource)
        g.list_things()
        mock_resource.list_resource.assert_called_once()
</code></pre>

<p>The result:</p>

<pre><code>AssertionError: Expected 'list_resource' to have been called once. Called 0 times.
</code></pre>

<p>What am I missing?</p>
",https://stackoverflow.com/questions/47342354/mocking-injected-class-method,"['python', 'unit-testing', 'dependency-injection', 'mocking']",388,TRUE,0,1
How to set up grunt task for Jest?,"<p>I need to run my jest command for unit testing react application using grunt. Is there any way I can set up a grunt task for the same and configure it to execute the jest command? Currently I am using <code>npm run test</code> to execute jest. For the same I have configured my <code>package.json</code> with a test script that executes jest.</p>

<pre><code>""test"": ""jest""
</code></pre>

<p>How can I achieve the same using Grunt task?</p>
",https://stackoverflow.com/questions/45675044/how-to-set-up-grunt-task-for-jest,"['node.js', 'reactjs', 'npm', 'gruntjs', 'jestjs']",1503,FALSE,0,0
UnitTesting SQL Database in Java,"<p>We have kinda stuck in one point of unit testing. 
We would like to test, what happens if the database server is not connected or not reachable. We have already written the testcode, but we are not able to imitate, if the server is not connected.</p>

<p>Here is our current test code:</p>

<pre><code>@Test
public void databaseIsNotRunning() throws Exception {
    mockMvc.perform(get(""/heartbeat""))
            .andExpect(status().is5xxServerError())
            .andExpect(MockMvcResultMatchers.jsonPath(""$.application-status"").value(""ok""))
            .andExpect(MockMvcResultMatchers.jsonPath(""$.database-status"").value(""error""))
            .andExpect(content().contentType(contentType));
}
</code></pre>

<p>What is wrong with it, or missing?
Can someone or anyone help?</p>
",https://stackoverflow.com/questions/47554265/unittesting-sql-database-in-java,"['java', 'unit-testing', 'mockmvc']",42,FALSE,0,1
.NET Nancy self hosting configuration files missing,"<p>I'm using the Nancy self hosting feature to do some unit testing. From my unit testing project (separate from the nancy API project), I use the following code to create an instance of my API:</p>

<pre><code>var myApp = new NancyHost(new Uri(MockRestApiUrl), new Bootstrapper(), new HostConfiguration() { UrlReservations = new UrlReservations { CreateAutomatically = true } });
</code></pre>

<p>In the Bootstrapper I have some code which looks for a set of config files to preload into memory. Note that these are not static files to be served, but files which drive the configuration of the API. </p>

<p>The problem I have is that the Bootstrapper generates an exception because it can't find the configuration files it's looking for. I set the config file path via <code>RootPathProvider.GetRootPath()</code> and get:</p>

<p>C:...\AppData\Local\Temp\b3f2483d-8c40-45d8-8ba3-dd8db2b9bfd3\b3f2483d-8c40-45d8-8ba3-dd8db2b9bfd3\assembly\dl3\bf80d16d\b3b00d8e_bd91d201\Mapping\PropertyMapping.json</p>

<p>When I look at the folder, the Mapping folder and config file are missing. I have tried marking these as 'Content' and 'Copy Always' in Visual Studio and have cleaned my solution several times, but no luck. How do I get these files copied to the self-hosted site?</p>
",https://stackoverflow.com/questions/42702004/net-nancy-self-hosting-configuration-files-missing,"['.net', 'unit-testing', 'nancy', 'self-hosting', 'configuration-files']",210,TRUE,1,1
spock and clover integration,"<p>In my project, we are using spock for unit testing. I want to configure spock test cases with clover so that it can generate the coverage report. I have followed steps and configure it in maven. However, I am not able to configure it properly.
Could anyone guide me, to configure clover with spock?</p>

<p>my groovy test cases are in src/test/groovy package.</p>

<p>Thanks,
Jay Patel</p>
",https://stackoverflow.com/questions/43273588/spock-and-clover-integration,"['maven', 'spock', 'clover']",270,FALSE,0,1
Unit Test Loop gets executed more than once,"<p>For some reason the loop inside a method, that gets executed in a unit test, gets executed more than once. And because of that I get <code>ConcurrentModificationException</code>. To make it short, method loops through objects, executes other method on each object, with <code>Runnable</code> parameter. This works just fine when application is deployed, but during unit testing, loop gets executed more than once and I get an error.</p>

<p>Code example:</p>

<pre><code>@RunWith(JukitoRunner.class)
public class MyTest {

    @Inject
    MainService mainService;

    @Test
    public void testMain(){
        mainService.setData(mainService.getSelectedData());
    }
}

public class MainService {

    List&lt;Data&gt; data = new ArrayList&lt;Data&gt;();

    List&lt;Field&gt; fields = new ArrayList&lt;Field&gt;();

    public MainService(){
        /* this.fields is filled here*/
        data.add(/*data obj*/);
        data.add(/*data obj*/);
        data.add(/*data obj*/);
    }

    public List&lt;Data&gt; getSelectedData(){
        /* alghoritm to filter data */
        return data; /*returns List with 1 and 2nd data objects from this.data*/
    }
    private void deleteEl(Field field, Runnable callback){
        fields.remove(field);
        for (ListIterator&lt;Data&gt; i = data.listIterator(); i.hasNext();) {
            Data data = i.next();
            if(data.something()) i.remove();
        }

        if (callback != null) {
            callback.run();
        }
    }

    public void setData(List&lt;Data&gt; selected){
        for(Field field : fields){// checked with debug, this gets executed more than once, why?! It should run only once. ConcurrentModificationException gets thrown here.
            if(field instanceof Object){
                deleteEl(field, new Runnable(){
                    @Override
                    public void run(){
                        create(selected); //won't post create() code, since even commenting this, does not help. Error persists
                    }
                })
            }
        }
    }

}
</code></pre>
",https://stackoverflow.com/questions/45584964/unit-test-loop-gets-executed-more-than-once,"['java', 'unit-testing']",56,TRUE,0,1
JUnit - NoSuchElementException: No line found,"<p>I'm trying to learn unit testing and Maven, to do so I'm using JUnit and writing simple random name generator. I have following class:</p>

<pre><code>public class Database {

  public String readRandomName(String url) throws FileNotFoundException {
     int sum = calculateFileLines(url);
     int lines = (int) (Math.random()*sum);
     File file = new File(url);
     Scanner scanner = new Scanner(file);
     for (int i=0; i&lt;lines;i++){
         scanner.nextLine();
     }
     return scanner.nextLine();
  }

  public int calculateFileLines(String url) throws FileNotFoundException {
    int sum = 0;
    try (Scanner scanner = new Scanner(new File(url))){
        while(scanner.hasNextLine() &amp;&amp; scanner.nextLine().length()!=0){
            ++sum;
        }
    }
    return sum;
  }
}
</code></pre>

<p>When I run simple test like this:</p>

<pre><code>public static void main(String[] args) throws FileNotFoundException {
    Database database = new Database();
    database.readRandomName(""names/maleNamesPL.txt"");
}
</code></pre>

<p>It works perfectly, but when I tried to write JUnit test with assertion there is an unexpected failure which I don't understand. This is test code:</p>

<pre><code>@Test
public void readRandomNameTest() throws FileNotFoundException {
    Database database = new Database();
    Assert.assertNotNull(""Should be some name"", database.readRandomName(""names/maleNamesPL.txt""));
}
</code></pre>

<p>And the results: </p>

<pre><code>Tests in error: 
readRandomNameTest(DatabaseTest): No line found
</code></pre>

<p>I would appreciate any help, thank you!</p>
",https://stackoverflow.com/questions/45653605/junit-nosuchelementexception-no-line-found,"['java', 'maven', 'junit', 'java.util.scanner']",1325,TRUE,0,1
Karma-Jasmine setup for Angular project,"<p>I have an angular(currently @4.0.0) project for which I want to introduce Unit Testing using Karma and Jasmine.</p>

<p>I have set up the appropriate <code>karma.conf.js</code>, <code>spec-bundle.js</code> and <code>package.json</code>. But when I run <code>npm test</code>, this is what is on the console. The test scripts dont seem to be recognized and run.</p>

<p><a href=""https://i.stack.imgur.com/DDsut.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/DDsut.png"" alt=""enter image description here""></a></p>

<p>And these are the warnings on the  console,
<a href=""https://i.stack.imgur.com/X5md3.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/X5md3.png"" alt=""enter image description here""></a></p>

<p>I have a <code>spec</code> file with simple test for <code>app.ts</code>. </p>

<pre><code>import { async, TestBed, ComponentFixture } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

import { App } from './app';
import { AuthorizationService } from '../service/security/authorizationService';


describe('App (templateUrl)', () =&gt; {
   let comp: App;
   let fixture: ComponentFixture&lt;App&gt;;
   let de: DebugElement;
   let el: HTMLElement;

   beforeEach(async(() =&gt; {
     TestBed.configureTestingModule({
       declarations: [App]
     })
       .compileComponents();
   }));

   beforeEach(() =&gt; {
     fixture = TestBed.createComponent(App);
     comp = fixture.componentInstance;
   });

   it('should display app title', () =&gt; {
     fixture.detectChanges();
     expect(comp.appTitle).toContain('Angular');
   });
});
</code></pre>

<p>package.json:</p>

<pre><code>""scripts"": {
""rimraf"": ""rimraf"",
""tslint"": ""tslint"",
""typedoc"": ""typedoc"",
""typings"": ""typings"",
""webpack"": ""webpack"",
""webpack-dev-server"": ""webpack-dev-server"",
""webdriver-manager"": ""webdriver-manager"",
""protractor"": ""protractor"",
""clean"": ""npm cache clean &amp;&amp; npm run rimraf -- node_modules doc typings coverage dist"",
""clean:dist"": ""npm run rimraf -- dist"",
""preclean:install"": ""npm run clean"",
""clean:install"": ""npm set progress=false &amp;&amp; npm install"",
""preclean:start"": ""npm run clean"",
""clean:start"": ""npm start"",
""watch"": ""npm run watch:local"",
""watch:dev"": ""npm run build:dev -- --watch"",
""watch:local"": ""npm run build:local -- --watch"",
""watch:dev:hmr"": ""npm run watch:dev -- --hot"",
""watch:test"": ""npm run test -- --auto-watch --no-single-run"",
""watch:uat"": ""npm run uat -- --auto-watch --no-single-run"",
""watch:prod"": ""npm run build:prod -- --watch"",
""build"": ""npm run build:local"",
""prebuild:dev"": ""npm run clean:dist"",
""build:dev"": ""webpack --config config/webpack.dev.js --progress --profile --colors --display-error-details --display-cached"",
""build:local"": ""webpack --config config/webpack.local.js --progress --profile --colors --display-error-details --display-cached"",
""build:devplus"": ""webpack --config config/webpack.devplus.js --progress --profile --colors --display-error-details --display-cached"",
""build:test"": ""webpack --config config/webpack.test.js --progress --profile --colors --display-error-details --display-cached --bail"",
""build:uat"": ""webpack --config config/webpack.uat.js --progress --profile --colors --display-error-details --display-cached --bail"",
""prebuild:prod"": ""npm run clean:dist"",
""build:prod"": ""webpack --config config/webpack.prod.js --progress --profile --colors --display-error-details --display-cached --bail"",
""server"": ""npm run server:dev"",
""server:dev"": ""webpack-dev-server --config config/webpack.dev.js --inline --progress --profile --colors --watch --display-error-details --display-cached --content-base src/"",
""server:local"": ""webpack-dev-server --config config/webpack.local.js --inline --progress --profile --colors --watch --display-error-details --display-cached --content-base src/"",
""server:dev:hmr"": ""npm run server:dev -- --hot"",
""server:prod"": ""http-server dist --cors"",
""webdriver:update"": ""npm run webdriver-manager update"",
""webdriver:start"": ""npm run webdriver-manager start"",
""lint"": ""npm run tslint 'src/**/*.ts'"",
""pree2e"": ""npm run webdriver:update -- --standalone"",
""e2e"": ""npm run protractor"",
""e2e:live"": ""npm run e2e -- --elementExplorer"",
""pretest"": ""npm run lint"",
""test"": ""karma start config/karma.conf.js"",
""ci"": ""npm run e2e &amp;&amp; npm run test"",
""docs"": ""npm run typedoc -- --options typedoc.json --exclude '**/*.spec.ts' ./src/"",
""start"": ""npm run server:local"",
""start:hmr"": ""npm run server:dev:hmr"",
""postinstall"": ""npm run typings -- install"",
""preversion"": ""npm test"",
""version"": ""npm run build"",
""postversion"": ""git push &amp;&amp; git push --tags""
},

""dependencies"": {
""@angular/common"": ""4.0.0"",
""@angular/compiler"": ""4.0.0"",
""@angular/core"": ""4.0.0"",
""@angular/forms"": ""4.0.0"",
""@angular/http"": ""4.0.0"",
""@angular/platform-browser"": ""4.0.0"",
""@angular/platform-browser-dynamic"": ""4.0.0"",
""@angular/router"": ""4.0.0"",
""@angular/router-deprecated"": ""2.0.0-rc.2"",
""@angular/upgrade"": ""4.0.0"",
""angular2-toaster"": ""1.0.1"",
""core-js"": ""^2.4.1"",
""css-loader"": ""0.23.1"",
""fullcalendar"": ""^2.7.1"",
""hammerjs"": ""^2.0.8"",
""intl"": ""1.2.4"",
""jquery"": ""2.2.2"",
""jquery-ui"": ""1.10.5"",
""lodash"": ""^4.17.4"",
""ng2-auto-complete"": ""^0.7.0"",
""ng2-cookies"": ""^0.1.5"",
""ng2-file-upload"": ""^1.0.0-beta.1"",
""node-sass"": ""^3.8.0"",
""normalize.css"": ""^4.1.1"",
""path-to-regexp"": ""^1.5.3"",
""postcss"": ""^5.0.19"",
""postcss-loader"": ""^0.8.2"",
""primeng"": ""1.0.0-beta.15"",
""primeui"": ""4.1.10"",
""resolve-url-loader"": ""^1.6.0"",
""rxjs"": ""^5.0.1"",
""sass-loader"": ""^3.2.3"",
""style-loader"": ""^0.13.1"",
""tether"": ""^1.2.0"",
""url-loader"": ""^0.5.7"",
""zone.js"": ""^0.8.4""
},
  ""devDependencies"": {
    ""angular2-hmr"": ""~0.5.5"",
    ""awesome-typescript-loader"": ""~0.17.0"",
    ""babel-core"": ""^6.18.2"",
    ""babel-loader"": ""^6.2.8"",
    ""babel-plugin-transform-es2015-modules-commonjs-simple"": ""^6.7.0"",
    ""babel-preset-es2015"": ""^6.1.18"",
    ""babel-preset-es2015-webpack"": ""^6.4.0"",
    ""bootstrap"": ""4.0.0-alpha.2"",
    ""bootstrap-loader"": ""1.0.10"",
    ""codelyzer"": ""0.0.15"",
    ""compression-webpack-plugin"": ""^0.3.1"",
    ""copy-webpack-plugin"": ""^2.1.3"",
    ""css-loader"": ""^0.23.1"",
    ""es6-promise"": ""^3.1.2"",
    ""es6-promise-loader"": ""^1.0.1"",
    ""es6-shim"": ""^0.35.0"",
    ""exports-loader"": ""^0.6.3"",
    ""expose-loader"": ""^0.7.1"",
    ""extract-text-webpack-plugin"": ""^1.0.1"",
    ""file-loader"": ""^0.8.5"",
    ""html-webpack-plugin"": ""^2.15.0"",
    ""http-server"": ""^0.9.0"",
    ""imports-loader"": ""^0.6.5"",
    ""istanbul-instrumenter-loader"": ""^0.2.0"",
    ""jasmine-core"": ""^2.6.2"",
    ""json-loader"": ""^0.5.4"",
    ""karma"": ""^1.6.0"",
    ""karma-chrome-launcher"": ""^0.2.3"",
    ""karma-coverage"": ""^0.5.5"",
    ""karma-jasmine"": ""^0.3.8"",
    ""karma-mocha-reporter"": ""^2.0.0"",
    ""karma-phantomjs-launcher"": ""^1.0.0"",
    ""karma-sourcemap-loader"": ""^0.3.7"",
    ""karma-webpack"": ""1.7.0"",
    ""lodash"": ""^4.6.1"",
    ""moment"": ""^2.11.2"",
    ""node-sass"": ""3.7.0"",
    ""npmconf"": ""2.1.2"",
    ""parse5"": ""^2.1.5"",
    ""phantomjs-polyfill"": ""0.0.2"",
    ""phantomjs-prebuilt"": ""^2.1.7"",
    ""protractor"": ""^3.2.2"",
    ""raw-loader"": ""0.5.1"",
    ""reflect-metadata"": ""^0.1.3"",
    ""remap-istanbul"": ""^0.6.3"",
    ""resolve-url-loader"": ""^1.4.3"",
    ""rimraf"": ""^2.5.2"",
    ""sass-loader"": ""^3.2.0"",
    ""source-map-loader"": ""^0.1.5"",
    ""style-loader"": ""^0.13.1"",
    ""ts-helpers"": ""1.1.1"",
    ""ts-node"": ""^0.7.1"",
    ""tslint"": ""^3.7.1"",
    ""tslint-loader"": ""^2.1.3"",
    ""typedoc"": ""^0.3.12"",
    ""typescript"": ""2.0.3"",
    ""typings"": ""^1.5.0"",
    ""url-loader"": ""^0.5.7"",
    ""webpack"": ""^1.12.14"",
    ""webpack-dev-server"": ""^1.14.1"",
    ""webpack-load-plugins"": ""^0.1.2"",
    ""webpack-md5-hash"": ""^0.0.5"",
    ""webpack-merge"": ""^0.12.0"",
    ""webpack-validator"": ""^1.0.0-beta.4""
  },
  ""repository"": {
    ""type"": ""git"",
    ""url"": ""https://github.com/angularclass/angular2-webpack-starter.git""
  },
  ""bugs"": {
    ""url"": ""https://github.com/angularclass/angular2-webpack-starter/issues""
  },
  ""engines"": {
    ""node"": ""&gt;= 4.2.1"",
    ""npm"": ""&gt;= 3""
  }
}
</code></pre>

<p>karma.conf.js:</p>

<pre><code>module.exports = function(config) {

var testWebpackConfig = require('./webpack.test.js');

  config.set({
    basePath: '',
    frameworks: ['jasmine'],
    exclude: [ ],

files: [ { pattern: 'spec-bundle.js', watched: false } ],

preprocessors: { 'spec-bundle.js': ['coverage', 'webpack', 'sourcemap'] },

webpack: testWebpackConfig,

coverageReporter: {
  dir : 'coverage/',
  reporters: [
    { type: 'text-summary' },
    { type: 'json' },
    { type: 'html' }
  ]
},
webpackServer: { noInfo: true },

reporters: [ 'mocha', 'coverage' ],
port: 9876,

colors: true,
logLevel: config.LOG_INFO,

autoWatch: true,

browsers: [
  'Chrome'
],
singleRun: true

 });

};
</code></pre>

<p>spec-bundle.js:</p>

<pre><code>Error.stackTraceLimit = Infinity;

require('core-js/es6');
require('core-js/es7/reflect');

require('zone.js/dist/zone');
require('zone.js/dist/long-stack-trace-zone');
require('zone.js/dist/proxy'); // since zone.js 0.6.15
require('zone.js/dist/sync-test');
require('zone.js/dist/jasmine-patch'); // put here since zone.js 0.6.14
require('zone.js/dist/async-test');
require('zone.js/dist/fake-async-test');
require('rxjs/Rx');

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

testing.TestBed.initTestEnvironment(
  browser.BrowserDynamicTestingModule,
  browser.platformBrowserDynamicTesting()
);

var testContext = require.context('../src', true, /\.spec\.ts/);

function requireAll(requireContext) {
  return requireContext.keys().map(requireContext);
}

var modules = requireAll(testContext);
</code></pre>
",https://stackoverflow.com/questions/44099264/karma-jasmine-setup-for-angular-project,"['javascript', 'angular', 'karma-runner', 'karma-jasmine', 'jasmine2.0']",667,FALSE,0,0
Cannot add a NOT NULL column with default value NULL,"<p>I'm testing a laravel site using codeception and I've followed the following tute:</p>

<p><a href=""http://www.phplab.info/categories/laravel/how-to-specify-a-separate-database-for-unit-testing-on-laravel-5"" rel=""nofollow noreferrer"">http://www.phplab.info/categories/laravel/how-to-specify-a-separate-database-for-unit-testing-on-laravel-5</a></p>

<p>I'm getting the following error:</p>

<blockquote>
  <p>[Illuminate\Database\QueryException] SQLSTATE[HY000]: General error: 1 Cannot add a NOT NULL column with default value NULL (SQL: alter table ""markers"" add column ""user_id"" integer not null)</p>
</blockquote>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/45729913/cannot-add-a-not-null-column-with-default-value-null,"['php', 'sql', 'laravel', 'testing', 'codeception']",3435,TRUE,-3,1
How can I instantiate a inner public static final class in java from a different package,"<p>I have a use case where I am trying to instantiate an inner public static final class from a different package. I am trying to do this so that I can mock the Response to unit testing. We can use a mock server, however, I just want to use a mock object for this case for speed and more controlled testing. Here is the code snippet below:</p>

<pre><code>public class Http {
  private final HttpClient client;

  @Inject
  Http(HttpClient client) {
    this.client = client;
  }

  public Http.Response get(Http.Request request) {
    try {
      Http.Response response = this.getResponse(this.client.execute(this.createHttpGet(request)));
      return response;
    } catch (IOException var4) {
      throw new RuntimeException(var4);
    } catch (URISyntaxException var5) {
      throw new RuntimeException(var5);
    }
  }

  private Http.Response getResponse(HttpResponse httpResponse) throws IOException {
    Http.Response response = new Http.Response(httpResponse.getStatusLine().getStatusCode());
    response.setMessageBody(EntityUtils.toString(httpResponse.getEntity()));
    return response;
  }

  public static final class Response {
    private final int statusCode;
    private ImmutableMap&lt;String, String&gt; headers;
    private String message;
    private String messageBody;

    Response(int statusCode) {
      this.statusCode = statusCode;
    }

    public int getStatusCode() {
      return this.statusCode;
    }

    public Map&lt;String, String&gt; getHeaders() {
      return this.headers;
    }

    void setHeaders(Map&lt;String, String&gt; headers) {
      this.headers = ImmutableMap.builder().putAll(headers).build();
    }

    public String getMessage() {
      return this.message;
    }

    void setMessage(String message) {
      this.message = message;
    }

    public String getMessageBody() {
      return this.messageBody;
    }

    void setMessageBody(String messageBody) {
      this.messageBody = messageBody;
    }

    public String toString() {
      return String.format(""HttpResponse{statusCode=%d, headers=%s, message='%s', messageBody='%s'}"", this.statusCode, this.headers, this.message, this.messageBody);
    }
  }
}
</code></pre>
",https://stackoverflow.com/questions/47766994/how-can-i-instantiate-a-inner-public-static-final-class-in-java-from-a-different,"['java', 'unit-testing', 'oop', 'mocking']",44,FALSE,0,1
Karma Jasmine unit test for Kendo template,"<p>I am trying to write Karma test for a function which uses a Kendo template Html.</p>

<p>The code goes like this:</p>

<pre><code>$scope.columns = [{ 
    field: gridColumns.STATUS, 
    title: gridColumnsTitle.STATUS, 
    template: $scope.getKendoTemplate($(""#statusTemplate"").html()), 
    width: 80 
}];
</code></pre>

<p>The issue is with HTML template <code>$(""#statusTemplate"").html()</code> which is undefined.
And I get an error like this:</p>

<pre><code>TypeError: Cannot read property 'replace' of undefined
           at Object.compile (app/js/kendo.all.min.js:25:7431)
           at new proxy (wwwroot/lib/jquery/dist/jquery.js:497:14)
           at ChildScope.getKendoTemplate (app/components/test/demo/demo.controller.es5.js:9:22664)
</code></pre>

<p>And the code for #statusTemplate goes like this in Html:</p>

<pre><code>&lt;script type=""text/x-kendo-template"" id=""statusTemplate""&gt;
        &lt;span data-ng-show=""dataItem.active""&gt;On&lt;/span&gt;
        &lt;span data-ng-show=""!dataItem.active""&gt;Off&lt;/span&gt;
&lt;/script&gt;
</code></pre>

<p>Is there a way I could get this unit testing passed. Without much changes to the actual code.</p>
",https://stackoverflow.com/questions/47507201/karma-jasmine-unit-test-for-kendo-template,"['unit-testing', 'jasmine', 'karma-jasmine']",190,TRUE,0,1
Error `The code you are testing needs to make 1 more call(s)` in testify package,"<p>I am using the testify package for the unit testing in golang. My code contains mocking. while running the test it is getting passed for sometimes and showing error <code>The code you are testing needs to make 1 more call(s)</code> for sometimes, I am unable to figure out the reason why is this happening:</p>
<p><img src=""https://i.stack.imgur.com/cXpZl.png"" alt=""enter image description here"" /></p>
<p>I went through this <a href=""https://github.com/stretchr/testify/issues/31"" rel=""nofollow noreferrer"">https://github.com/stretchr/testify/issues/31</a> but did get what is the problem and how it can be solved?</p>
",https://stackoverflow.com/questions/47510225/error-the-code-you-are-testing-needs-to-make-1-more-calls-in-testify-package,"['unit-testing', 'go', 'testify']",6245,TRUE,-2,3
Laravel 5.4 not working on PHP 7.0 due to Doctrine package,"<p>I'm trying to deploy a Laravel application on an AWS PHP 7.0 instance (Elastic Beanstalk, but that doesn't really matter).</p>

<p>I get the following error</p>

<pre><code>+ composer.phar install --no-ansi --no-interaction
Do not run Composer as root/super user! See https://getcomposer.org/root for details
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for doctrine/instantiator 1.1.0 -&gt; satisfiable by doctrine/instantiator[1.1.0].
    - doctrine/instantiator 1.1.0 requires php ^7.1 -&gt; your PHP version (7.0.16) does not satisfy that requirement.
  Problem 2
    - doctrine/instantiator 1.1.0 requires php ^7.1 -&gt; your PHP version (7.0.16) does not satisfy that requirement.
    - phpunit/phpunit-mock-objects 3.4.4 requires doctrine/instantiator ^1.0.2 -&gt; satisfiable by doctrine/instantiator[1.1.0].
    - Installation request for phpunit/phpunit-mock-objects 3.4.4 -&gt; satisfiable by phpunit/phpunit-mock-objects[3.4.4].
 (Executor::NonZeroExitStatus)
</code></pre>

<p>Any ideas how can I suppress this or get around it on PHP 7.0?</p>

<p>My composer.json</p>

<pre><code>{
    ""name"": ""myapp"",
    ""description"": ""My App."",
    ""keywords"": [""framework"", ""laravel"", ""lumen""],
    ""license"": ""MIT"",
    ""type"": ""project"",
    ""require"": {
        ""php"": ""&gt;=5.6.4"",
        ""laravel/lumen-framework"": ""5.4.*"",
        ""vlucas/phpdotenv"": ""~2.2"",
        ""romanpitak/nginx-config-processor"": ""^0.2.1"",
        ""symfony/stopwatch"": ""^3.2"",
        ""comodojo/zip"": ""^2.1"",
        ""riimu/kit-pathjoin"": ""1.*"",
        ""aws/aws-sdk-php"": ""^3.25"",
        ""spatie/url"": ""dev-master""
    },
    ""require-dev"": {
        ""fzaninotto/faker"": ""~1.4"",
        ""phpunit/phpunit"": ""~5.0"",
        ""mockery/mockery"": ""~0.9""
    },
    ""autoload"": {
        ""psr-4"": {
            ""App\\"": ""app/""
        }
    },
    ""autoload-dev"": {
        ""classmap"": [
            ""tests/"",
            ""database/""
        ]
    },
    ""scripts"": {
        ""post-root-package-install"": [
            ""php -r \""copy('.env.example', '.env');\""""
        ]
    },
    ""minimum-stability"": ""dev"",
    ""prefer-stable"": true
}
</code></pre>

<p>P.s. I am not using any unit testing. I tried to get rid of the ""require-dev"" packages and still the same error.</p>
",https://stackoverflow.com/questions/45927432/laravel-5-4-not-working-on-php-7-0-due-to-doctrine-package,"['php', 'laravel', 'amazon-web-services', 'laravel-5', 'php-7']",2584,TRUE,0,1
Mocking lombok @Getter fields with Mockito,"<p>I am using <code>@Getter</code> notation with Lombok on some of my static fields as such:</p>

<pre><code>public class A {

    @Getter protected static MyClass myClass;
}
</code></pre>

<p>While unit testing, I have to mock the value of these static fields for a section of code that does:</p>

<pre><code>MyClass.getMyClass();
</code></pre>

<p>To mock, I'm doing:</p>

<pre><code>mock(MyClass.class);
when(MyClass.getMyClass()).thenReturn(...);
</code></pre>

<p>However, such mock gives below error.</p>

<pre><code> [testng] org.mockito.exceptions.misusing.MissingMethodInvocationException:
 [testng] when() requires an argument which has to be 'a method call on a mock'.
 [testng] For example:
 [testng]     when(mock.getArticles()).thenReturn(articles);
 [testng]
 [testng] Also, this error might show up because:
 [testng] 1. you stub either of: final/private/equals()/hashCode() methods.
 [testng]    Those methods *cannot* be stubbed/verified.
 [testng]    Mocking methods declared on non-public parent classes is not supported.
 [testng] 2. inside when() you don't call method on mock but on some other object.
</code></pre>

<p>I must be hitting condition 2, but I'm not understanding how I am not ""calling method on mock"". </p>

<p>Has anyone successfully mocked Lombok getters?</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/46598432/mocking-lombok-getter-fields-with-mockito,"['java', 'unit-testing', 'mocking', 'mockito', 'lombok']",4348,TRUE,3,1
Django - null value in column &quot;user_id&quot; violates not-null constraint,"<p>I keep getting this error after countless trials:</p>

<pre><code>Traceback (most recent call last):
    File ""C:\...\tests.py"", line 82, in test_profile_creation
       w = self.create_profile()
    File ""C:\...\tests.py"", line 78, in create_profile
       self.user = Profile.objects.create(id=1)
    ...
    django.db.utils.IntegrityError: null value in column ""user_id"" violates not-null constraint
    DETAIL:  Failing row contains (1, null).
</code></pre>

<p>I try to cover these area:</p>

<p><a href=""https://i.stack.imgur.com/d11l6.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/d11l6.png"" alt=""enter image description here""></a></p>

<p>I am not sure how to proceed testing with other two methods as marked ( <code>get_screen_name() and get_association_name()</code>) so guidance would be helpful.</p>

<p>It is my first time in unit testing and still fresh on this so appreciate your guidance, folks!</p>

<p><strong>EDIT 2</strong></p>

<p>tests.py</p>

<pre><code>  def create_profile(self):
    self.asoc = Association.objects.create(id=2)
    self.admin = Administrator.objects.create(id=1, association=self.asoc)
    self.user = Profile.objects.create(id=2, user=self.admin)
    return Profile.objects.get(user=self.user, administrator=self.admin)

  Traceback (most recent call last):
    File ""C:\...\tests.py"", line 83, in test_profile_creation
        w = self.create_profile()
    File ""C:\...\tests.py"", line 79, in create_profile
        self.user = Profile.objects.create(id=2, user=self.admin)
    django.db.utils.IntegrityError: duplicate key value violates unique constraint ""Profile_pkey""
     DETAIL:  Key (id)=(2) already exists.
</code></pre>

<hr>

<p><strong>EDIT 3</strong></p>

<pre><code> def create_profile(self):
    self.asoc = Association.objects.create()
    self.admin = Administrator.objects.create(association=self.asoc)
    self.user = Profile.objects.create(user=self.admin)
    return Profile.objects.get(user=self.user, administrator=self.admin)


  Traceback (most recent call last):
     File ""C:\..\tests.py"", line 83, in test_profile_creation
        w = self.create_profile()
     File ""C:\...\tests.py"", line 79, in create_profile
        self.user = Profile.objects.create(user=self.admin)
     django.db.utils.IntegrityError: duplicate key value violates unique constraint ""Profile_user_id_key""
     DETAIL:  Key (user_id)=(2) already exists.
</code></pre>

<hr>

<p><strong>EDIT 4</strong></p>

<pre><code> def create_profile(self):
    self.asoc = Association.objects.create(id=7)
    self.admin = Administrator.objects.create(id=6, association=self.asoc)
    self.user = Profile.objects.create(id=5)
    return Profile.objects.get(user=self.user, administrator=self.admin)


  Traceback (most recent call last):
     File ""C:\..\tests.py"", line 83, in test_profile_creation
        w = self.create_profile()
     File ""C:\...\tests.py"", line 79, in create_profile
        self.user = Profile.objects.create(id=5)
     ...
     django.db.utils.IntegrityError: null value in column ""user_id"" violates not-null constraint
     DETAIL:  Failing row contains (5, null).
</code></pre>

<hr>

<p><strong>EDIT 5</strong></p>

<pre><code> def create_profile(self):
    self.asoc = Association.objects.create(id=7)
    self.admin = Administrator.objects.create(id=6, association=self.asoc)
    self.user = Profile.objects.create(id=self.admin)        
    return Profile.objects.get(user=self.user, administrator=self.admin)


  Traceback (most recent call last):
     File ""C:\..\tests.py"", line 83, in test_profile_creation
        w = self.create_profile()
     File ""C:\...\tests.py"", line 79, in create_profile
        self.user = Profile.objects.create(id=self.admin)
     ...
     TypeError: int() argument must be a string, a bytes-like object or a number, not 'Administrator'
</code></pre>

<hr>

<p><strong>EDIT 6</strong></p>

<pre><code> def create_profile(self):
    self.asoc = Association.objects.create(id=7)
    self.admin = Administrator.objects.create(id=6, association=self.asoc)
    self.user = Profile.objects.create(id=self.admin.id)        
    return Profile.objects.get(user=self.user, administrator=self.admin)


  Traceback (most recent call last):
     File ""C:\..\tests.py"", line 83, in test_profile_creation
        w = self.create_profile()
     File ""C:\...\tests.py"", line 79, in create_profile
        self.user = Profile.objects.create(id=self.admin.id)
     ...
     django.db.utils.IntegrityError: null value in column ""user_id"" violates not-null constraint
     DETAIL:  Failing row contains (6, null).
</code></pre>

<hr>

<p>tests.py</p>

<pre><code>class ProfileTest(TestCase):
    def create_profile(self):
        self.asoc = Association.objects.create(id=2)
        self.admin = Administrator.objects.create(id=1, association=self.asoc)
        self.user = Profile.objects.create(id=1)
        return Profile.objects.get(user=self.user, administrator=self.admin)

    def test_profile_creation(self):
        w = self.create_profile()
        self.assertTrue(isinstance(w, Profile))
        self.assertEqual(w.__str__(), w.user.username)
</code></pre>

<hr>

<p>models.py</p>

<pre><code>class Administrator(AbstractUser):
   ...
   association = models.ForeignKey(Association)


   class Meta:
       db_table = 'Administrator'

   def __str__(self):
      return self.username

   def __unicode__(self):
      return self.username



class Profile(models.Model):
   user = models.OneToOneField(Administrator)

   class Meta:
      db_table = 'Profile'

   def __str__(self):
       return self.user.username

   def get_screen_name(self):
       try:
           if self.user.get_full_name():
               return self.user.get_full_name()
           else:
               return self.user.username
       except:
           return self.user.username


    def get_association_name(self):
       try:
           if self.user.association:
               return self.user.association
           else:
               return self.user.username
       except:
           return self.user.username


 class Association(models.Model):
       asoc_name = models.CharField(max_length=50, null=True, blank=True, unique=True)

       class Meta:
          db_table = 'Association'

       def __str__(self):
          return self.asoc_name

       def __unicode__(self):
          return self.asoc_name
</code></pre>
",https://stackoverflow.com/questions/43926397/django-null-value-in-column-user-id-violates-not-null-constraint,"['django', 'python-3.x', 'unit-testing']",4192,TRUE,0,2
Google-test : Comparing file outputted by unit-tested function with reference file,"<p>I am unit-testing a function whose purpose is to store data under a certain format into a file. I want to unit-test this function to make sure that the file it outputs indeed matches a reference file. Is there a way to do that with the google test library directly? Or do I have to implement a function to compare two files myself?</p>
",https://stackoverflow.com/questions/46517251/google-test-comparing-file-outputted-by-unit-tested-function-with-reference-fi,"['c++', 'file', 'googletest']",566,FALSE,0,0
object&#39; does not contain a definition for MainTypeCode for dynamic data,"<p>This below query return some mock data for unit testing. </p>

<pre><code>var colorsList = (IEnumerable&lt;dynamic&gt;)colorsRepository.GetColorsList().Result;
</code></pre>

<p>It given the result as dynamic object </p>

<p><a href=""https://i.stack.imgur.com/nSdWA.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/nSdWA.jpg"" alt=""enter image description here""></a></p>

<p>I want to get <code>MainTypeCode</code> value only. But it is showing <strong>object' does not contain a definition for MainTypeCode</strong></p>

<pre><code>colorsList.Select(cl =&gt; (dynamic)cl.MainTypeCode);
</code></pre>

<h2>Edit:</h2>

<blockquote>
  <p>And let me know how to arrange  dummy/mock dynamic data to execute the query?</p>
</blockquote>

<p>and <code>colorsRepository.GetColorsList().Result;</code> is returning below way. Shall I change the mock data to run the query?</p>

<pre><code> public static IEnumerable&lt;dynamic&gt; GetColorsList()
        {
            List&lt;dynamic&gt; colours = new List&lt;dynamic&gt;();
            for (int i = 0; i &lt; 1; i++)
            {
                colours.Add((dynamic)new
                {
                    MainTypeCode = 1,
                    DoorCode = ""001""
                });
            }
            return colours.AsEnumerable();
        }
</code></pre>
",https://stackoverflow.com/questions/47813531/object-does-not-contain-a-definition-for-maintypecode-for-dynamic-data,"['c#', 'linq', 'dynamic']",990,TRUE,0,2
testing a vriable scoped whose scope is inside a function in JavaScript,"<p>I am unit testing my ionic app with <code>Jasmine</code>. I have a service function to handle file upload.</p>

<pre><code>  fileUpload(filePath: string,apiEndpoint: string){
    const fileTransfer = new Transfer();
    let fileName = filePath.substr(filePath.lastIndexOf('/') + 1);
    let options = Object.assign( this.httpHeader(),{chunkedMode: false, fileName: fileName});
    return fileTransfer.upload(filePath, apiEndpoint, options)
    .then((data) =&gt; {
      return data;
    }).catch(this.handleError);
  }
</code></pre>

<p>The scope of <code>fileTransfer</code> is inside the function, so it is not available in the test.<code>fileTransfer.upload</code> call would fail inside the function as it is a <code>cordova</code> library. </p>

<pre><code>  it('updateImage updates the image of user',(done)=&gt;{
    auth.fileUpload(""path"",""url"").then((data)=&gt;{
      done();
    })
  })
</code></pre>

<p>One possible solution which I can think of is <code>this.fileTransfer = new Transfer();</code> . Is there any other way to mock the library or intercept it? </p>
",https://stackoverflow.com/questions/41790797/testing-a-vriable-scoped-whose-scope-is-inside-a-function-in-javascript,"['javascript', 'angularjs', 'jasmine']",38,FALSE,0,1
Syntax of Javascript TAPE unit test,"<p>I'm new to unit testing for javascript and node-js.  I'm trying to figure out the syntax of the following TAPE unit test:</p>

<pre><code>test('player has computed fields', (assert) =&gt; {
    const playerData = {
        firstName: 'Test',
        lastName: 'Testerton'
    };

  var player = new Player(playerData);

  assert.equal(`${player.fullName}`,
                `${playerData.firstName} ${playerData.lastName}`,
                'has full name');
  assert.end();
});
</code></pre>

<p>I understand basically what's going on, but the syntax is hard to reference anywhere.  For example is the '=>' a conditional or fancy arrow syntax format?</p>

<p>This would read to me as make sure it's not empty if this was a conditional.</p>
",https://stackoverflow.com/questions/46844732/syntax-of-javascript-tape-unit-test,"['javascript', 'node.js', 'unit-testing']",71,TRUE,0,1
Integration testing Android,"<p>I'm new to testing on Android. I see a lot of articles and tutorial about unit testing and with end-to-end testing (with espresso). It's ok. But what about integration testing ?</p>

<p>For the exemple, I use Firebase Database for my app. Is it possible to do this kind of test in the instrumentation test :</p>

<pre><code>@Test
public void tryFirebaseTest() throws FieldRequiredException, InvalidPhoneException, InvalidEmailException, InterruptedException {

    UserManager userManager = new UserManager(new FIRUserStorage(FirebaseDatabase.getInstance().getReference()));
    userManager.createUser(""test@test.com"", ""test"", ""+4778787"", """", new CreateUserCallback() {
        @Override
        public void userCreated(User user) {
            assertNotNull(user);
        }

        @Override
        public void userExistError() {
            fail();
        }

        @Override
        public void userDatabaseError(String errorMessage) {
            fail();
        }
 });

}
</code></pre>

<p>In this case, the test don't get in the callback.</p>
",https://stackoverflow.com/questions/41585530/integration-testing-android,"['android', 'unit-testing', 'testing', 'integration-testing', 'android-testing']",547,FALSE,0,1
Why can&#39;t smoke testing be done by developer?,"<p>By reference from : </p>

<p><a href=""http://istqbexamcertification.com/what-is-smoke-testing-when-to-use-it-advantages-and-disadvantages-2/"" rel=""nofollow noreferrer"">http://istqbexamcertification.com/what-is-smoke-testing-when-to-use-it-advantages-and-disadvantages-2/</a></p>

<p>Smoke testing is used in the following scenarios:</p>

<ul>
<li><p>It is done by developers before giving build to the testing team.</p></li>
<li><p>It is done by the testers before they start the detailed testing.</p></li>
</ul>

<p>Question is, can it be compromised, just because an ""agile-developer"" has done ""Unit Testing"" ?</p>
",https://stackoverflow.com/questions/43907200/why-cant-smoke-testing-be-done-by-developer,"['testing', 'software-quality', 'agile-processes', 'smoke-testing']",145,TRUE,-1,1
testing if proper route is called after clicking on a button,"<p>I'm new to unit testing, tried reading several tuorials as how to test ng2 components, routers etc.. But still I'm no wiser as how to accomplish this.</p>

<p>I'd like to test whether the ""login"" route is activated after clicking on <code>#logout</code> button.</p>

<p>Here's what I got so far, but it's <s>not working at all</s> partially working. When I call the <code>spy.calls.first()</code> I get <code>undefined</code>, however when I call <code>spy.calls.all()</code> I can see the expected result.  </p>

<pre><code>import { ComponentFixture, TestBed, inject } from '@angular/core/testing';
import { By }              from '@angular/platform-browser';
import { Router } from '@angular/router';
import { DebugElement }    from '@angular/core';
import { async } from '@angular/core/testing';

import { HomeComponent } from './home.component';

import { click } from '../testing/index'

class RouterStub {
  navigate(url: string) { return url; }
}

describe('HomeComponent', () =&gt; {

  let comp:    HomeComponent;
  let fixture: ComponentFixture&lt;HomeComponent&gt;;
  let de:      DebugElement;
  let el:      HTMLElement;
  let logoutBtnEl: HTMLElement;

  // async beforeEach
  beforeEach( async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ HomeComponent ], // declare the test component
      providers: [
        { provide: Router,      useClass: RouterStub }
      ]
    })
    .compileComponents();  // compile template and css
  }));


  // synchronous beforeEach
  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(HomeComponent);
    comp = fixture.componentInstance; // BannerComponent test instance

    de = fixture.debugElement.query(By.css('h1'));  // query for the title &lt;h1&gt; by CSS element selector
    el = de.nativeElement;
    logoutBtnEl = fixture.debugElement.query(By.css('#logout')).nativeElement;
    fixture.detectChanges(); // trigger initial data binding
  });

  it('should display contain \'Welcome\' in title', () =&gt; {
    expect(el.textContent).toContain(""Welcome"");
  });

  it('should tell ROUTER to navigate when logout clicked',
    inject([Router], (router: Router) =&gt; {
        const spy = spyOn(router, 'navigate');
        click(logoutBtnEl);
        console.log(spy.calls.first())
        const navArgs = spy.calls.first().args[0];
        expect( navArgs ).toBe('login', 'should nav to login screen')
    }
  ));


});
</code></pre>
",https://stackoverflow.com/questions/41632996/testing-if-proper-route-is-called-after-clicking-on-a-button,"['angularjs', 'angular', 'jasmine', 'karma-jasmine', 'router']",2394,FALSE,2,1
Mock vs Spy in Angular,"<p>I'm new to Angular and am working on unit testing.</p>

<p>I'm trying to confirm my understanding of Fakes vs Spies (spyOn).</p>

<p>My understanding is that Fakes let you mock up data that is not really being returned from a service. It's just simulating like it is passing from a service.</p>

<p>Spies on the other hand let you actually call, or spy on, a service and get back a real result to compare in your test.</p>

<p>Am I correct?</p>
",https://stackoverflow.com/questions/44074764/mock-vs-spy-in-angular,"['angular', 'typescript', 'jasmine']",5204,TRUE,8,3
Should all classes have a .equals and .hashcode method?,"<p>I'm working on a unit testing project where the asserts call the .equals method. However the people on the project before didn't generate these methods.</p>

<p>Is it considered best practice to auto generate these methods as you code? Should all coders be doing this?</p>

<p>I was searching for more information on the .equals and .hashcode method and most of them seem to be geared towards how to implement or override them.</p>
",https://stackoverflow.com/questions/44205458/should-all-classes-have-a-equals-and-hashcode-method,"['java', 'methods', 'equals', 'hashcode']",1914,TRUE,2,2
Python unit test with coverage cross references?,"<p>Which unit testing tool in Python that can generate cross-references in coverage reports? For example, it can say for line 4567 in <code>foo.py</code> was hit by tests A, B, and C.</p>

<p>I've tried <a href=""https://pypi.python.org/pypi/nose-cov/"" rel=""nofollow noreferrer"">nose-cov</a> but in its HTML report it only colors the lines to indicate they were hit. However it does not say which unit test that exercises those lines.</p>

<p>Preferably a tool one that works with Python 3.</p>
",https://stackoverflow.com/questions/44493715/python-unit-test-with-coverage-cross-references,"['python', 'unit-testing', 'test-coverage']",63,FALSE,2,0
Unit Test - call a function in two test cases if the function is called only once in productive code,"<p>maybe there is someone who has experience with Unit Testing with <em>cpputest</em>.</p>

<p>I have something like this:</p>

<p><strong>Source code Under Test:</strong></p>

<pre><code>main_function()
{
   static int8 is_functioncalled = 1;

   if (is_functioncalled){
   my_local_function();
   is_functioncalled = 0
   }
</code></pre>

<p><strong>UNIT Test Environment:</strong></p>

<pre><code>TEST(TESTGROUP,TEST_CASE1){

   //Some Unit Test checks of my_local_function()

   main_function();
}

TEST(TESTGROUP,TEST_CASE2){

   //Some other Unit Test stuff

   main_function();        // --&gt; my_local_function() will not be called in this test case because it's called already before
</code></pre>

<p>}</p>

<p>I need in TEST_CASE2 the function <em>my_local_function()</em> to be called again. This function is indirectly called through the public interface <em>main_function()</em> which can be called directly within the Unit Test. Does anybody have an idea how to do this in generally or in <em>cpputest</em> environment ?</p>
",https://stackoverflow.com/questions/43224464/unit-test-call-a-function-in-two-test-cases-if-the-function-is-called-only-onc,"['unit-testing', 'cpputest']",485,TRUE,2,2
How to mock method that called in other method while using Spring Dependency Injection?,"<p>I have something like this:</p>

<pre><code>public class Class1 {
    @Autowired
    Class2 class2;

    public Object class1Method {
        // Do something
        Object obj = class2.class2Method(arg);
        // Do something with obj
        return somthing;
    }
}
</code></pre>

<p>I am doing unit testing to Class1 and I want to mock the class2Method. I tried to find solution and I found this:</p>

<p><a href=""https://stackoverflow.com/questions/5920153/test-class-with-a-new-call-in-it-with-mockito"">Test class with a new() call in it with Mockito</a></p>

<p>I understood that this solution works if I do new instance of Class2 in the class1Method, but in my case I use Spring Dependency Injection and I can't figure out how to this.</p>
",https://stackoverflow.com/questions/42693486/how-to-mock-method-that-called-in-other-method-while-using-spring-dependency-inj,"['java', 'spring', 'unit-testing', 'junit', 'mockito']",6397,TRUE,2,3
Junit testing for a function,"<p>I have a confusion regarding Junit testing.For some functions(add function) with closed business logic we can make unit testing by asserting the function.</p>

<p>For example</p>

<pre><code>public int add(int a,int b){
  int c = a+b;
  return c;
}
</code></pre>

<p>But for some function(as below example) in a route what methodology we have to do.</p>

<p>For example</p>

<pre><code>public int foo(int totalnum){
  Zoo soo = new Zoo();
  int giraffNumber = soo.giraffe(totalnum);//here we are calling another method
  return giraffNumber;
}
</code></pre>

<p>For these kind of methods what approach we have to do.Does we need to write another class.</p>

<p>Can anybody please advise me with an example. </p>
",https://stackoverflow.com/questions/44351002/junit-testing-for-a-function,"['java', 'mockito']",283,TRUE,2,2
Visual Studio Code: Unit test projects,"<p>I know how to setup a separate project in regular Visual Studio: just add another project to the solution, and set the startup project to your asp.net project.</p>

<p>However, in VisualStudio Code, everything is more file and convention based. I am not sure how to include unit testing practices within visual studio code.</p>

<p><strong>TL;DR:</strong> what is the strategy for seperating your unit tests from your core projects code?</p>
",https://stackoverflow.com/questions/47342950/visual-studio-code-unit-test-projects,"['asp.net-core', 'visual-studio-code', 'nunit']",1666,FALSE,2,0
How to unit test a helper funtion call in a collection in C# using Mock,"<p>I 'm new to unit testing and I want to create a unit test for the following code: </p>

<pre><code>   public IEnumerable&lt;Product&gt; CreateProductList(
       IEnumerable&lt;int&gt; productsIds, IEnumerable&lt;Product&gt; products)
    {
        var productsList = productsIds.GroupJoin(
            inner: products, 
            outerKeySelector: x =&gt; x, 
            innerKeySelector: y =&gt; y.Id,
            resultSelector: (x, y) =&gt; _productServiceHelper.
            FactoryProduct(x, y.FirstOrDefault(k =&gt; k.Id == x))).ToList();

        return productsList;
    }
</code></pre>

<p>The unit test that I have written so far is trying to use MockSequence but unsuccessfully: </p>

<pre><code>   [Test, TestCaseSource(nameof(TestCases_CreateProductList_SomeMissingIds))]
    public void CreateProductList_SomeMissingIds_ReturnListContainingMissingOnes
        (IEnumerable&lt;int&gt; listWithRequiredProductsIds, IEnumerable&lt;Product&gt; listMissingIds,
        IEnumerable&lt;Product&gt; expectedListContainingAllRequired)
    {
        //_mockProductServiceHelper.InSequence(sequence).Setup(x =&gt; 
        //    x.FactoryProduct(It.IsAny&lt;int&gt;(), It.IsAny&lt;Product&gt;())).Returns(()=&gt; expectedListContainingAllRequire(x =&gt; x));

        //expectedListContainingAllRequired.ToList()
           // .Select(x =&gt; _mockProductServiceHelper.InSequence(sequence)
                       // .Setup(y =&gt; y.FactoryProduct(It.IsAny&lt;int&gt;(), It.IsAny&lt;Product&gt;()))
                    //.Returns(x));
        //expectedListContainingAllRequired.
        var result = _productService.CreateProductList(listWithRequiredProductsIds,
                        listMissingIds);


        var jsonResult = JsonConvert.SerializeObject(result);
        var jsonExpectedListContainingAllRequired = JsonConvert.SerializeObject
                                        (expectedListContainingAllRequired);
        //_mockProductServiceHelper.Verify(x =&gt; x.FactoryProduct(),Times.Once);

        //Assert.That(result.Count(), Is.EqualTo(expectedListContainingAllRequired.Count()));
        Assert.That(result.Count(), Is.EqualTo(expectedListContainingAllRequired.Count()));
        Assert.That(jsonResult, Is.EqualTo(jsonExpectedListContainingAllRequired));
    }

    public static IEnumerable TestCases_CreateProductList_SomeMissingIds
    {
        get
        {
            yield return DataCases_CreateProductList_SomeMissingIds(
                new List&lt;int&gt; { 1, 2 }, new List&lt;int&gt; { 1 });
            yield return DataCases_CreateProductList_SomeMissingIds(
                new List&lt;int&gt; { 1, 2, 3, 4 }, new List&lt;int&gt; { 1, 2 });
        }
    }

    private static TestCaseData DataCases_CreateProductList_SomeMissingIds
        (IEnumerable&lt;int&gt; productIDs, IEnumerable&lt;int&gt; productObjects)
    {
        var productListObjects = productObjects.Select(CreateMockObject);

        var expectedProductList = productIDs.Select(CreateMockObject);

    return new TestCaseData(productIDs, productListObjects, expectedProductList);
    }

    private static Product CreateMockObject(int x)
    {
        return new Product
        {
            Category = new Category { Id = 1, Name = ""padrao"" },
            Name = ""Product "" + x,
            Description = ""Any Description "" + x,
            Creation = DateTime.Now.Date,
            Launch = DateTime.Now.Date,
            Price = x * 2
    };
    }
</code></pre>

<p>I have tried so many things but apparently nothing works. I left some paths that I tried to follow commented.</p>

<p>Does anybody have a suggestion or an example that helps to accomplish testing my method?</p>
",https://stackoverflow.com/questions/45680366/how-to-unit-test-a-helper-funtion-call-in-a-collection-in-c-using-mock,"['c#', 'moq']",82,FALSE,1,0
The method in the Type is not applicable for the arguments for varargs method upgrading to Java 1.8,"<p>I am using Mocikto framework (<em>version 1.9.5</em>) in my project for unit testing with Java 1.7 now I am migrating my project to build and run with <strong>Java 1.8</strong>.</p>

<p>In one of my unit test I am trying to mock following method </p>

<pre><code>public &lt;T&gt; List&lt;T&gt; myMethod(final String sql, final MyMapper&lt;T&gt; MyMapper, final Argument... args) 
</code></pre>

<p>with this code </p>

<pre><code>String learningId = ""testLeaId"";
String catalogId = ""testCatId"";
List&lt;String&gt; returnList = new ArrayList&lt;String&gt;();
returnList.add(catalogId);
when(myService.myMethod(Mockito.anyString(), Mockito.any(MyMapper.class), (Argument[]) Mockito.anyVararg())).thenReturn(returnList);
</code></pre>

<p>This code works fine with <em>Java 1.7</em> now when I upgraded my Java version to 1.8 in my pom.xml I am getting following error...</p>

<pre><code>[ERROR] The method myMethod(String, MyMapper&lt;T&gt;, Argument...) in the type MyService is not applicable for the arguments (String, MyMapper, Argument)
        C:\somepath\MyDaoTest.java:59
</code></pre>

<p>Can any one help me to solve this error ? Thanks </p>
",https://stackoverflow.com/questions/42555707/the-method-in-the-type-is-not-applicable-for-the-arguments-for-varargs-method-up,"['java', 'java-8', 'mockito']",836,TRUE,7,2
"Expression has changed after it was checked, getting error in testing an angular 2 component with jasmine","<p>I am getting an error while testing a component that is receiving an observable from the service, I have tried to mock that behaviour in the spec but I am getting the following error: Expression has changed after it was checked, previous vale '', current value: [object Object]. Could you please help me with this. My spec file is as follows: </p>

<pre><code>import { ManualProcessService } from '../../services/manual-process.service';
import { ManualProcessComponent } from './manual-process.component';
import { MANUALPROCESSMOCKDATA } from '../../shared/mocks/mock-manualprocessdata';
import {DataTableModule, SharedModule, DropdownModule as PrimeNgDropDownModule, CheckboxModule, InputTextModule} from 'primeng/primeng';
import {MenuModule} from 'primeng/components/menu/menu';
import {DropdownModule} from 'ng2-bootstrap';
import { PopoverModule } from 'ng2-popover';
import {Observable} from 'rxjs/Observable';
import { IManualProcessData} from '../../models/manual-process.model';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {
  async,
  TestBed,
  fakeAsync,
  tick,
} from '@angular/core/testing';

class MockManualProcessService {

  getManualProcessData(): Observable&lt;IManualProcessData&gt; {
      return Observable.of(MANUALPROCESSMOCKDATA);
  }
}

describe('Testing Manual Process Component', () =&gt; {

  let fixture,
  event = {
    first: 0,
    rows: 10
  }, 
  manualProcessService;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [
        ManualProcessComponent
      ],
      providers: [
        { provide: ManualProcessService, useClass: MockManualProcessService }
      ],
      imports: [
        FormsModule, 
        ReactiveFormsModule,
        DataTableModule,
        SharedModule,
        PopoverModule,
        PrimeNgDropDownModule,
        DropdownModule.forRoot(),
        CheckboxModule,
        InputTextModule,
        MenuModule
    ],
    });
    fixture = TestBed.createComponent(ManualProcessComponent);
    manualProcessService = TestBed.get(ManualProcessService);
    spyOn(manualProcessService, 'getManualProcessData').and.returnValue(Observable.of(MANUALPROCESSMOCKDATA));
    fixture.detectChanges();
  });

  it('Filters should be reset', (done) =&gt; {
    fixture.componentInstance.clearFilters()
    fixture.detectChanges();
    expect(fixture.componentInstance.filterBy.length).toBe(0);
    done();
  })


  it('Should load list of manual process files', fakeAsync(() =&gt; {
    fixture.componentInstance.loadData(event);
    tick();
    fixture.detectChanges();
    expect(fixture.componentInstance.filterBy.length).toBe(10);
  }));
});
</code></pre>

<p>I am new to angular 2 and unit testing. Can someone guide, what am I doing wrong.</p>
",https://stackoverflow.com/questions/42383117/expression-has-changed-after-it-was-checked-getting-error-in-testing-an-angular,"['angular', 'typescript', 'jasmine', 'karma-jasmine']",18447,TRUE,7,5
Global Scope for Mock HTTPContext - CloudService Project?,"<p>I'm trying to set up a Unit Testing Framework for my WebRole project. I created a mock HTTP context and attached it to the controller that I'm trying to test as such:</p>

<pre><code>var fakeHttpContext = new Mock&lt;HttpContextBase&gt;();
var fakeIdentity = new GenericIdentity(username);
var principal = new GenericPrincipal(fakeIdentity, null);

fakeHttpContext.Setup(t =&gt; t.User).Returns(principal);
var controllerContext = new Mock&lt;ControllerContext&gt;();
controllerContext.Setup(t =&gt; t.HttpContext).Returns(fakeHttpContext.Object);

var controller = new HomeController();
controller.ControllerContext = controllerContext.Object;
</code></pre>

<p>My question is instead of attaching the mock context to one controller, can I mock up HTTP context for the project on a global scope, so all controller and utility classes have access to the mock HTTP context?</p>

<pre><code>//Mock Context is attached to this controller. When Membership provider is accessed 
//from inside the controller it works fine. However when Membership Provider 
//is used from outside the Controller it returns null. 
public void controlerMethodinHomeController()
{ 
    //Returns Null
    var userID = Utility.GetUserId();

    //Returns valid UserID
    var userID = Membership.GetUser(User.Identity.Name).ProviderUserKey;
}

///Utility Class
public static Guid GetUserId()
{
  var user = Membership.GetUser();
  return user.ProviderUserKey
}
</code></pre>
",https://stackoverflow.com/questions/44248774/global-scope-for-mock-httpcontext-cloudservice-project,"['c#', 'unit-testing', 'azure', 'moq', 'azure-web-roles']",180,FALSE,1,0
How to keep test coverage high when mocking?,"<p>Let's say I have this object which is a core part of my system, and most of its work is to communicate with a remote agent - send tasks and get responses:</p>

<pre><code>class AgentAPI:
    ... # Constructor etc.

    def do_foo(self, args):
        .... # Send data and wait for response
        return result

    def do_bar(self, args):
        .... # Send data and wait for response
        return result
</code></pre>

<p>The way I would go about unit-testing this object is with a mock, right?<br>
So:</p>

<pre><code>def test_agent_api_foo():
    agent_api = AgentAPI(someargs)
    agent_api.do_foo = Mock()
    .... # test logic
</code></pre>

<p>That means the methods are not really executed, of course...</p>

<p>So how do I keep my unit-tests reliable on highly distributed systems?</p>
",https://stackoverflow.com/questions/46889084/how-to-keep-test-coverage-high-when-mocking,"['python', 'unit-testing', 'mocking']",48,FALSE,1,0
Some clarifications about using H2 with junit?,"<p>The below gives me: </p>

<blockquote>
  <p>org.h2.jdbc.JdbcSQLException: Table ""FOO"" already exists; SQL
  statement</p>
</blockquote>

<p>Which has me confused and hoping for a couple of clarifiactions.</p>

<p>When is the H2 server started/shutdown, by <code>getConnection</code> and <code>close</code>?</p>

<p>Why does the <code>already exists</code> occur? When the H2 server starts, is the schema persisted from previous sessions?</p>

<p>Any best practice recommendations for setting up a test schema and data set in H2 for usage in database unit testing?</p>

<pre><code>public class MyTest {
    @Before
        public void setUp() throws ClassNotFoundException, SQLException {
            try {
                   Class.forName(""org.h2.Driver"");
                    Connection conn = DriverManager.getConnection(""jdbc:h2:~/test;MODE=Oracle"", ""sa"", """");
                    // add application code here


                    Statement statement =conn.createStatement();
                    statement.execute(""create table foo (id integer)"");
                    conn.commit();

                    ResultSet rs = statement.executeQuery(""select * from foo"");
                    if (rs.next()) {
                            System.out.println(rs.getString(""id""));
                    }

                    statement.execute(""insert into foo (id) values (5)"");
                    conn.commit();

                    rs = statement.executeQuery(""select * from foo"");
                    if (rs.next()) {
                            System.out.println(rs.getString(""id""));
                    }


                    conn.close();
            } catch (Throwable t) {
                t.printStackTrace();
            }

        }


    @Test
    public void test() {

    }
}
</code></pre>
",https://stackoverflow.com/questions/46100544/some-clarifications-about-using-h2-with-junit,['java'],2673,TRUE,1,2
What is the Best plugin to integrate Node Js Istanbul code coverage into Jenkins,"<p>I am working on a NodeJS project, chai framework is been used for the unit testing and istanbul is been used for the code coverage. </p>

<p>I wanted to integrate the istnabul code coverage into the Jenkins. I have googled regarding the same, but couldn't get much of the information regarding this integration. </p>

<p>What is the best way/best jenkins plugins available to integrate the istanbul code coverage into jenkins?</p>
",https://stackoverflow.com/questions/46680221/what-is-the-best-plugin-to-integrate-node-js-istanbul-code-coverage-into-jenkins,"['node.js', 'jenkins', 'chai', 'istanbul']",970,TRUE,1,1
"unit test a react component- jest, enzyme","<p>I am unit testing react component. One component imports other component and use its props. Here are jsx files :</p>

<pre><code>class First extends React.PureComponent {
    render() {
        const { name, isSelected, onClick } = this.props;
        const activeClass = isSelected ? styles.active : '';
        return (
            &lt;div
                className={`${styles.first} ${activeClass}`}
                role=""button""
                tabIndex={0}
                onClick={() =&gt; onClick(name)}
            &gt;
                {name}
            &lt;/div&gt;
        );
    }
}

First.propTypes = {
    name: PropTypes.string.isRequired,
    isSelected: PropTypes.bool,
    onClick: PropTypes.func,
};

export default First;
</code></pre>

<p>Here is my second class that imports this class :
i</p>

<pre><code>mport First from '../First/First';

const Second = ({ values, passedVal, onClick }) =&gt; {
    const second = values.map(vlaue =&gt;
        &lt;First
            key={value}
            name={value}
            isSelected={value === passedVal}
            onClick={onClick}
        /&gt;,
    );

    return (
        &lt;div &gt;
            {Second}
        &lt;/div&gt;
    );
};

Second.propTypes = {
    values: PropTypes.arrayOf(PropTypes.string),
    passedVal: PropTypes.string,
    onClick: PropTypes.func,
};

export default FilterList;
</code></pre>

<p>Here is my test. I want to test isSelected condition in my test :</p>

<pre><code>describe('Second - Unit test', () =&gt; {
    let props;
    let secondComponent;

    const second = () =&gt; {
        if (!secondComponent) {
            secondComponent = shallow(&lt;Second {...props} /&gt;);
        }
        return secondComponent;
    };
      beforeEach(() =&gt; {
        props = Second.defaultProps;
        secondComponent = undefined;
    });

   it('verify value of isSelected ', () =&gt; {
             props.passedVal='value01';
             props.value=['value01'];
            console.log(props.isSelected);
           });
</code></pre>

<p>It gives me undefined as this is prop of First class. How can i verify this logic here. Need to make instance of first and then check?</p>
",https://stackoverflow.com/questions/46701623/unit-test-a-react-component-jest-enzyme,"['javascript', 'reactjs', 'enzyme', 'jestjs']",848,TRUE,1,2
"Jasmine, AngularJS: Unit test a function which returns a value after timeout","<p>I'm not sure where I'm going wrong with this test. </p>

<p>Service Code: </p>

<pre><code>self.clearMessage = function(interval) {
  if (!interval)
    interval = 2000;

  return $timeout(function() {
    return '';
  }, interval);
};
</code></pre>

<p>Spec: </p>

<pre><code>it('clears message', function() {
  var result = self.clearMessage();

  $timeout.flush();

  expect(result).toBe('');
});
</code></pre>

<p>I've also tried triggering a digest cycle in test with no success. I'be never run into this issue before, as I generally would be setting an external variable inside the timeout block - that works fine for unit testing. </p>

<p>In this scenario, when there is only a return inside the timeout I receive the following error:</p>

<p><code>Expected Promise({ $$state: Object({ status: 1, value: '' }), $$timeoutId: 1 }) to be ''.</code></p>

<p><strong>EDIT / ANSWER</strong></p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>it('clears message', function() {
  self.clearMessage().then(function(response) {
    expect(response).toBe('');
  })

  $timeout.flush();
});</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/45155167/jasmine-angularjs-unit-test-a-function-which-returns-a-value-after-timeout,"['javascript', 'angularjs', 'unit-testing', 'jasmine', 'karma-jasmine']",813,TRUE,1,1
Delay in publishing message on topic using aws-sdk iotData.publish on aws lambda,"<p>I am using aws-sdk for publishing message on topic below is the code:</p>

<pre><code>var AWS = require('aws-sdk');
AWS.config.region = 'us-east-1';
AWS.config.credentials = {
    accessKeyId: 'myaccesskeyid',
    secretAccessKey: 'mysecretaccesskey'
}

function LEDOnIntent() {
    this.iotdata = new AWS.IotData({
        endpoint: 'XXXXXXXXX.iot.us-east-1.amazonaws.com'
    });
}

LEDOnIntent.prototype.publishMessage = function() {
    console.log('&gt;publishMessage');
    var params = {
        topic: 'test_topic',
        /* required */
        payload: new Buffer('{action : ""LED on""}') || 'STRING_VALUE',
        qos: 1
    };
    this.iotdata.publish(params, function(err, data) {
        if (err) console.log(err, err.stack); // an error occurred
        else {
            console.log(""Message published : "" + data); // successful response
        }
    });
}
</code></pre>

<p>It works fine in local unit testing but when I deploy this code on AWS lambda then I got very uneven behaviour. For the first few requests it will not publish message then it will work fine when I continuously test it. When I test after some break then again it stop working for some initial requests.</p>
",https://stackoverflow.com/questions/46709232/delay-in-publishing-message-on-topic-using-aws-sdk-iotdata-publish-on-aws-lambda,"['node.js', 'aws-lambda', 'aws-sdk']",881,FALSE,1,1
Python: How to wait until a subprocess finishes initializing,"<p>I am trying to create a Redis temporary instance for unit testing:</p>

<pre><code>class RedisTemporaryInstance:
    def __enter__(self):
        self.process = subprocess.Popen(['redis-server', '--port', '6399'],
                                        stdout=open(os.devnull, 'wb'),
                                        stderr=subprocess.STDOUT)
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        subprocess.call(['redis-cli', '-p', '6399', 'shutdown'])
</code></pre>

<p>But when I am using it like this:</p>

<pre><code>import redis
with RedisTemporaryInstance() as temp:
    red = redis.Redis(port=6399)
    print(red.ping())
</code></pre>

<p>i am getting </p>

<pre><code>ConnectionError: Error 111 connecting to localhost:6399. Connection refused.
</code></pre>

<p>However when I am adding a small sleep</p>

<pre><code>with RedisTemporaryInstance() as temp:
    sleep(0.01)
    red = redis.Redis(port=6399)
    print(red.ping())
</code></pre>

<p>everything works fine. So apparently the server is not ready yet to accept connections without the sleep.</p>

<p>My question is: is there a better way to wait for the server to be ready instead of adding an arbitrary sleep duration?</p>
",https://stackoverflow.com/questions/45216260/python-how-to-wait-until-a-subprocess-finishes-initializing,"['python', 'sockets', 'server', 'redis', 'subprocess']",1196,TRUE,1,2
How to test single file Vue components,"<p>I would like to use <code>ava</code> for unit testing my <code>Vue</code> components. Right now I have a very simple setup:</p>

<p><strong>package.json</strong></p>

<pre><code>{
    ""name"": ""vue-testing"",
    ""version"": ""1.0.0"",
    ""description"": """",
    ""main"": ""index.js"",
    ""scripts"": {
        ""test"": ""echo \""Error: no test specified\"" &amp;&amp; exit 1""
    },
    ""keywords"": [],
    ""author"": """",
    ""license"": ""ISC"",
    ""babel"": {
        ""presets"": [
            ""es2015""
        ]
    },
    ""ava"": {
        ""require"": [
            ""babel-register"",
            ""./test/helpers/setup-browser-env.js""
        ]
    },
    ""devDependencies"": {
        ""ava"": ""^0.18.1"",
        ""babel-preset-es2015"": ""^6.24.1"",
        ""babel-register"": ""^6.22.0"",
        ""browser-env"": ""^2.0.21""
    },
    ""dependencies"": {
        ""vue"": ""^2.1.10""
    }
}
</code></pre>

<p><strong>./test/helpers/setup-browser-env.js</strong></p>

<pre><code>import browserEnv from 'browser-env';

browserEnv();
</code></pre>

<p><strong>./test/Notification.js</strong></p>

<pre><code>import Vue from 'vue/dist/vue.js';
import test from 'ava';
import Notification from '../src/Notification';

let vm;

test.beforeEach(t =&gt; {
    let N = Vue.extend(Notification);

    vm = new N({ propsData: {
        message: 'Foobar'
    }}).$mount();
});


test('that it renders a notification', t =&gt; {
    t.is(vm.$el.textContent, 'FOOBAR');
});
</code></pre>

<p><strong>src/Notification.js</strong></p>

<pre><code>export default {
    template: '&lt;div&gt;&lt;h1&gt;{{ notification }}&lt;/h1&gt;&lt;/div&gt;',
    props: ['message'],
    computed: {
        notification() {
            return this.message.toUpperCase();
        }
    }
};
</code></pre>

<p>When I run <code>ava</code> everything works as expected: <code>1 passed</code>.</p>

<p>I'd be more happy if I could use the following component syntax:</p>

<p><strong>./src/Notification.vue</strong></p>

<pre><code>&lt;template&gt;
    &lt;div&gt;
        &lt;h1&gt;{{ notification }}&lt;/h1&gt;
    &lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
export default {
     props: ['message'],

    computed: {
        notification() {
            return this.message.toUpperCase();
        }
    }
}
&lt;/script&gt;
</code></pre>

<p>But then <code>ava</code> will return the following error:</p>

<pre><code>&gt; 1 | &lt;template&gt;
    | ^
  2 |     &lt;div&gt;
  3 |         &lt;h1&gt;{{ notification }}&lt;/h1&gt;
  4 |     &lt;/div&gt;
</code></pre>

<p>I can't figure out how to make this work, any help would be greatly appreciated!</p>
",https://stackoverflow.com/questions/43678826/how-to-test-single-file-vue-components,"['javascript', 'testing', 'vue.js', 'ava']",2066,TRUE,1,3
Abstracted Dispose Method not called when using nSubstitute,"<p>i have this base (abstract) class:</p>

<pre><code>public abstract class StreamWriterBuilderService : IStreamWriterService
{
    private Stream fs;
    private StreamWriter stream;

    public void WriteLine(
        string stringToWrite )
    {
        if ( stream == null )
        {
            throw new InvalidOperationException( ""Tried to call WriteLine on an uninitialised StreamWriterBuilderService"" );
        }

        stream.WriteLine( stringToWrite );
        Flush();
    }

    public void Flush()
    {
        if ( stream == null )
        {
            throw new InvalidOperationException( ""Tried to call Flush on an uninitialised StreamWriterBuilderService"" );
        }

        stream.Flush();
    }

    public void Initialise(
        string filePath )
    {
        Contract.Requires&lt;ArgumentNullException&gt;( filePath != null );

        fs = File.Open( filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite );
        stream = new StreamWriter( fs );
        WriteLine(""Initialised"");
        Initialised = true;
    }

    public bool Initialised { get; private set; }

    #region Dispose Implementation

    ~StreamWriterBuilderService()
    {
        Dispose( false );
        Debug.WriteLine( false, ""This StreamWriterBuilderService object was not disposed of"" );
    }

    private bool _isDisposed;

    public virtual void Dispose()
    {
        Dispose( true );
        GC.SuppressFinalize( this );
    }

    protected virtual void Dispose(
        bool disposing )
    {
        if ( _isDisposed )
            return;

        if ( disposing &amp;&amp; Initialised )
        {
            stream.Dispose();
            fs.Dispose();
            stream = null;
            fs = null;
        }

        _isDisposed = true;
    }

    #endregion Dispose Implementation
}
</code></pre>

<p>I am unit testing this with:</p>

<pre><code>    protected readonly string TargetFilePath = Path.GetTempFileName();
    protected const string Header = ""Initialised"";

    protected override void SetContext()
    {
        SUT = Substitute.For&lt;StreamWriterBuilderService&gt;();
    }
</code></pre>

<p>and...</p>

<pre><code>    private string fileContents;
    private const string TestString = @""ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!£$%^&amp;*()+~@?&gt;&lt;|¬"";

    protected override void Because()
    {
        base.Because();
        SUT.Initialise( TargetFilePath );
        SUT.WriteLine( TestString );
        SUT.Flush();
        SUT.Dispose();
        fileContents = File.ReadAllText( TargetFilePath );
    }
</code></pre>

<p>The trouble I am having is that this:</p>

<pre><code>SUT.Dispose();
</code></pre>

<p>does not actually call my Dispose method in my abstract class because it is declared as a virtual method.  If I remove the virtual method then the code is played out. However, I need to keep the virtual method there as I need to override elsewhere in my solution...</p>
",https://stackoverflow.com/questions/45731949/abstracted-dispose-method-not-called-when-using-nsubstitute,"['c#', 'unit-testing', 'abstract-class', 'nsubstitute']",448,TRUE,-1,2
C# - Mock Unit Test From Service Client,"<p>Hi I have a test method is trying to Mock Unit Testing from Local ServiceClient using Visual Studio </p>

<pre><code>[TestMethod()]
public void IsSuccess_ThanAllocateFund()
{
    string FundCode =""CodeABC123"";   
    bool isAvailable = CheckFundAvialable(FundCode);
    bool result = db.AddFund(""UserHaskins"",FundCode);
    Assert.AreEqual(isAvailable, result);
}
</code></pre>

<p>First of all it is checking the fund. If fund available then it will add fund to user using following method</p>

<pre><code>public bool CheckFundAvialable(FundCode)
{
    bool isAvailable =true;
    FundAvailableServiceClient _PartAvailabilityService = new FundAvailableServiceClient()
    int _Available = _FundAvailableService.GetAvailability(FundCode);
    if (_Available &lt;= 0) {
     isAvailable = false;
    }
    return isAvailable;
}
</code></pre>

<p>My ServiceClint  method are given bellow </p>

<pre><code>public partial class FundAvailibilityServiceClient : System.ServiceModel.ClientBase&lt;MyProject.IFundAvailibilityService&gt;,
MyProject.IFundAvailibilityService
{
    public int GetAvailability(string stockCode)
    {
        return base.Channel.GetFundAvailibility(FundCode);
    }
</code></pre>

<p>}</p>

<p>And Add To Database; however I am trying to mock </p>

<pre><code>public bool AddFund(string UserName, string FundCode)
{ 
  // Database add / Insert
  return true;  
}
</code></pre>

<p>Now my problem is that how I will do Mock for my ClientService in unit test;      </p>
",https://stackoverflow.com/questions/41849592/c-mock-unit-test-from-service-client,['c#'],702,FALSE,0,1
Testing component Angular2,"<p>I have to make some unit tests for a website made with Angular2 but im not sure how to test the components using traditional Unit testing. Example of a component i want to test: </p>

<pre><code>    import { Component } from '@angular/core';
import * as io from ""socket.io-client"";
import { SocketService } from '../global/socket.service';
import { Router } from '@angular/router';

@Component({
  moduleId: module.id,
  selector: 'login-app',
  templateUrl: 'login.component.html',
})
export class LoginComponent  { 
  name = 'Angular'; 
  username: string;
  password: string;

  constructor(private socketService: SocketService, private router: Router){ } 

  loginAccount(){
    var login = {
        username: this.username,
        password: this.password,
    }
    this.socketService.socket.emit('login', JSON.stringify(login));
  } 

  ngOnInit(){
    if(localStorage.getItem('user')){
        this.router.navigateByUrl('/home');
    }
  }
}
</code></pre>

<p>The test class ive made so far looks like this: </p>

<pre><code>import {LoginComponent} from './login.component';
describe('login' , ()=&gt;{
    it('test userinput' , ()=&gt;{

    })
}) 
</code></pre>

<p>Im not sure what test and how to test it as the functions i have do not have any parameters or returns. Any help is greatly appreciated. </p>
",https://stackoverflow.com/questions/43346021/testing-component-angular2,"['unit-testing', 'angular', 'testing']",50,FALSE,0,1
"Unit Test - What is difference between AutoFixture Stub, Expect and RhinoMock Stub, Expect?","<p>I see a lot of people using RhinoMock with AutoFixture for unit testing. With RhinoMock we can GenerateMock or GenerateStub a class and then Stub or Expect something happen on that class but with AutoFixture we can do the same by Freeze or Create a class then Stub or Expect a method will be called.
So the what is difference between those? Why we need to use RhinoMock with AutoFixture?</p>
",https://stackoverflow.com/questions/45630804/unit-test-what-is-difference-between-autofixture-stub-expect-and-rhinomock-st,"['rhino-mocks', 'autofixture']",214,FALSE,0,0
Jasmine Error: Expected undefined to equal,"<p>I'm trying to figure out why I'm getting this error. I have a $scope.message in my angular application in my controller but when I put expect(scope.message)toEqual(""It Works"");  I get this Error can anyone point me in the right direction as to what I'm doing wrong. It works when I render the application with index file, I'm using Jasmine and Karma for unit testing. Here is my code.</p>

<pre><code>var app = angular.module(""MyApp"", []);

app.controller(""MyController"",['$scope', function($scope) {
console.log(""Reaching Controller"");

  $scope.message=""Its Good"";

   $scope.customer = {
   name: 'Naomi',
   address: '1600 Amphitheatre'
  };


}])


//normilized name factory function and should return an object
    app.directive('myCustomer', function(){
    return function(scope, elem){ //this for strictly testing 
     directives

    elem.append('&lt;span&gt;This span is appended from directive.&lt;/span&gt;');
   };
});

 /*Here is my unit test
 describe(""Hello PageCtrl working"", function() {
    beforeEach(module('MyApp'));

   describe('Reaching Controller', function(){
       var scope,appCtrl, message;


      beforeEach(inject(function($rootScope, $controller) {
      scope = $rootScope.$new();
      appCtrl = $controller(""MyController"", {$scope:scope}); 

 })); 

        it(""should have a message of Its Good"", function () {
         expect(scope.message).toEqual(""Its Good"");
      });
   });
}); 


Thanks In Advance,
HP
</code></pre>
",https://stackoverflow.com/questions/44233807/jasmine-error-expected-undefined-to-equal,"['angularjs', 'html', 'jasmine']",1258,FALSE,0,0
python.path.append() can&#39;t access 2 directories above - Windows10,"<p>I'm trying to create a unit testing folder outside of the program itself. The structure of the program is as follows:</p>

<pre><code>TheProgram
-- Folder_1
-- -- File_1.py

unittest
-- TestFolder1
-- -- TestFile_1.py
</code></pre>

<p>From TestFile_1.py the path accessing code was </p>

<pre><code>import sys
sys.path.append(""../../TheProgram/Folder_1"")
from File_1.py import *
</code></pre>

<p>The system couldn't find the Folder_1 directory. The following code was also tested but yielded the same result: <code>sys.path.insert(2, ""TheProgram/Folder_1"")</code>. Both the <code>TheProgram</code> and the <code>unittest</code> folders are in the same directory.</p>

<p>How do you access File_1.py from TestFile_1.py in this case?</p>
",https://stackoverflow.com/questions/46135217/python-path-append-cant-access-2-directories-above-windows10,['sys.path'],561,FALSE,0,0
How to unit test class that performs get request,"<p>Say I want to scrape ""long"" posts from a particular website. In order to do this, I've created the following class:</p>

<pre><code>import requests

class PostScraper:

    THRESHOLD = 100

    def __init__(self, thread_id):
        self.url = 'foo.bar/thread-%s?pg=last' % thread_id

    def get_long_posts(self):
        page = requests.get(self.url)
        soup = BeautifulSoup(page.content, 'html.parser')
        posts = soup.find_all('div', 'post-text')
        return [post if len(post.text) &gt; THRESHOLD for post in posts]
</code></pre>

<p>I'd like to write a unit test for this, but I'm not sure how to properly go about it... I'm imagining something like this pseudo-Python:</p>

<pre><code>def test_getting_long_posts():
    scraper = PostScraper(None) # &lt;- Not sure what to pass in. Advice?
    stub = {'text': '&lt;html&gt;&lt;/html&gt;', 'status': '200'}
    bind(url=scraper.url, response=stub)
    posts = scraper.get_long_posts()
    assert.equals(len(posts), 0)
</code></pre>

<p>I'm somewhat new to unit testing, particularly in Python. Does this approach even make sense? How <em>should</em> I go about this?</p>
",https://stackoverflow.com/questions/46780979/how-to-unit-test-class-that-performs-get-request,"['python', 'unit-testing', 'testing', 'web-scraping']",378,FALSE,0,1
How to use InternalsVisibleTo without creating a circular reference,"<p>My understanding of <code>InternalsVisibleTo</code> is that it is primarily for unit-testing. But that means that my unit test class, if it's in a separate project, needs a reference to the project that has the class with <code>InternalsVisibleTo</code>, and also <em>that</em> class needs a reference to the unit test class in order to get its assembly name to put in the parameter of the attribute. </p>

<p>How to solve this Catch-22?</p>
",https://stackoverflow.com/questions/42779818/how-to-use-internalsvisibleto-without-creating-a-circular-reference,"['c#', '.net', 'reflection']",232,TRUE,0,1
Reorder constructor parameters,"<p>Is given a class that takes a bunch of parameters in the explicit constructor.
What i have to do is to reorder this parameters. That is going to chain into a lot of change in unit testing and whatever place I use that class.
Is there any way, tool or something, that can switch parameters between them in the whole solution where that class is used?</p>

<p><strong>Example:</strong></p>

<p><em>Change</em></p>

<pre><code>public ClassName(string first,string second, string 3rd)
{
}
</code></pre>

<p><em>Into</em></p>

<pre><code>Public ClassName(string second, string 3rd, string first)
{
}
</code></pre>
",https://stackoverflow.com/questions/47157736/reorder-constructor-parameters,"['c#', 'visual-studio', 'unit-testing', 'parameters', 'constructor']",152,TRUE,0,1
XML to JSON with org.json fails in JUnit test. NoSuchMethodError for JSONObject,"<p>I have a Spring Boot project where i map XML to JSON using org.json. This works very well outside test environment, but when I try to unit test, I get NoSuchMethodError on the first method call on the JSONObject. Looking at other answers at SO, it looks like JSONObject is not available for unit testing by default or something like that. </p>

<p>How can I unittest a class using org.json and JSONObject?</p>
",https://stackoverflow.com/questions/44105347/xml-to-json-with-org-json-fails-in-junit-test-nosuchmethoderror-for-jsonobject,"['java', 'junit', 'org.json']",413,FALSE,-2,1
React Enzyme Jest error jest.fn() should be called,"<p>My component is as below</p>

<pre><code>import React from 'react';
import { connect } from 'react-redux';
import { Button } from 'react-bootstrap';

import UserActions from '../../../actions/sampleUserAction';
import UserForm from '../../../views/sample/userForm';
import UsersList from '../../../views/sample/usersList';

@connect(store =&gt; ({
    users: store.sampleUserReducer.users,
}))

export default class UserComponent extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            displayForm: false,
            user: { id: '', fName: '', lName: '' },
            isCreationMode: true,
        };

        this.addNewUser = this.addNewUser.bind(this);
        this.handleChange = this.handleChange.bind(this);
        this.submitForm = this.submitForm.bind(this);
        this.editUser = this.editUser.bind(this);
        this.deleteUser = this.deleteUser.bind(this);
    }

    addNewUser() {
        this.setState({
            displayForm: !this.state.displayForm,
            isCreationMode: true,
            user: { id: '', fName: '', lName: '' },
        });
    }

    createUser(users) {
        users.push({
            id: users.length + 1,
            fName: this.state.user.fName,
            lName: this.state.user.lName,
        });
        return users;
    }

    updateUser(users) {
        users.forEach((user) =&gt; {
            if (user.id === this.state.user.id) {
                user.fName = this.state.user.fName;
                user.lName = this.state.user.lName;
            }
        });
        return users;
    }

    submitForm(e) {
        e.preventDefault();
        let { users } = this.props;

        if (this.state.isCreationMode) {
            users = this.createUser(users);
        } else if (!this.state.isCreationMode) {
            users = this.updateUser(users);
        }
        this.addNewUser();
        this.props.dispatch(UserActions.listUsers(users));
    }

    handleChange(e) {
        const { id } = this.state.user;
        let { fName, lName } = this.state.user;
        if (e.target.name === 'fName') {
            fName = e.target.value;
        }

        if (e.target.name === 'lName') {
            lName = e.target.value;
        }

        this.setState({ user: { id, fName, lName } });
    }

    editUser(e, id) {
        const { users } = this.props;
        let user = users.filter(obj =&gt; obj.id === id);
        user = user.length &gt; 0 ? user[0] : null;
        if (user != null) {
            this.setState({
                displayForm: true,
                isCreationMode: false,
                user: { id: user.id, fName: user.fName, lName: user.lName },
            });
        }
    }

    deleteUser(e, id) {
        let { users } = this.props;
        users = users.filter(user =&gt; user.id !== id);
        this.props.dispatch(UserActions.listUsers(users));
    }

    render() {
        console.log(this.state.displayForm);
        return (
            &lt;div className=""container-fluid""&gt;
                &lt;div className=""well""&gt;
                    Sample Users App With Redux
                &lt;/div&gt;
                &lt;UserForm
                  displayForm={this.state.displayForm}
                  isCreationMode={this.state.isCreationMode}
                  submitForm={this.submitForm}
                  handleChange={this.handleChange}
                  user={this.state.user}
                  addNewUser={this.addNewUser}
                /&gt;
                &lt;UsersList
                  users={this.props.users}
                  editUser={this.editUser}
                  deleteUser={this.deleteUser}
                /&gt;
                &lt;div className=""clearfix""&gt;
                    &lt;Button bsStyle=""primary"" onClick={this.addNewUser}&gt;Add User&lt;/Button&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        );
    }
}
</code></pre>

<p>and test file is as below</p>

<pre><code>import React from 'react';
import { createMockStore } from 'redux-test-utils';
import { shallowWithStore } from 'enzyme-redux';
import { Button } from 'react-bootstrap';

import UserComponent from '../../../../src/components/containers/sample/userComponent';
import UserForm from '../../../../src/views/sample/userForm';
import UsersList from '../../../../src/views/sample/usersList';


describe('UsersComponent', () =&gt; {
    let store;
    let container;
    const props = {
        submitForm: jest.fn(),
        addNewUser: jest.fn(),
    };

    beforeEach(() =&gt; {
        const defaultState = { sampleUserReducer: { users: [] } };
        store = createMockStore(defaultState);
        container = shallowWithStore(&lt;UserComponent /&gt;, store);
    });

    it('should work', () =&gt; {
        expect(true).toEqual(true);
    });

    it('container should have UserForm component', () =&gt; {
        expect(container.dive().find(UserForm)).toHaveLength(1);
    });

    it('container should have UsersList component', () =&gt; {
        expect(container.dive().find(UsersList)).toHaveLength(1);
    });

    it('should have add new user button', () =&gt; {
        expect(container.dive().find(Button)).toHaveLength(1);
        expect(container.dive().find(Button).dive().text()).toEqual('Add User');
    });

    it('On click add user button', () =&gt; {
        container.dive().find(Button).simulate('click');
        expect(props.addNewUser).toHaveBeenCalled();
    });
});
</code></pre>

<p>I'm using jest, enzyme, enzyme-redux. I'm new to react unit testing. Last test case is giving error as below. React version is 16.x. In last test case I'm trying to call mocked jest function on button click. For button using react-bootstrap inbuilt Button component</p>

<p>expect(jest.fn()).toHaveBeenCalled()
Expected mock function to have been called.</p>
",https://stackoverflow.com/questions/47668957/react-enzyme-jest-error-jest-fn-should-be-called,"['javascript', 'reactjs', 'react-redux', 'jestjs', 'enzyme']",1023,TRUE,0,3
WEB API unit test using Moq,"<p>Trying to add unit test for the below controller.</p>

<pre><code>   public HttpResponseMessage pldindexingSummary()
    {
        try
        {       
            Logger.log.Info(""Begin GET api/capturestats/pldindexingsummary request from "" + HttpContext.Current.User.Identity.Name);        
            using (Utilities.CreateTransactionScope())
            {
                if (!PLDGlobals.isPopulated) _repository.PopulatePLDGlobals();
                return Request.CreateResponse(HttpStatusCode.OK, _repository.GetIndexingSummary());
            }
        }
        catch (EntityException enEx)
        {
            Logger.log.Error(""Entity Error in GET api/capturestats/pldindexingsummary"", enEx);
            Utilities.SendEmail(""GET api/capturestats/pldindexingsummary"", Utilities.EntityError + enEx.Message, enEx.StackTrace.ToString(), string.Empty);
            HttpError error = new HttpError(Utilities.EntityError + enEx.Message);
            return Request.CreateResponse(HttpStatusCode.InternalServerError, error);
        }
        catch (Exception ex)
        {
            Logger.log.Error(""General Error in GET api/capturestats/pldindexingsummary"", ex);
            Utilities.SendEmail(""GET api/capturestats/pldindexingsummary"", Utilities.ExceptionError + ex.Message, ex.StackTrace.ToString(), string.Empty);
            HttpError error = new HttpError(Utilities.ExceptionError + ex.Message);
            return Request.CreateResponse(HttpStatusCode.InternalServerError, error);
        }
    }

         public static TransactionScope CreateTransactionScope()
    {
        var transactionOptions = new TransactionOptions();
        transactionOptions.IsolationLevel = IsolationLevel.ReadUncommitted;
        transactionOptions.Timeout = TransactionManager.MaximumTimeout;
        return new TransactionScope(TransactionScopeOption.Required, transactionOptions);
    }    
</code></pre>

<p>This is what i have done so far.</p>

<pre><code>    [TestMethod]
    public void GetAllIndexingSummary()
    {
        // Arrange
        var mockRepository = new Mock&lt;IPLDRepository&gt;();
        mockRepository.Setup(x =&gt; x.GetIndexingSummary())
            .Returns(new List&lt;IndexingSummaryResponseDTO&gt;
        {
            new IndexingSummaryResponseDTO {DocumentQueueId =1, DocumentQueueName = ""Sales Upload"", DepartmentName = ""PLD_SalesUpload"", DocumentCount= 10, OldestDocumentDate = ""09/01/2016 09:25:50"", UserLocation = ""Dover"" , IsChecked = false, Usernames = ""Gupta_A_N0182727, Ansara_E_N0000391, Aronson_D_N0175509"" },
            new IndexingSummaryResponseDTO {DocumentQueueId =2, DocumentQueueName = ""Inbound Fax Manual"", DepartmentName = ""PLD_InboundFaxManual"", DocumentCount= 20, OldestDocumentDate = ""09/02/2016 12:55:04"", UserLocation = ""Dover"" , IsChecked = false, Usernames = ""Bent_E_N0156485, Herron_E_N0175690"" },
            new IndexingSummaryResponseDTO {DocumentQueueId =3, DocumentQueueName = ""Rating Scan"", DepartmentName = ""PLD_RatingScan"", DocumentCount= 30, OldestDocumentDate = ""09/03/2016 04:45:08"", UserLocation = ""Dover"" , IsChecked = false, Usernames = ""Gupta_A_N0182727, Jinkens_M_N0178324"" },
            new IndexingSummaryResponseDTO {DocumentQueueId =4, DocumentQueueName = ""Indexing/Loading Error"", DepartmentName = ""PLD_IndexingLoadingError"", DocumentCount= 50, OldestDocumentDate = ""09/04/2016 05:10:28"", UserLocation = ""Dover"" , IsChecked = false, Usernames = ""Gupta_A_N0182727, Keshavarz_M_N0070514"" },
            new IndexingSummaryResponseDTO {DocumentQueueId =5, DocumentQueueName = ""Prod Center Scan"", DepartmentName = ""PLD_ProdCenterScan"", DocumentCount= 60, OldestDocumentDate = ""09/05/2016 16:12:12"", UserLocation = ""Dover"" , IsChecked = false, Usernames = ""Libby_S_N0145549, Long_S_N0236534, Miller_K_N0177119"" },
            new IndexingSummaryResponseDTO {DocumentQueueId =6, DocumentQueueName = ""Prod Center Inbound Fax"", DepartmentName = ""PLD_ProdCenterInboundFax"", DocumentCount= 70, OldestDocumentDate = ""09/06/2016 15:25:03"", UserLocation = ""Dover"" , IsChecked = false, Usernames = ""Parmer_N_N0290328, Porter_S_N0074020"" },
            new IndexingSummaryResponseDTO {DocumentQueueId =7, DocumentQueueName = ""Research Dover"", DepartmentName = ""PLD_ResearchDover"", DocumentCount= 0, OldestDocumentDate = ""N/A"", UserLocation = ""Dover"" , IsChecked = false, Usernames = ""Porter_S_N0074020"" },
            new IndexingSummaryResponseDTO {DocumentQueueId =8, DocumentQueueName = ""Orlando Fax/Scan"", DepartmentName = ""PLD_OrlandoFaxScan"", DocumentCount= 80, OldestDocumentDate = ""09/08/2016 21:25:03"", UserLocation = ""Orlando"" , IsChecked = false, Usernames = ""Putnam_S_N0199165"" },
            new IndexingSummaryResponseDTO {DocumentQueueId =9, DocumentQueueName = ""Research Orlando Fax/Scan"", DepartmentName = ""PLD_ResearchOrlandoFaxScan "", DocumentCount= 10, OldestDocumentDate = ""09/09/2016 18:25:03"", UserLocation = ""Orlando"" , IsChecked = false, Usernames = ""Seefeld_J_N0030634"" },
        });

        var controller = new CaptureStatsController(mockRepository.Object);
        controller.Request = new HttpRequestMessage();
        controller.Configuration = new HttpConfiguration();

        //Act
        var result = controller.pldindexingSummary();         

        Assert.IsNotNull(result, ""Result is null"");

        IList&lt;IndexingSummaryResponseDTO&gt; product;
            Assert.IsTrue(result.TryGetContentValue&lt;IList&lt;IndexingSummaryResponseDTO&gt;&gt;(out product));
         Assert.AreEqual(10, product.Count);
    }
</code></pre>

<p>I am getting NullReference Exception : Object reference not set to an instance of object. 
This is my first Unit test.I am not sure where it is going wrong. I have followed the Microsoft article. reference link : 
<a href=""https://learn.microsoft.com/en-us/aspnet/web-api/overview/testing-and-debugging/unit-testing-controllers-in-web-api"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/aspnet/web-api/overview/testing-and-debugging/unit-testing-controllers-in-web-api</a></p>
",https://stackoverflow.com/questions/42449725/web-api-unit-test-using-moq,"['c#', 'unit-testing', 'asp.net-web-api', 'asp.net-web-api2', 'moq']",987,FALSE,0,0
To to test the return value of a method inside a method using Mockito in andorid,"<p>I'm new to Unit testing concept, and would like to test the following scenario.</p>

<pre><code>public interface CredentialService{
    String getAuthToken();
}
</code></pre>

<p>Following implements the service</p>

<pre><code>public class CredentialImpl implements CredentialService{
     @Override
     public String getAuthToken(){
        if(StorageManager.isExpired()) {
          return StorageManager.getToken();
        } else {
          return ""Some error"";
        }
}
</code></pre>

<p>Storage logic it's a singleton class</p>

<pre><code>public class  StorageManager{

  public void setToken(String token) {
    //stores into the prefs
  }

  public String getToken(){
    //get token from prefs
  }

  public boolean isExpired(){
     return false;
  }

}
</code></pre>

<p>Here I would like to test CredentialImplTest and following is my test class</p>

<pre><code>@Config(constants = BuildConfig.class, sdk = TestConfig.SDK)
@RunWith(RobolectricGradleTestRunner.class)
public class CredentialImplTest extends TestCase {
    CredentialServiceImpl mSubject = new CredentialServiceImpl();
    StorageManager mStorageManager = mock(StorageManager.class);
    String mTestToken = ""abcd"";

@Test
public void getAccessToken_noError_expectToken(){
    mStorageManager.setAccessToken(mTestToken);
    when(mSubject.getAuthToken())
            .thenReturn(mTokenUtils.getAccessToken());
    assertEquals(mTestToken, mSubject.getAccessToken());
}
}
</code></pre>

<p>If I try to execute the above test the Android Studio throwing E.g. thenReturn() may be missing.</p>

<pre><code>Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod();
Hints:
 1. missing thenReturn()
 2. you are trying to stub a final method, you naughty developer!
</code></pre>

<p>Is my approach to test <code>getAuthToken()</code> method right, and if not please suggest me the right one?</p>
",https://stackoverflow.com/questions/46811138/to-to-test-the-return-value-of-a-method-inside-a-method-using-mockito-in-andorid,"['java', 'android', 'unit-testing', 'mockito', 'junit4']",78,FALSE,0,0
How to write unit tests for stored procedures in MySQL?,"<p>I am working on a project where we use lots of stored procedures. Currently, we unit test stored procedures by:</p>

<p>1) Writing a sql script that calls the stored procedure and uses select statements to print output values. </p>

<p>2) Then by comparing a good output with the test output for declaring whether the test has passed or not.</p>

<p>Is there an inbuilt support for Unit Testing in MySQL? What is the industry standard way of doing this?</p>
",https://stackoverflow.com/questions/43128012/how-to-write-unit-tests-for-stored-procedures-in-mysql,"['mysql', 'unit-testing', 'stored-procedures']",476,FALSE,6,0
Mocking angular service class properties or variables,"<p>I am unit testing an angular application and there is a service I need to mock. I am able to mock service methods without any problem but when I try to mock properties in the same way it give me error</p>

<p>My configuration service have one property and one mothod, I want to mock the property as I cannot generate that value.</p>

<p>Service</p>

<pre><code>@Injectable()
export class ConfigService {
  public config = 'iamdirect';

  constructor(private http: Http) {
   }

  public load(): Observable&lt;any&gt; {
    return 'Iamokey';
  }
}
</code></pre>

<p>Mocking the service in angular test</p>

<pre><code>// mocking config service
configService = TestBed.get(ConfigService);
spyOn(configService, 'load')
  .and.returnValue(Observable.of({
  contactDetails: {
    emailAddress: 'testemail@email.com'
  }
}));
</code></pre>

<p>When I do It gives me error.</p>

<pre><code>spyOn(configService, 'config') //config is the property
  .and.returnValue(Observable.of({
  contactDetails: {
    emailAddress: 'testemail@email.com'
  }
}));
</code></pre>
",https://stackoverflow.com/questions/46549869/mocking-angular-service-class-properties-or-variables,"['angular', 'angular-test', 'angular-unit-test']",10377,TRUE,6,1
Karma + AngularJS Multiple expects but only one success,"<p>I am new to AngularJS and Karma and trying to follow official AngularJS tutorials. As I am running simple unit testing in Karma, I tried to edit one more test case in the -spec.js file. The <code>app-spec.js</code> file is as:</p>

<pre><code>'use strict';
describe('PhoneListController', function() {
    beforeEach(module('phonecatApp'));
    it('should create a `phones` model with 3 phones', inject(function($controller) {
        var scope = {};
        var ctrl = $controller('PhoneListController', {$scope: scope});
        expect(scope.phones.length).toBe(3);
        expect(scope.phones.length+2).toBe(5);
    }));
});
</code></pre>

<p>And here is the sole line in the output:</p>

<pre><code>Chrome 59.0.3071 (Windows 7 0.0.0): Executed 1 of 1 SUCCESS (0.013 secs / 0.005 secs)
</code></pre>

<p>I think I should be expecting two lines or something like <code>Executed 1 of 2 SUCCESS</code> and <code>Executed 2 of 2 SUCCESS</code>.
I do not understand what the problem is. Any idea?</p>
",https://stackoverflow.com/questions/45336935/karma-angularjs-multiple-expects-but-only-one-success,"['javascript', 'angularjs', 'karma-jasmine']",157,FALSE,0,0
What is use of &quot;expect_file()&quot; function in Codeception?,"<p>Hi i am new to codeception unit testing and i am using it with Yii2. I know the user of functions <code>expect_not()</code> and <code>expect_that()</code> and also know little about <code>expect()</code> function and uses it to check key in error array.</p>

<p>However I don't know the use of <code>expect_file()</code>. I searched little in internet but found not any good help. can anyone please give me little description about the use of this function.</p>
",https://stackoverflow.com/questions/44367149/what-is-use-of-expect-file-function-in-codeception,"['php', 'yii', 'yii2', 'phpunit', 'codeception']",194,TRUE,0,1
Javascript: is it a bad practice to instantiate a class inside method?,"<pre><code>class A {}

class B {
 foo() {
   const a = new A();
 }
}
</code></pre>

<p>I know in other OOP languages it is a sin. Objects are passed by a dependency injector (getter or constructor).</p>

<p>As far as I remember, the main issue with that syntax is unit-testing. 
In the example above, if it was OOP language, it would be hard to test the method <code>foo()</code> as it's impossible to mock the class <code>A</code>.
However, Javascript is different, and the mocking is possible in this situation.</p>
",https://stackoverflow.com/questions/44641157/javascript-is-it-a-bad-practice-to-instantiate-a-class-inside-method,"['javascript', 'dependency-injection']",75,FALSE,0,0
"Does the DebuggerDisplay directive &quot;,nq&quot; only have effect for strings?","<p>I'm writing some code to automatically parse/evaluate <code>DebuggerDisplay</code> strings for unit testing purposes. I'm curious, does the <code>,nq</code> directive only have effect for strings? I see that if I write</p>

<pre><code>[DebuggerDisplay(""{c,nq}"")]
public class D { public C c = new C(); }

public class C { }
</code></pre>

<p>Then a <code>new D()</code> will present as <code>{C}</code> in the debugger. Removing the <code>,nq</code> from the display string has the same effect. Only if I change the type of <code>c</code> to a string, like this</p>

<pre><code>[DebuggerDisplay(""{c,nq}"")]
public class D { public string c = ""foo""; }
</code></pre>

<p>does removing/keeping <code>,nq</code> seem to have effect (it results in <code>""foo""</code> and <code>foo</code>, respectively). So does <code>,nq</code> only matter when you're trying to display a string field/member?</p>
",https://stackoverflow.com/questions/41838481/does-the-debuggerdisplay-directive-nq-only-have-effect-for-strings,"['c#', '.net', 'visual-studio', 'visual-studio-debugging', 'debuggerdisplay']",3000,TRUE,11,1
"How can I mock HttpRequestMessage, specifically the CreateResponse?","<p>How can I mock <code>HttpRequestMessage</code>, specifically the <code>CreateResponse</code>?</p>

<pre><code>var requestMessage = Substitute.For&lt;HttpRequestMessage&gt;();
requestMessage.CreateResponse().ReturnsForAnyArgs(
       new HttpResponseMessage(HttpStatusCode.OK));
</code></pre>

<p>but I get the exception ...</p>

<pre><code>NSubstitute.Exceptions.CouldNotSetReturnDueToNoLastCallException: 
  'Could not find a call to return from.
</code></pre>

<p>I've seen the questions ... <a href=""https://stackoverflow.com/questions/11053598/how-to-mock-the-createresponset-extension-method-on-httprequestmessage"">How to mock the CreateResponse&lt;T&gt; extension method on HttpRequestMessage</a> </p>

<p>And associated ... <a href=""https://stackoverflow.com/questions/10868673/asp-net-webapi-unit-testing-with-request-createresponse"">ASP.NET WebApi unit testing with Request.CreateResponse</a> ... </p>

<p>But they don't seem to actually end up mocking the CreateResponse </p>

<p><strong>Additional comments:</strong> </p>

<p>I'm trying to write a unit test around the starter of an Azure precompiled C# function ...</p>

<pre><code>[FunctionName(""Version"")]
public static HttpResponseMessage Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, ""get"", ""post"", Route = null)]
    HttpRequestMessage req,
    TraceWriter log)
{
    log.Info(""Version function processed a request ... "");

    return req.CreateResponse(HttpStatusCode.OK, ""Version 0.0.1"");
}
</code></pre>

<p>and the actual test, where I want to mock up the HttpRequestMessage, specifically the CreateReponse where I get the error is ... </p>

<pre><code>[TestMethod]
public void Version_returns_value()
{
    var requestMessage = Substitute.For&lt;HttpRequestMessage&gt;();
    requestMessage.CreateResponse(Arg.Any&lt;HttpStatusCode&gt;(), Arg.Any&lt;string&gt;())
                  .Returns(new HttpResponseMessage(HttpStatusCode.OK));
    var log = new CustomTraceWriter(TraceLevel.Verbose);

    var httpResponseMessage = VersionFunction.Run(requestMessage, log);
    var httpContent = httpResponseMessage.Content;

    httpContent.Should().Be(""Version 0.0.1 :: valid"");
}
</code></pre>
",https://stackoverflow.com/questions/45239471/how-can-i-mock-httprequestmessage-specifically-the-createresponse,"['c#', 'unit-testing', 'asp.net-web-api', 'mocking', 'nsubstitute']",7386,TRUE,8,1
"Tests not picked up with XUnit testrunner on Visual Studio on Mac (C#, .net Core)","<p>I am running Visual Studio on Mac (Preview 5, latest) and I am trying to get unit testing with Xunit working.</p>

<p>I created a new project for .NET Core -> Tests which creates the following 
sample code</p>

<pre><code>using System;
using Xunit;

namespace SMASHDOCsTests
{
    public class UnitTest1
    {
        [Fact]
        public void testFoo()
        {
            return;
        }
    }
}
</code></pre>

<p>I am able to compile the code properly however I can not execute the tests.</p>

<p>It always complains with ""Internal error: unable to run tests, test discovery failed"".</p>

<p>How can I track this error down or resolve it?</p>
",https://stackoverflow.com/questions/43328489/tests-not-picked-up-with-xunit-testrunner-on-visual-studio-on-mac-c-net-core,"['c#', 'visual-studio-mac']",492,FALSE,2,1
Pattern matching in haskell for lists,"<p>[Noob question]
I have a list in haskell with only two elements : </p>

<pre><code>mylist = [""Apple"", ""Mango""]
</code></pre>

<p>When I try to do pattern matching like this</p>

<pre><code>[firstelemet ,secondelement] = mylist;
</code></pre>

<p>I get this kind of warning. </p>

<blockquote>
  <p>warning: [-Wincomplete-uni-patterns]
      Pattern match(es) are non-exhaustive
      In a pattern binding:
          Patterns not matched:
              []
              [<em>]
              (</em>:<em>:</em>:_)</p>
</blockquote>

<p>Any suggestions on how this can be done in a better way. Actually I need to do this for unit testing that returns a list with two elements.</p>
",https://stackoverflow.com/questions/45117288/pattern-matching-in-haskell-for-lists,['haskell'],928,TRUE,2,2
"ReactJS/Jest: How to test/mock a function, which is passed to component","<p>I'm trying to do some unit testing using jest/enzyme for my react components.</p>

<p>But I'm facing problems with an function I'm passing to a second component.
I don't understand if I have to test or mock this function. If I have to mock it, I don't know how to do that for a function.</p>

<p><strong>Parent Component</strong></p>

<pre><code>export default class Parent extends Component {
  togglePosition (term, event) {
    this.setState({
      top: term.length &gt;= 3
    })
  }

  render () {
    return (
      &lt;div&gt;
        &lt;Child togglePosition={this.togglePosition} /&gt;
      &lt;/div&gt;
    )
  }
}
</code></pre>

<p><strong>Child component</strong></p>

<pre><code>export default class Child extends Component {
  handleChange (event) {
    const term = event.target.value
    this.props.togglePosition(term) // &lt;-- Test/mock it?
    this.setState({
      loading: 'loading',
      term
    })
  }

  render () {
    return (
      &lt;div&gt;
        &lt;Input id=""target-input"" onChange={this.handleChange} /&gt;
      &lt;/div&gt;
    )
  }
}
</code></pre>

<p>This is how I do a test for the Child component - testing <code>handleChange</code>:</p>

<p><strong>Unit test (Child)</strong></p>

<pre><code>it('handleChange() should set state.term', () =&gt; {
  const event = { target: { value: 'test' } }
  const wrapper = shallow(&lt;Child /&gt;)

  wrapper.find('#target-input').simulate('change', event)
  const state = wrapper.instance().state
  expect(state).toEqual({ loading: 'loading', term: 'test' })
})
</code></pre>

<p>Do get this error: <code>TypeError: this.props.togglePosition is not a function</code></p>
",https://stackoverflow.com/questions/47102645/reactjs-jest-how-to-test-mock-a-function-which-is-passed-to-component,"['javascript', 'reactjs', 'unit-testing', 'jestjs']",4058,TRUE,5,1
Ignore View controllers from XCTest coverage,"<p>I am making my first go to the unit testing. I am using MVVM and i can test pretty much everything with unit test (not ui test). The problem is that in the coverage my controller classes are showing up and that affect my coverage. Off course i can always do UI testing to cover those classes but i do not want. Is it possible to ignore from coverage all the classes that <code>import UIKit</code> ?</p>
",https://stackoverflow.com/questions/44462386/ignore-view-controllers-from-xctest-coverage,"['swift', 'unit-testing', 'code-coverage', 'xctest']",744,FALSE,2,1
Asp.net core 2.0 remote testing and ef core mocking,"<p>I am developing web api(s) for an android app client. Now the developer of the client, wants a way to test web api(s) without getting the real data corrupt. So now I am thinking of something like unit testing and database (ef core) mocking in that except the requests are remote and stateless; so every time the client app requests for data or changing it, the database should remember the last things.</p>

<p>From the <a href=""https://learn.microsoft.com/en-us/ef/core/miscellaneous/testing/"" rel=""nofollow noreferrer"">docs of Microsoft</a>, there are two ways to do this on unit testing:</p>

<ul>
<li><a href=""https://learn.microsoft.com/en-us/ef/core/miscellaneous/testing/sqlite"" rel=""nofollow noreferrer"">SQLite in-memory mode</a></li>
<li><a href=""https://learn.microsoft.com/en-us/ef/core/miscellaneous/testing/in-memory"" rel=""nofollow noreferrer"">The InMemory provider</a></li>
</ul>

<p>But the thing is that those are volatile and from one request to another request they will be refreshed. So I think SQLite (normal mode - file mode), or using SQLServer with different connection string will be a good solution. Now there are some questions:</p>

<ol>
<li>Is this a good idea or there is one better?</li>
<li>If it is good, then how should I implement it?</li>
<li>Is it good to add a header in the request?</li>
<li>On the server-side code where should I tell the ef to use testing database?</li>
</ol>
",https://stackoverflow.com/questions/45876334/asp-net-core-2-0-remote-testing-and-ef-core-mocking,"['sqlite', 'testing', 'asp.net-core-2.0', 'entity-framework-core']",169,FALSE,3,0
Use props instead of state,"<p>I know if you want to alter something within a component itself you use state, and when the emit is external then u use props to receive it. But today I stumped across this example</p>

<pre><code>var Label = React.createClass({
    handleClick: function(){
        console.log(""Click"");
        this.props.children = ""Text After Click"";
        this.setState({liked: false});
    },

    render: function () {
        console.log(""Render"");
        return (
            &lt;p ref=""p"" onClick={this.handleClick}&gt;{this.props.children}&lt;/p&gt;
            );
    }
});
</code></pre>

<p>Used props instead of state to change the text a value of a button. I'm confused now. The link to the source is here <a href=""http://myshareoftech.com/2013/12/unit-testing-react-dot-js-with-jasmine-and-karma.html"" rel=""nofollow noreferrer"">http://myshareoftech.com/2013/12/unit-testing-react-dot-js-with-jasmine-and-karma.html</a></p>
",https://stackoverflow.com/questions/42479155/use-props-instead-of-state,"['javascript', 'reactjs']",329,FALSE,1,1
"CamelBlueprintTesting, why can&#39;t I override this propertyplaceholder?","<p>I have a boolean flag propertyplaceholder that I'm trying to override in one of my unit tests but it's not working.</p>

<pre><code>&lt;cm:property-placeholder id=""id"" persistent-id=""persistent-id&gt;
  &lt;cm:default-properties&gt;
    &lt;cm:property name=""flag"" value=""true"" /&gt;
  &lt;/cm:default-properties&gt;
&lt;/cm:property-placeholder&gt;
</code></pre>

<p>This flag gets use in a bean:</p>

<pre><code>&lt;bean id=""myBean"" class=""com.myBean""&gt;
  &lt;property name=""flag"" value=""${flag}"" /&gt;
&lt;/bean&gt;
</code></pre>

<p>I'd like to override the property to be false when doing unit testing so I implemented the useOverridePropertiesWithPropertiesComponent() method:</p>

<pre><code>@Override
protected Properties useOverridePropertiesWithPropertiesComponent() {
  Properties prop = new Properties();
  prop.put(""errorQueue"", ""mock:error"");
  prop.put(""flag"", false);

  return prop;
</code></pre>

<p>}</p>

<p>My errorQueue property is working fine and error messages are going to ""mock:error"" but the flag isn't overridden property. Does anyone know why this is?</p>
",https://stackoverflow.com/questions/44143649/camelblueprinttesting-why-cant-i-override-this-propertyplaceholder,"['apache-camel', 'blueprint-osgi']",697,TRUE,1,2
Code coverage of Polymer Application with WCT,"<p>I have the sapplication developed in Polymer and unit testing with WCT. I want to generate the code coverage report for that.</p>

<p>I tried with the istanbul<code>(web-component-tester-istanbul)</code>, but it is not supporting it, I am using Polymer Version <code>1.2</code>.</p>

<p>And I tried with Karma + Grunt, but I am not able to genrate the code coverage report.</p>

<p>Can anybody tell me how we can generate code coverage with Karma? I search on google but not able to find WCT with Karma.</p>
",https://stackoverflow.com/questions/43086760/code-coverage-of-polymer-application-with-wct,"['code-coverage', 'wct']",663,TRUE,4,1
Why dont google sample android-architecture todo-mvp project use robolectric to do unit test,"<p>I have read the googlesamples/android-architecture todo-mvp code over and over again. I learned 2 things in the project, mvp and unit-testing. However, I'm wondering the developers don't use robolectric tools to test model-layer. The robolectric tools are faster and easier to use than the android instrumental test. To write mock and prod flavors looks a little boring. There has to be some reason. What is it?
<a href=""https://github.com/googlesamples/android-architecture"" rel=""nofollow noreferrer"">github</a></p>
",https://stackoverflow.com/questions/44815053/why-dont-google-sample-android-architecture-todo-mvp-project-use-robolectric-to,"['android', 'unit-testing', 'robolectric', 'android-mvp']",191,FALSE,1,0
How to refactor class in order to be testable without reflection,"<p>I have a class similar to this:</p>

<pre><code>public class QueueingCommandRunner {
    private Status status;
    private Map&lt;Class&lt;CommandHandler&gt;, CommandHandler&gt; queuedCommands;
    private RunnerClass runnerClass;
    private ExternalCommandRunnerRegistry externalCommandRunnerRegistry;
    private ExternalCommandRunner externalCommandRunner;

    public QueueingCommandRunner(ExternalCommandRunnerRegistry externalCommandRunnerRegistry,
            RunnerClass runnerClass) {

        this.externalCommandRunnerRegistry = externalCommandRunnerRegistry;
        this.runnerClass = runnerClass;
        this.queuedCommands = new LinkedHashMap&lt;&gt;();
        this.status = Status.DOWN;
    }

    public void init() {
        doSomeStuff();
        externalCommandRunner = externalCommandRunnerRegistry.get(runnerClass);
        externalCommandRunner.runListeningCommand(ListenableStatusCommand.class,
                new ListenableStatusHandler(this::changeStatus));
    }

    public &lt;T extends CommandHandler&gt; void runCommand(Class&lt;T&gt; command, T commandHandler) {
        if (status == UP) {
            externalCommandRunner.run(command, commandHandler);
        } else {
            queuedCommands.put(command, commandHandler);
        }
    }

    private void changeStatus(Status status) {
        this.status = status;
        if (status == UP) {
            Iterator&lt;Entry&lt;Class&lt;CommandHandler&gt;, CommandHandler&gt;&gt; commandsIterator =
                queuedCommands.iterator();
            while (commandsIterator.hasNext()) {
                &lt;Entry&lt;Class&lt;CommandHandler&gt;, CommandHandler&gt;&gt; queuedCommand = commandsIterator.next();
                externalCommandRunner.run(queuedCommand.getKey(), queuedCommand.getValue());
                commandsIterator.remove();
            }
        }
    }
}
</code></pre>

<p>I omit stuff like synchronization. My question is, how to test queuing which is inside without using things like invocation of private methods via reflection? In particular I would like to know how to test <code>changeStatus</code> method since it is not directly run from any public method in this class. Is this class bad by design (from unit testing point of view)?</p>

<p>I am using JMockit for testing...</p>
",https://stackoverflow.com/questions/45855880/how-to-refactor-class-in-order-to-be-testable-without-reflection,"['java', 'unit-testing', 'jmockit']",249,TRUE,1,1
How to link an exe project to the classes in another exe project,"<p>Suppose you want to do some unit testing on classes in an executable but you don't want to refactor them out into a lib where you can add the lib using <code>target_link_libraries( target  library )</code> in cmake.</p>

<p>How do you give the test class access to the other classes? </p>

<p>1) Build test project with the source files from the other project?
   another thing</p>

<pre><code>  include_directories(${otherExeProjectDir})

  set( SOURCE_FILES 
     main.cpp
     tests.h
     tests.cpp
     ${otherExeProjectDir}/otherclass1.h
     ${otherExeProjectDir}/otherclass2.h
   )
</code></pre>

<p>2) Link test project with obj files from the other project?
some sort of <code>add_library( otherclass.obj )</code> craziness?</p>

<p>3)</p>
",https://stackoverflow.com/questions/45315932/how-to-link-an-exe-project-to-the-classes-in-another-exe-project,"['c++', 'unit-testing', 'cmake', 'linker', 'exe']",114,TRUE,1,1
Unit tests for cloud Bigtable data access,"<p>How can I get a mock Bigtable with some data to be used in unit testing (ScalaTest with MockitoSugar)? I'm creating an API on top of the Hbase java API, and the data access involves forming row keys using custom logic and then used in Get or Scan methods. So its not enough to have a Result mock object, instead I need a Table instance with some rows in it. How can I achieve it?</p>
",https://stackoverflow.com/questions/44634037/unit-tests-for-cloud-bigtable-data-access,"['unit-testing', 'mockito', 'scalatest', 'bigtable', 'google-cloud-bigtable']",2273,TRUE,1,2
python bokeh unit tests,"<p>I was wondering if there were any strategies or implementations to unit testing of a bokeh plot rendered within a Django template other than looking at the response status code of the Django view?</p>

<p>Here is my code snippet below,</p>

<pre><code>#views.py

def bokeh_view(request):
    ...
    script,div = components(mygraph)
    return render(request, 'graph.html',{'script': script, 'div': div})

#graph.html
...
{{ div | safe }}
{{ script | safe }}
...

#test.py

def test_dashboard(self):
    responce = self.client.post('/bokeh_view/', follow=True)
    self.assertEqual(response.status_code, 200)
</code></pre>

<p>I also have user forms which may affect the database tables from which will then be graphed. I do not have access to selenium currently so all tests are running via Django's test runner.</p>
",https://stackoverflow.com/questions/44010011/python-bokeh-unit-tests,"['python', 'django', 'unit-testing', 'bokeh']",287,TRUE,1,1
getting a python function of functionType for a nested function with recursion,"<p>I am trying to do unit testing for nested functions (function inside a function), I am using code(""nested"" is function name) from below link which would supply closures and returns a valid function that is callable from tests. It works for simple functions. I am trying to make it work for recursive functions. </p>

<p>As an example: 
I am trying to get a valid function for ""innerfunction"" which has an entry in co_freevars as ""innerfunction"".</p>

<p>I want to get a function (FunctionType I believe) for ""innerfunction"" as a callable. To get this I need to call FunctionType with a tuple with a FunctionType for ""innerfunction"". This becomes a recursive ""dependency"".  How can I resolve this dependency for parameters to be sent for ""closures""</p>

<p>Function for </p>

<pre><code>def toplevelfunction():
    def innerfunction(a):
        print ('val of a is ', a)
        if a &gt; 0:
            innerfunction(a -1)
    innerfunction(10)
</code></pre>

<p>Original code that I am using:</p>

<pre><code>def freeVar(val):
  def nested():
    return val
  return nested.__closure__[0]

codeAttribute = '__code__' if sys.version_info[0] == 3 else 'func_code'

def nested(outer, innerName, **freeVars):
  if isinstance(outer, (types.FunctionType, types.MethodType)):
    outer = outer.__getattribute__(codeAttribute)
  for const in outer.co_consts:
    if isinstance(const, types.CodeType) and const.co_name == innerName:
      return types.FunctionType(const, globals(), None, None, tuple(
          freeVar(freeVars[name]) for name in const.co_freevars))
</code></pre>

<p><a href=""https://code.activestate.com/recipes/580716-unit-testing-nested-functions/"" rel=""nofollow noreferrer"">https://code.activestate.com/recipes/580716-unit-testing-nested-functions/</a></p>

<p>How to add support for closures so below works:</p>

<p>func = nested(toplevelfunction, 'innerfunction')</p>

<p>func(5)</p>

<p>would return error need a closure of length 1.
Adding a closure referring to ""const"" shows up that it is of CodeType and not FunctionType. 
Adding a closure value to refer itself seems tricky after reading through the documentation.</p>

<p>I do find innerfunction as:</p>

<pre><code> {code} &lt;code object innerfunction at 0x104b9bc00, file ""/&lt;filedirectory&gt;/handle_results.py"", line 44&gt;
 co_argcount = {int} 1
 co_cellvars = {tuple} &lt;class 'tuple'&gt;: ()
 co_code = {bytes} b""t\x00\x00d\x01\x00|\x00\x00\x83\x02\x00\x01|\x00\x00d\x02\x00k\x04\x00r'\x00\x88\x00\x00|\x00\x00d\x03\x00\x18\x83\x01\x00\x01d\x00\x00S""
 co_consts = {tuple} &lt;class 'tuple'&gt;: (None, 'val of a is ', 0, 1)
 co_filename = {str} '/&lt;fildirectory&gt;/handle_results.py'
 co_firstlineno = {int} 44
 co_flags = {int} 19
 co_freevars = {tuple} &lt;class 'tuple'&gt;: ('innerfunction ',)
 co_kwonlyargcount = {int} 0
 co_lnotab = {bytes} b'\x00\x01\r\x01\x0c\x01'
 co_name = {str} 'innerfunction '
 co_names = {tuple} &lt;class 'tuple'&gt;: ('print',)
 co_nlocals = {int} 1
 co_stacksize = {int} 3
 co_varnames = {tuple} &lt;class 'tuple'&gt;: ('a',)
</code></pre>
",https://stackoverflow.com/questions/41814589/getting-a-python-function-of-functiontype-for-a-nested-function-with-recursion,['python'],758,TRUE,2,1
StackOverflowException in JsonConvert.DeserializeXmlNode,"<p>We recently upgraded to Json.NET 10.0r2 from 6.0.1 and since upgrading I noticed that one of our unit tests throws a Stack Overflow Exception when trying to deserialize invalid Json.  The purpose of the test was to ensure handling of invalid Json.  This same test used to throw a JsonSerializationException, but now is bringing down nUnit with the StackOverflow.  </p>

<p>I've replicated it in Json.NET's own unit testing project with this test:</p>

<pre><code>[Test]
public void FailOnInvalidJSON( )
{
    string json = @""{'Row' : "";

    Assert.Throws&lt;JsonSerializationException&gt;(()=&gt;JsonConvert.DeserializeXmlNode(json, ""ROOT""));
}
</code></pre>

<p>Any ideas on work a work-around?</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/43552070/stackoverflowexception-in-jsonconvert-deserializexmlnode,"['json', 'json.net', 'overflow']",351,TRUE,3,1
How to return empty JSON array from SQL Server,"<p>I have a database with some random data like:</p>

<p><strong>Book</strong>:</p>

<pre><code>    Id uniqueidentifier,
    title nvarchar(255),
    author nvarchar(255),
    genre nvarchar (255),
    deleted datetime
</code></pre>

<p>I have many different books in my <code>Book</code> table. When I want to delete a book, I dont really delete it from database, but just set datetime for <code>deleted</code>, when I delete it.</p>

<p>Here is a case that bothers me.</p>

<p>If user tries to look (search) for a book he deleted (which doesn't exist anymore), it needs to return empty array</p>

<p>Here is what I've done, but it doesn't work:</p>

<pre><code>CREATE PROCEDURE dbo.Book_GetById
    @id uniqueidentifier
AS
BEGIN
    DECLARE @_deleted DATETIME
    SET @_deleted = NULL

    SELECT @_deleted  = Deleted 
    FROM Book 
    WHERE Id = @id

    IF (@_deleted IS NOT NULL) 
    BEGIN
        SELECT JSON_QUERY('[]')
        FOR JSON PATH
</code></pre>

<p>This is not the entire procedure, just the part where I want to return an empty JSON array by checking if deleted is not null, it means that there is a datetime set for that row - book deleted (if it is null, it is not deleted).</p>

<p><strong>PS1</strong>: if there is any other better way than empty array, id like to hear about it too!</p>

<p><strong>PS2</strong>: I need to ""return"" data in my unit testing to see if book is really deleted by checking <code>Assert.IsNotNull(book.Deleted);</code></p>

<p>When I run my debugger in unit testing and when I step over, my <code>var books</code> says <code>null</code>, which I think isn't really right I guess</p>
",https://stackoverflow.com/questions/45610572/how-to-return-empty-json-array-from-sql-server,"['sql', 'arrays', 'sql-server', 'stored-procedures']",3003,FALSE,1,1
Mocking database return types with interfaces,"<p>How to correctly mock some <code>*sql.DB</code> methods for unit testing using interfaces? For example, I want to have a <code>Store</code> struct that is used as a datasource for my handlers. It has a <code>conn</code> field that is the <code>*sql.DB</code>. But in my tests I want to mock the DB, so I try to return not the actual <code>*sql.Rows</code> but an interface that the <code>*sql.Rows</code> should satisfy. Here is the code:</p>

<pre><code>type TestRows interface {
    Scan ()
}

type TestDB interface {
    Query (query string, args ...interface{}) (TestRows, error) 
}

type Rows struct {
    //..
}

func (r *Rows) Scan () {
    fmt.Println(""Scanning"")
}
</code></pre>

<p>This is the <code>*sql.DB</code></p>

<pre><code>type DB struct {
    //...
}

func (d *DB) Query (query string, args ...inteface{}) (*Rows, error) {
    return &amp;Rows{/* .... */}, nil
}
</code></pre>

<p>And when I want to instantiate the <code>Store</code>, it throws error</p>

<pre><code>type Store struct {
    conn TestDB
}

func main() { 
    cl := Store {conn: &amp;DB{}}
    fmt.Println(""Hello, playground"")
}

cannot use DB literal (type *DB) as type TestDB in field value:
    *DB does not implement TestDB (wrong type for Query method)
        have Query(string) (*Rows, error)
        want Query(string) (TestRows, error)
</code></pre>
",https://stackoverflow.com/questions/45596695/mocking-database-return-types-with-interfaces,"['go', 'mocking']",810,TRUE,3,2
Jest specs in nested directories,"<p>Using vue-cli and the template ""webpack"", I get an out-of-the-box setup for unit testing VueJS components.</p>

<p>As long as I keep components source in <code>src/components/</code> and their tests in <code>test/unit/specs/</code> everything is fine. However when i nest them in directories (ie. <code>src/components/fields/</code> and <code>test/unit/specs/fields</code>) Jest seems to ignore some of them.</p>

<p>I'm also getting different outputs by using the flag <code>--no-cache</code>.</p>

<p>Is there additional config needed for getting sub directories to work with Jest ?</p>
",https://stackoverflow.com/questions/47752940/jest-specs-in-nested-directories,"['unit-testing', 'vuejs2', 'jestjs']",370,FALSE,0,0
How to use a config file for Unit Test and another for production in NODE,"<p>I have a value in config file which is used in an IF condition and once that value is set I am not able to get the minimum coverage required. </p>

<p>As work around I created two json files one is production.json and other is test.json and I want to use test.json for Unit Testing and production.json for normal execution.</p>

<p>Please let me know if there is a better way to test this scenario. </p>
",https://stackoverflow.com/questions/47311362/how-to-use-a-config-file-for-unit-test-and-another-for-production-in-node,"['json', 'node.js', 'unit-testing', 'nconf']",328,TRUE,0,1
VisualStudio 2017 preview 2 doesn&#39;t load Unit tests with .NET Core 2.0.0-preview2-006391,"<p>In the last two days I've had some trouble with Unit Testing in VS 2017 preview 2. Yesterday I've installed the last version of .NET core, I've updated every package inside my project and, since then, I haven't been able to see not a single test in VisualStudio's Test Explorer . If run the command ""dotnet test"" in the PowerShell everything works and I receive the information of test's execution. What can I do? Thanks!</p>
",https://stackoverflow.com/questions/44522282/visualstudio-2017-preview-2-doesnt-load-unit-tests-with-net-core-2-0-0-preview,"['visual-studio', 'unit-testing', '.net-core']",52,FALSE,0,1
How do I setup a method to return a DbParameter?,"<p>I have an interface I am attempt mock up for unit testing. It has a method that accepts two parameters, name and value and returns a DbParameter to be built from those parameters</p>

<pre><code>public interface IDbUnitOfWork {
   DbParameter BuildParameter(string name, object value);
}
</code></pre>

<p>I am attempting to set up a test case which I can mock up a returned DbParameter and I am having trouble.</p>

<pre><code>   unitOfWorkMock = new Mock&lt;IDbUnitOfWork&gt;();
   unitOfWorkFactoryMock = new Mock&lt;IUnitOfWorkFactory&gt;();
   unitOfWorkFactoryMock.Setup(u =&gt; u.LoadUnitOfWork()).Returns(new Mock&lt;IDbUnitOfWork&gt;().Object);
   unitOfWorkMock
            .Setup(u =&gt; u.BuildParameter(It.IsAny&lt;string&gt;(), It.IsAny&lt;object&gt;()))
            .Returns((name, value) =&gt; ASDASDASDASD);
</code></pre>

<p>how can I return a DbParameter populated with passed in parameters or a Mocked up DbParameter?</p>

<hr>

<p>Solution (thanks to Patrick)</p>

<pre><code> unitOfWorkMock
    .Setup(u =&gt; u.BuildParameter(It.IsAny&lt;string&gt;(), It.IsAny&lt;object&gt;()))
    .Returns((string name, object value) =&gt; Mock.Of&lt;DbParameter&gt;(p=&gt; p.ParameterName == name &amp;&amp; p.Value == value));
</code></pre>
",https://stackoverflow.com/questions/42377497/how-do-i-setup-a-method-to-return-a-dbparameter,"['c#', 'unit-testing', 'moq']",333,TRUE,0,1
jQuery with Angular 4: InjectionToken vs TypeScript imports,"<p>Provided I've installed jquery &amp; its types:</p>

<pre><code>npm i jquery
npm i @types/jquery
</code></pre>

<p>and ability to import it </p>

<pre><code>import * as $ from 'jquery';
</code></pre>

<p>now I have full:</p>

<ul>
<li>TypeScript support</li>
<li>jQuery is automatically included in the bundle (I used Angular CLI)</li>
</ul>

<p>So my question is: why should I bother use InjectionToken (previously OpaqueToken) to have another layer around jQuery?  I mean: what would be real benefits? Probably I could mock jQuery when unit testing, but in Angular apps I never actually did it and never saw it...</p>
",https://stackoverflow.com/questions/44180064/jquery-with-angular-4-injectiontoken-vs-typescript-imports,"['jquery', 'angular']",219,TRUE,0,1
VS2017 throws Unknow Error after Live Unit Test set to start on a solution,"<p>I have installed VS2017 Enterprise. It was working fine with few of our existing solutions. Then I tried to enable Live Unit Test for one of the solutions and it crashed with Unknown Error. After that every attempt to launch Visual Studio (note: not the solution) failed with Unknow Error. We are using xunit 2.2.0 for our unit testing. Following is what I found in the Event Viewer</p>

<pre><code>Application: devenv.exe
Framework Version: v4.0.30319
Description: The application requested process termination through System.Environment.FailFast(string message).
Message: StreamJsonRpc.RemoteInvocationException: Request locate failed with message: Cannot find service module info file '*/emitService.servicehub.service.json' in 'E:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\ServiceHub\Services', using discovery services failed: VsixServiceDiscovery: ExternalSettingsManager::GetScopePaths failed to initialize PkgDefManager for E:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\devenv.exe
   at Microsoft.VisualStudio.Settings.ExternalSettingsManager.GetScopePaths(String applicationPath, String suffixOrName, String vsVersion, Boolean isLogged, Boolean isForIsolatedApplication)
   at Microsoft.VisualStudio.Settings.ExternalSettingsManager.CreateForApplication(String applicationPath, IInteropLogger logger)
   at Microsoft.ServiceHub.VsixServiceDiscovery.DiscoveryService.EnumerateContentLocations()
   at Microsoft.ServiceHub.VsixServiceDiscovery.DiscoveryService.EnsureServiceModulesEnumerated()
   at Microsoft.ServiceHub.VsixServiceDiscovery.DiscoveryService.discoverService(String serviceName)
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at StreamJsonRpc.JsonRpc.&lt;InvokeCoreAsync&gt;d__56`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.Threading.ThreadingTools.&lt;WithCancellationSlow&gt;d__9`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.ServiceHub.Client.HubClient.&lt;LocateServiceAsync&gt;d__39.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.ServiceHub.Client.HubClient.&lt;RequestServiceChannelNameAsync&gt;d__25.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.ServiceHub.Client.HubClient.&lt;RequestServiceAsync&gt;d__28.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.LanguageServices.Remote.ServiceHubRemoteHostClient.&lt;RequestServiceAsync&gt;d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.VisualStudio.Telemetry.WindowsErrorReporting.WatsonReport.GetClrWatsonExceptionInfo(Exception exceptionObject)
Stack:
   at System.Environment.FailFast(System.String, System.Exception)
   at Microsoft.CodeAnalysis.FailFast.OnFatalException(System.Exception)
   at Microsoft.CodeAnalysis.ErrorReporting.FatalError.Report(System.Exception, System.Action`1&lt;System.Exception&gt;)
   at Microsoft.CodeAnalysis.ErrorReporting.FatalError.ReportUnlessCanceled(System.Exception)
   at Microsoft.VisualStudio.LanguageServices.Remote.ServiceHubRemoteHostClient+&lt;RequestServiceAsync&gt;d__11.MoveNext()
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore+MoveNextRunner.InvokeMoveNext(System.Object)
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore+MoveNextRunner.Run()
   at System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(System.Action, Boolean, System.Threading.Tasks.Task ByRef)
   at System.Threading.Tasks.Task.FinishContinuations()
   at System.Threading.Tasks.Task.FinishStageThree()
   at System.Threading.Tasks.Task`1[[System.Threading.Tasks.VoidTaskResult, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].TrySetResult(System.Threading.Tasks.VoidTaskResult)
   at System.Threading.Tasks.Task+DelayPromise.Complete()
   at System.Threading.Tasks.Task+&lt;&gt;c.&lt;Delay&gt;b__274_1(System.Object)
   at System.Threading.TimerQueueTimer.CallCallbackInContext(System.Object)
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.TimerQueueTimer.CallCallback()
   at System.Threading.TimerQueueTimer.Fire()
   at System.Threading.TimerQueue.FireNextTimers()
   at System.Threading.TimerQueue.AppDomainTimerCallback()
</code></pre>

<p>Any help will be appreciated.</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/42730143/vs2017-throws-unknow-error-after-live-unit-test-set-to-start-on-a-solution,"['visual-studio-2017', 'live-unit-tests']",449,FALSE,0,1
Gitlab CI: How to run tests in pipeline using docker and shell runner,"<p>I need to run tests in my gitlab CI pipeline. This is how my YAML document looks like:</p>

<pre><code>before_script:
  - docker info

build:
  script:
    - docker build -t $CI_REGISTRY_IMAGE:$VERSION .
    - docker push $CI_REGISTRY_IMAGE:$VERSION
</code></pre>

<p>I'm using a shell runner. And now I want to check for correct eslint, which would look like:</p>

<pre><code>eslint .
</code></pre>

<p>In a second step I want to do some unit testing using mocha</p>

<pre><code>meteor test --driver-package practicalmeteor:mocha
</code></pre>

<p>How can I do this in the pipeline using the already build container/image? How should I implement this into the YAML file?</p>
",https://stackoverflow.com/questions/43423881/gitlab-ci-how-to-run-tests-in-pipeline-using-docker-and-shell-runner,"['node.js', 'meteor', 'docker', 'continuous-integration', 'gitlab']",1907,TRUE,0,1
Error with npm test but not mocha test node.js,"<p>I am working with node.js and mocha unit testing and I want to be able to run the test command through npm. When I run mocha test in my tests folder, the test runs sucessfully. However, when I run npm test, the test gives me an error. </p>

<p><a href=""https://i.stack.imgur.com/CiOIU.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/CiOIU.png"" alt=""enter image description here""></a></p>

<p>Here is a snippet from my package.json:</p>

<pre><code>  ""scripts"": {
    ""test"": ""./tests/test.js""
  },
</code></pre>

<p>Anyone know why the npm test would give me an error but mocha test runs just fine?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/43815725/error-with-npm-test-but-not-mocha-test-node-js,"['javascript', 'node.js', 'unit-testing', 'npm', 'mocha.js']",783,TRUE,0,1
Cannot access test resource from production class,"<p>I have the following class which I want to unit test:</p>

<pre><code>class PropsProvider {

    String propsfileLocation;

    void init() {
        Path path = getPropsPath();
        loadPropertiesFromPath(path);
    }

    private Path getPropsPath() throws URISyntaxException {
        URI fileUri = new URI(propsfileLocation);
        return Paths.get(fileUri); // &lt;&lt; failure here
    }

    // ...

}
</code></pre>

<p>I am unit testing the above class and I keep getting a failure on the line <code>Paths.get(fileUri)</code>. I get an <code>IllegalArgumentException</code>. I am passing in a relative path from my unit test, which is <code>src/test/resources/app.properties</code>. I believe this is happening because I haven't included the prefix <code>file:</code>. The unit test resides in the same package as the above class albeit in the <code>/src/test/java folder</code>. How can I fix this? </p>
",https://stackoverflow.com/questions/44417360/cannot-access-test-resource-from-production-class,"['java', 'unit-testing', 'junit']",152,TRUE,0,1
Unittest in Python 2 not working in Python 3,"<p>To have some practice and work on my programming skills I decided to built an application in Python to solve problems from Project Euler. I have no experience with unit testing so I decided to build my project with the help of  TDD and get some experience with that as well. Unfortunately while building the foundation I run my program with Python3 but did all the unit testing with Python2. Now I try to do the test with Python3 and it fails.</p>

<p>Before this I never wrote more than some small scripts with Python. I expect this project to be bigger and also it will contain more files so after some research I decided to use the following project structure:</p>

<pre><code>project_euler:
  euler:
    - __init__.py
    - euler.py
    - problems.py
  tests:
    - __init__.py
    - test_euler.py
    - test_problems.py
</code></pre>

<p>The init files are empty.  </p>

<p><strong>euler.py</strong></p>

<pre><code>#!/usr/bin/env python3
# coding: utf-8


class Euler:
    def __init__(self):
        pass
</code></pre>

<p><strong>problems.py</strong></p>

<pre><code>#!/usr/bin/env python3
# coding: utf-8

import sys
import euler


class ProjectEuler(euler.Euler):
    def __init__(self):
        pass
</code></pre>

<p><strong>test_euler.py</strong></p>

<pre><code>#!/usr/bin/env python3
# coding: utf-8

import unittest
import euler.euler as euler


class UnitTest(unittest.TestCase):
    # a bunch of tests here

if __name__ == '__main__':
    unittest.main(module=None)
</code></pre>

<p>test_problems.py</p>

<pre><code>#!/usr/bin/env python3
# coding: utf-8

import unittest
from euler import problems


class UnitTest(unittest.TestCase):
    # a bunch of tests here

if __name__ == '__main__':
    unittest.main(module=None)
</code></pre>

<p>The following commands do work:<br>
python -m unittest discover<br>
python -m unittest tests.test_problems  </p>

<p>The following do not.<br>
<strong>python3 -m unittest discover</strong></p>

<pre><code>ImportError: Failed to import test module: tests.test_problems
Traceback (most recent call last):
  File ""/usr/lib64/python3.6/unittest/loader.py"", line 428, in _find_test_path
    module = self._get_module_from_name(name)
  File ""/usr/lib64/python3.6/unittest/loader.py"", line 369, in _get_module_from_name
    __import__(name)
  File ""/home/me/code/project_euler/tests/test_problems.py"", line 5, in &lt;module&gt;
    import euler.problems as problems
  File ""/home/me/code/project_euler/euler/problems.py"", line 8, in &lt;module&gt;
    class ProjectEuler(euler.Euler):
AttributeError: module 'euler' has no attribute 'Euler'
</code></pre>

<p><strong>python3 -m unittest tests.test_problems</strong></p>

<pre><code>Traceback (most recent call last):
  File ""/usr/lib64/python3.6/runpy.py"", line 193, in _run_module_as_main
    ""__main__"", mod_spec)
  File ""/usr/lib64/python3.6/runpy.py"", line 85, in _run_code
    exec(code, run_globals)
  File ""/usr/lib64/python3.6/unittest/__main__.py"", line 18, in &lt;module&gt;
    main(module=None)
  File ""/usr/lib64/python3.6/unittest/main.py"", line 94, in __init__
    self.parseArgs(argv)
  File ""/usr/lib64/python3.6/unittest/main.py"", line 141, in parseArgs
    self.createTests()
  File ""/usr/lib64/python3.6/unittest/main.py"", line 148, in createTests
    self.module)
  File ""/usr/lib64/python3.6/unittest/loader.py"", line 219, in loadTestsFromNames
    suites = [self.loadTestsFromName(name, module) for name in names]
  File ""/usr/lib64/python3.6/unittest/loader.py"", line 219, in &lt;listcomp&gt;
    suites = [self.loadTestsFromName(name, module) for name in names]
  File ""/usr/lib64/python3.6/unittest/loader.py"", line 153, in loadTestsFromName
    module = __import__(module_name)
  File ""/home/me/code/project_euler/tests/test_problems.py"", line 5, in &lt;module&gt;
    import euler.problems as problems
  File ""/home/mvrakking/code/project_euler/euler/problems.py"", line 8, in &lt;module&gt;
    class ProjectEuler(euler.Euler):
AttributeError: module 'euler' has no attribute 'Euler'
</code></pre>

<p>I tried all kinds of options, but it breaks my program or my unit test. I can't find what is the difference between Python 2.7.13 and 3.6.2 that is causing this.</p>
",https://stackoverflow.com/questions/46456359/unittest-in-python-2-not-working-in-python-3,"['python', 'python-2.7', 'python-3.x', 'tdd', 'python-unittest']",1064,FALSE,1,1
How to assert if converter is applied on a type using Fluent Assertions,"<p>I need to apply some complex logic for creating map so i have used custom type converter as below:</p>

<pre><code>cfg.CreateMap&lt;ConsumerRequest,IEnumerable&lt;ProviderRequest&gt;&gt;().ConvertUsing&lt;RequestConverter&gt;();
</code></pre>

<p>I am using fluentassertions in unit testing and want to assert that ConsumerRequest has RequestConverter applied but not sure how to do it, I think I should be able to right an extension method which will assert the same with some message but not sure how to achieve this, any help will be really appreciated.  </p>
",https://stackoverflow.com/questions/41798791/how-to-assert-if-converter-is-applied-on-a-type-using-fluent-assertions,"['unit-testing', 'automapping', 'fluent-assertions']",352,TRUE,0,1
stub test cases are not showing in code coverage,"<p>I am doing my unit testing using spock framework. I am using stub to do my test. my unit test gave me success but when I checked my code coverage that is showing that code has not been included. Is it expected behaviour? if not how to resolve this?</p>

<p>below is my spcok framework code</p>

<pre><code>  class ConfigurationLoaderTest extends Specification {
    def ""loadConfigurationTest"" (){
        given:
        ConfigurationLoader configLoader = Stub()
        when:
        def rpcApiInfo= configLoader.loadConfiguration();
        then:
        rpcApiInfo != null
    }
    }
</code></pre>

<p>when I ran it it showing test case passed but my code coverage is still 0 for 'loadConfiguration' method</p>
",https://stackoverflow.com/questions/47748110/stub-test-cases-are-not-showing-in-code-coverage,"['unit-testing', 'code-coverage', 'spock']",149,FALSE,0,0
JUnit spring boot application,"<p>I am writing JUnit test cases for my Spring Boot Application in which dynamically data is generated through various APIs. I wanted to truncate all the test data after test cases are passed. But is it advisable to write a test case which will truncate the data at the end of Unit testing. But provided that the developed application does not have a delete API and the API is solely developed only for JUnit.  </p>
",https://stackoverflow.com/questions/47670813/junit-spring-boot-application,"['java', 'spring', 'unit-testing', 'spring-boot', 'junit']",106,TRUE,-1,1
How to show tests result report in TFS,"<p>I just started playing around with online version of TFS for build. I have written unit test using Qunit and nightwatch (uses selenium and node). I am running all the task via grunt. I want to show the test result in TFS for selenium end to end tests. For unit testing I run grunt task which execute Qunit and create a junit xml report which I share in the TFS build process. </p>

<p>Thanks</p>
",https://stackoverflow.com/questions/42122636/how-to-show-tests-result-report-in-tfs,"['selenium', 'junit', 'azure-devops', 'tfsbuild']",1102,TRUE,0,1
Cannot mock instance of Firebase Analytics for Android,"<p>I'm trying to mock an instance of Firebase Analytics for Android unit testing, but my Firebase variable remains undefined after I call Firebase's <code>getInstance()</code> method - which should initialize an instance of the FirebaseAnalytics class.</p>

<p>I'm using PowerMock and Android Studio. Here's my Test.java file (no tests yet - just trying to initialize a mock of the class):</p>

<pre><code>@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 18, manifest = 
Config.NONE)
@PowerMockIgnore({ ""org.mockito.*"", ""org.robolectric.*"", ""android.*"" })
@PrepareForTest({FirebaseAnalytics.class})
public class FirebaseTest {
    @Rule public PowerMockRule rule = new PowerMockRule();
    @Mock Application application;
    @Mock Analytics analytics;
    FirebaseAnalytics firebase;

    @Before
    public void setUp() {
        initMocks(this);

        /* mock context */
        when(analytics.getApplication()).thenReturn(application);

        PowerMockito.mockStatic(FirebaseAnalytics.class);

when(FirebaseAnalytics.getInstance(application)).thenReturn(firebase);  /* firebase remains null */
        PowerMockito.mockStatic(FirebaseAnalytics.class);
    }
</code></pre>

<p>FirebaseAnalytics is a final class, and getInstance() is a static final method. I'm not sure whether these may make mocking difficult. Any ideas are appreciated!</p>
",https://stackoverflow.com/questions/45964540/cannot-mock-instance-of-firebase-analytics-for-android,"['java', 'unit-testing', 'firebase', 'mockito', 'powermockito']",1463,FALSE,5,0
how to test react components with recompose hocs,"<p>recently started using recompose (<a href=""https://github.com/acdlite/recompose"" rel=""nofollow noreferrer"">https://github.com/acdlite/recompose</a>)</p>

<p>I wonder how should I approach unit testing components that are wrapped with some of hocs recompose provide? I love how entire class component can be replaced with functional approach but it totally not true in terms of unit tests.</p>

<p>For example with given list component</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>export const ListItem = toClass(pure(({ text }) =&gt; &lt;li&gt;{text}&lt;/li&gt;));
const renderItems = R.map(t =&gt; &lt;ListItem key={t} text={t} /&gt;);

export const ListComponent = toClass(({ todos, name, updateName, addTodo }) =&gt;
  &lt;div&gt;
    &lt;input onChange={updateName} value={name} /&gt;
    &lt;button onClick={() =&gt; addTodo(name)}&gt;add todo&lt;/button&gt;
    &lt;ul&gt;
      {renderItems(todos)}
    &lt;/ul&gt;
  &lt;/div&gt;
);

...

const List = compose(
  withReducer(""state"", ""dispatch"", listReducer, props =&gt; ({
    ...initialState,
    ...props
  })),
  withHandlers({
    updateName: ({ dispatch }) =&gt; e =&gt;
      dispatch({ type: ""UPDATE_NAME"", payload: e.target.value }),
    addTodo: ({ dispatch, name }) =&gt; name =&gt;
      dispatch({ type: ""ADD_TODO"", payload: name })
  }),
  flattenProp(""state"")
)(ListComponent);

export default List;</code></pre>
</div>
</div>
</p>

<p>How can I test children length with given props? I've tried something like this but it's not working.</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""true"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>it(""renders todos list"", () =&gt; {
    const component = shallow(&lt;List todos={[""todo1"", ""todo2"", ""todo3""]} /&gt;);
    expect(component.instance().children).toHaveLength(3);
  });</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/44660168/how-to-test-react-components-with-recompose-hocs,"['javascript', 'reactjs', 'recompose']",2778,TRUE,0,2
Karma unable to launch IE on VSO build agent(build server),"<p>It is a in house build server. We are running VSO build agent on Window Server 2012 and it has IE 11 installed on it.</p>

<p>VSO build agent is running under 'Network Service' user.</p>

<p>On the unit testing build step, Karma is able to launch chrome but not IE.</p>

<p><strong>Error</strong></p>

<pre><code>2017-06-14T18:10:38.5588660Z [33m14 06 2017 14:10:38.557:WARN [launcher]: [39mIE have not captured in 60000 ms, killing.
2017-06-14T18:10:38.7008770Z [32m14 06 2017 14:10:38.699:INFO [launcher]: [39mTrying to start IE again (1/2).
2017-06-14T18:11:38.7030837Z [33m14 06 2017 14:11:38.702:WARN [launcher]: [39mIE have not captured in 60000 ms, killing.
2017-06-14T18:11:38.8830954Z [32m14 06 2017 14:11:38.882:INFO [launcher]: [39mTrying to start IE again (2/2).
2017-06-14T18:12:38.8953023Z [33m14 06 2017 14:12:38.884:WARN [launcher]: [39mIE have not captured in 60000 ms, killing.
2017-06-14T18:12:39.0743168Z [31m14 06 2017 14:12:39.074:ERROR [launcher]: [39mIE failed 2 times (timeout). Giving up.
</code></pre>

<p>I even tried the suggestion in <a href=""https://stackoverflow.com/questions/31029087/karma-fails-to-launch-ie-on-team-city-build"">Karma fails to launch IE on Team City build</a></p>

<p>Still no luck. Am I missing something?</p>
",https://stackoverflow.com/questions/44552023/karma-unable-to-launch-ie-on-vso-build-agentbuild-server,"['internet-explorer', 'karma-jasmine', 'azure-pipelines', 'build-server']",102,FALSE,0,2
Why do I get &quot;Linker command failed&quot; error if I import my main target into my XCTest?,"<p>I'm trying to do some unit testing with Xcode, and I have some extensions in my main target I want to write tests for.</p>

<p>I try to import access to these with <code>@testable import MainProjectTarget</code> at the top of the <code>XCTestCase</code> subclass, but if I then try to run the tests, I get a <code>linker command failed with exit code 1</code> error. If I remove it, the tests run find (provided I don't try to access those extensions).</p>

<p>What am I doing wrong?</p>
",https://stackoverflow.com/questions/43299855/why-do-i-get-linker-command-failed-error-if-i-import-my-main-target-into-my-xc,"['ios', 'objective-c', 'xcode', 'cocoa-touch', 'xctest']",100,FALSE,0,1
DevOps with XPages on Premesis or PaaS like Bluemix,"<p>What is the best way to achieve DevOps with XPages.</p>

<blockquote>
  <p>Multiple Developers working as a team, On Premises Servers [Dev, QA,
  Prod] can we replicate to Bluemix? Source Control Automated Testing UI
  / Application, Unit testing business logic with testing framework, Automated Deployment</p>
</blockquote>

<p>IDE/Tools
Domino Designer; are there other ways?</p>

<p>Note: Use of Views when the data is in a NSF, otherwise data is in the cloud, or SQL.  No Forms or other classic Notes design elements.</p>

<p>What are your approaches to this?</p>
",https://stackoverflow.com/questions/41877024/devops-with-xpages-on-premesis-or-paas-like-bluemix,"['version-control', 'xpages', 'ibm-cloud', 'continuous-deployment', 'devops']",253,TRUE,5,1
Creation of Classes?,"<p>I am new in python and trying to figure out how to modularize my functions. My project is a unit testing framework for Restful APIs. For brevity I've simplified the code.</p>

<h1>type_parser.py</h1>

<pre><code>import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--type', help='a or b')
args = parser.parse_args()

def A(func):
    def return_func():
        if args.type == ""b"":
          return func()
        else:
          pass
    return return_func

def B(func):
    def return_func():
        if args.type == ""a"":
          return func()
        else:
          pass
    return return_func
</code></pre>

<h1>api_funcs.py</h1>

<pre><code>from type_parser import *

class ApiFunctions:

    @A
    def login():
        print ""cool""
    @B
    def logout()
        print ""not cool""
</code></pre>

<h1>main.py</h1>

<pre><code>from api_funcs import *

api = ApiFunctions()

def __main__():
    api.login()
    api.logout()

__main__()
</code></pre>

<h1>CLI</h1>

<pre><code>python main.py --type=a
</code></pre>

<h1>Outcome</h1>

<p>Expected:</p>

<pre><code>cool
</code></pre>

<p>Actual:</p>

<pre><code>TypeError: return_func() takes no arguments
</code></pre>

<p><em>It works if I take api functions out of a class and call it straight up, but I would want to make it more abstract since there will be 3 sets of APIs</em></p>

<h1>Update - I figured out the answer</h1>

<pre><code>class ApiFunctions:

    @A
    def login(self):
        print ""cool""
    @B
    def logout(self)
        print ""not cool""


def A(func):
        def return_func(self):
            if args.type == ""b"":
              return func(self)
            else:
              pass
        return return_func
</code></pre>
",https://stackoverflow.com/questions/41858008/creation-of-classes,"['python', 'class']",82,TRUE,2,1
Django Unit Tests doesn&#39;t run in Visual Studio Test Explorer,"<p>I'm trying to implement my Django (1.11.7, Python 3.6) unit testing in Visual Studio. When I run them in my terminal (python manage.py test) they run fine, while when executing from the VS Test Explorer it fails with an error saying:</p>

<pre><code>django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
</code></pre>

<p>I've read that newer Django versions require an explicit django.setup() to be called, so I've tried to add it both to setUpClass(cls) and to setUpTestData(cls).</p>

<pre><code>import django
from datamodel.models import Engagement, BusinessUnit
from django.contrib.auth.models import User
from django.test import TestCase, Client

class TestViewRPA(TestCase):
    @classmethod
    def setUpClass(cls):
        super(TestViewRPA, cls).setUpClass()
        django.setup()

    @classmethod
    def setUpTestData(cls):
        super(TestViewRPA, cls).setUpTestData()
        django.setup()
        User.objects.create_user('dummyuser')
        eng = Engagement.objects.create(name = 'Test Client', owner=User.objects.get(username='dummyuser'))
        businessunit = BusinessUnit.objects.create(name = 'Business Unit', engagement=eng)

    def test_get_industry_segment1(self):
        businessunit = BusinessUnit.objects.get(name = 'Business Unit')
        c = Client()
        response = c.get('/rpa/%d' % businessunit.id)
        self.assertContains(response, 'id"":1,""businessunit_set"":[{""id"":1,', status_code=200)
</code></pre>

<p>Result from executing from CLI</p>

<pre><code>...&gt;env\Scripts\python.exe manage.py test app
Creating test database for alias 'default'...
System check identified no issues (0 silenced).

----------------------------------------------------------------------
Ran 3 tests in 0.028s

OK
Destroying test database for alias 'default'...
</code></pre>

<p>Any ideas?
Thanks in advance</p>
",https://stackoverflow.com/questions/47381718/django-unit-tests-doesnt-run-in-visual-studio-test-explorer,"['python', 'django', 'unit-testing', 'visual-studio-2017']",584,TRUE,2,1
Unit test module that invokes private functions upon promise resolve,"<p>I'm new to unit testing in Node and hit a road block when it comes to promises. My module performs a search through the ApiController which then returns a promise. Depending on its resolve status, it invokes one of two private functions within the module.</p>

<p>Module:</p>

<pre><code>module.exports.process = function(req, res) {
  let searchTerm = req.query.searchValue;

  ApiController.fetchResults(searchTerm)
    .then((results) =&gt; onReturnedResults(results), (err) =&gt; onNoResults());

  function onReturnedResults(results) {
    req.app.set('searchResults', results);
    res.redirect('/results');
  }

  function onNoResults() {
    res.render('search/search', { noResultsFound: true });
  }
};
</code></pre>

<p>Test:</p>

<pre><code>var res = {
  viewName: '', data : {},
  render: function(view, viewData) {
    this.view = view;
    this.viewData = viewData;
  }
};

var req = { query: { searchValue: 'doesnotexist' } }

describe('When searching for results that do not exist', function() {
  it('should display a no results found message', function(done) {
    let expectedResult = {
      noResultsFound: true;
    }

    SearchController.process(req, res);

    // Assert...  
    expect(res.viewData).to.be.equal(expectedResult);
    done();
  });
})
</code></pre>

<p>What are the best practices around this and how can I 'mock' the fetchResults returned promise so that it doesn't actually fetch results from the API (whilst still invoking the private function)?</p>
",https://stackoverflow.com/questions/42595505/unit-test-module-that-invokes-private-functions-upon-promise-resolve,"['javascript', 'node.js', 'unit-testing', 'chai']",63,TRUE,2,1
How to patch built-in/extension types in python using mockito?,"<p>While using <a href=""http://mockito-python.readthedocs.io/en/latest/"" rel=""nofollow noreferrer"">mockito</a> for unit testing in python, I came across an issue that I cannot find a solution for. I am trying to patch the usage of <code>io.BytesIO</code> in a given class method. The following code shows a simplified version where the issue occurs:</p>

<pre><code>from mockito import mock, patch, when
from io import BytesIO

class Foo:
    def bar(self):
        buffer = io.BytesIO()
        # ...
        return buffer.getvalue()

def test_foo():
    bytesIO_mock = mock(strict=True)
    when(bytesIO_mock).getvalue().thenReturn('data')

    patch(BytesIO.__new__, lambda: bytesIO_mock)
    result = Foo().bar()
    assert result == 'data'
</code></pre>

<p>I am getting the following error when I execute the test:</p>

<pre><code>/venv/lib/python3.6/site-packages/mockito/mockito.py:270: in patch
when2(fn, Ellipsis).thenAnswer(replacement)
/venv/lib/python3.6/site-packages/mockito/mockito.py:245: in when2
return invocation.StubbedInvocation(theMock, name)(*args, **kwargs)
/venv/lib/python3.6/site-packages/mockito/invocation.py:284: in __call__
self.mock.stub(self.method_name)
/venv/lib/python3.6/site-packages/mockito/mocking.py:117: in stub
self.replace_method(method_name, original_method)
/venv/lib/python3.6/site-packages/mockito/mocking.py:108: in replace_method
self.set_method(method_name, new_mocked_method)

self = &lt;mockito.mocking.Mock object at 0x10d50cb38&gt;, method_name = '__new__'
new_method = &lt;function Mock.replace_method.&lt;locals&gt;.new_mocked_method at 0x10d753e18&gt;

    def set_method(self, method_name, new_method):
&gt;       setattr(self.mocked_obj, method_name, new_method)
E       TypeError: can't set attributes of built-in/extension type '_io.BytesIO'

/venv/lib/python3.6/site-packages/mockito/mocking.py:74: TypeError
</code></pre>

<p>Is there any solution to this issue, or is it just the case it is not possible to mock certain objects in python?</p>
",https://stackoverflow.com/questions/43031393/how-to-patch-built-in-extension-types-in-python-using-mockito,"['python', 'unit-testing', 'mocking', 'mockito']",1484,TRUE,2,1
How to write database-agnostic functions to make them easier to unit-test,"<p><strong>TLDR</strong>: What's the best way of unit-testing a function that uses a database as its datasource but that the datasource does not have to be a database (that is, the function isn't aware of where the data is coming from. e.g. it can be an object, etc.)?</p>

<p>=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=</p>

<p>I'm trying to find out what's the best practice for unit-testing functions that use a database as its datasource - which is passed through its parameter - but that the datasource does not have to be a database (e.g. it can be an object, etc.). The reason I add the clause, ""that the datasource does not have to be a database,"" is because I don't want to use a database during unit-tests. So, how do I write a function that is database-agnostic?</p>

<p>One possible approach is to provide an ""env"" parameter that holds the datasource, like so:</p>

<pre><code>type Env struct {
    DataSource  interface{}
}

func FunctionToTest(env Env) {
    switch et := (env.DataSource).(type) {
    case UserDatasource:
        userSource := (env.DataSource).(UserDatasource)
        user := userSource.getUser()
    default:
        // Throw error
    }
}

func FunctionToTest2(env Env) {
    switch et := (env.DataSource).(type) {
    case CredentialsDatasource:
        credentialSource := (env.DataSource).(CredentialsDatasource)
        password := credentialSource.getPassword()
    default:
        // Throw error
    }
}
</code></pre>

<p>The issue with this is that it seems ""hacky"" and it feels like there exists a better solution. The reason I want to learn how to do this is so that I can write unit-tests that mock the database.</p>

<p>I appreciate any and all input.</p>

<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/46880158/how-to-write-database-agnostic-functions-to-make-them-easier-to-unit-test,"['database', 'unit-testing', 'go']",695,TRUE,0,1
Convert Spring field injection to constructor injection (IntelliJ IDEA)?,"<p>I am convinced to convert my Spring Java field injection [@Autowired] to constructor injection (<a href=""http://vojtechruzicka.com/field-dependency-injection-considered-harmful/"" rel=""noreferrer"">among other reasons</a>, to facilitate mock unit testing)...</p>

<p><em>Is there a utility I can use to automatically do that Spring field to constructor injection conversion?</em></p>

<p>For example, IntelliJ IDEA has generation shortcuts for a lot of things (i.e: generate setters &amp; getters for fields); I'm hoping there's something similar to that... This is particularly useful when it is tedious to do the conversion manually, because a class to be converted already has numerous field-injected fields.</p>
",https://stackoverflow.com/questions/44008985/convert-spring-field-injection-to-constructor-injection-intellij-idea,"['java', 'spring', 'intellij-idea', 'dependency-injection', 'constructor-injection']",8881,TRUE,10,2
Why is the result from this controller action null?,"<p>I'm starting a new project from scratch. Currently I'm working through design of some elements and attempting to implement unit testing early on. The problem, the unit tests are failing due to what appears to be a null response from a controller action. In the Watch Window, <code>actionResult</code> displays ""Internal error in the expression evaluator"" and <code>contentResult</code> is null.</p>

<p>How do I fix this?</p>

<p>xunit 2.2.0.3545, Moq 4.7.63.0</p>

<p>Here is the unit test (xunit):</p>

<pre><code>// Used in the unit tests
private List&lt;City&gt; cities = new List&lt;City&gt;
{
 new City { City_Name = ""Chicago"", City_Code = 1 },
 new City { City_Name = ""New York"", City_Code = 2 },
 new City { City_Name = ""Seattle"", City_Code = 3 }
};

[Fact]
public async Task Get_AllCities_PropertiesArePopulated()
{
    // Arrange
    var mockService = new Mock&lt;ICityService&gt;();
    mockService.Setup(x =&gt; x.GetCities()).ReturnsAsync(this.cities);

    var controller = new CityController(mockService.Object);

    // Act
    IHttpActionResult actionResult = await controller.GetCities();
    var contentResult = actionResult as OkNegotiatedContentResult&lt;List&lt;City&gt;&gt;;

    foreach (var city in contentResult.Content)
    {
        // doesn't get here due to .Content being null.
    }
}
</code></pre>

<p>Here is my controller:</p>

<pre><code>public class CityController : ApiController
{
    private readonly ICityService cityService;

    public CityController(ICityService svc)
    {
        this.cityService = svc;
    }

    public async Task&lt;IHttpActionResult&gt; GetCities()
    {
        var cities = await this.cityService.GetCities();

        if (!cities.Any())
        {
            return this.BadRequest();
        }

        return this.Ok(cities);
    }
}
</code></pre>

<p>The service interface:</p>

<pre><code>public interface ICityService
{
    Task&lt;IEnumerable&lt;City&gt;&gt; GetCities();
}
</code></pre>
",https://stackoverflow.com/questions/45195758/why-is-the-result-from-this-controller-action-null,"['c#', 'unit-testing', 'asp.net-web-api', 'moq', 'xunit']",920,TRUE,1,1
"Warning: Failed prop type: The prop open is marked as required in Snackbar, but its value is undefined","<p>I'm trying to introduce <code>jest</code> snapshot tests to my app.</p>

<p><strong>LoginForm</strong> component</p>

<pre><code>render() {
    return (
    ...
    &lt;DynamicSnack
        dialogOpen={this.props.dialogOpen}
        snackOpen={this.props.snackOpen}
        snackTimer={this.props.snackTimer}
        snackMessage={this.props.snackMessage}
    /&gt;
    )
}
</code></pre>

<p><strong>DynamicSnack</strong> component</p>

<pre><code>import Snackbar from 'material-ui/Snackbar';

render() {
    let { snackOpen, snackTimer, snackMessage } = this.props

    return (
        &lt;Snackbar
            open={snackOpen}
            message={snackMessage}
            autoHideDuration={snackTimer}
            onRequestClose={this.closeSnack}
        /&gt;
    )
}
</code></pre>

<p><strong>LoginForm.spec.js</strong></p>

<pre><code>import React from 'react'
import renderer from 'react-test-renderer'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';

import LoginForm from '../../app/components/loginComponents/loginForm'

describe('LoginForm', () =&gt; {
    it('should render snapshot', () =&gt; {
        const component = renderer.create(
            &lt;MuiThemeProvider&gt;
                &lt;LoginForm /&gt;
            &lt;/MuiThemeProvider&gt;
        )
        const tree = component.toJSON()
        expect(tree).toMatchSnapshot()
    })
})
</code></pre>

<p><strong>Warnings</strong>:</p>

<p><a href=""https://i.stack.imgur.com/WJyyI.jpg"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/WJyyI.jpg"" alt=""enter image description here""></a></p>

<blockquote>
  <p>Warning: Failed prop type: The prop <code>message</code> is marked as required in <code>Snackbar</code>, but its value is <code>undefined</code>.<br>
  Warning: Failed prop type: The prop <code>open</code> is marked as required in <code>Snackbar</code>, but its value is <code>undefined</code>.</p>
</blockquote>

<p>I have tried importing the DynamicSnack component and even the Snackbar directly and manually add the properties <code>open={false} message={'w00f'}</code>  but nothing changes.</p>

<p>I'm new to unit testing and trying to start by learning <code>jest</code>.  </p>

<p><strong>How can i get rid of these warnings?</strong></p>
",https://stackoverflow.com/questions/46687271/warning-failed-prop-type-the-prop-open-is-marked-as-required-in-snackbar-but,"['javascript', 'reactjs', 'unit-testing', 'material-ui', 'jestjs']",23858,TRUE,7,2
React/enzyme: How to test for subcomponent?,"<p>This is how my <em>Messenger</em> Component looks like. As you can see there is the main component and a list component. The main component is exported as default.
With this everything is working as expected in my application.</p>

<p><strong>/imports/ui/components/messenger.jsx</strong></p>

<pre><code>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { Container, Segment, Loader, Header } from 'semantic-ui-react'

class Messenger extends Component {
  static get propTypes () {
    return {
      data: PropTypes.array,
      articleId: PropTypes.string,
      isLoading: PropTypes.bool
    }
  }

  render () {
    const { data, articleId, isLoading } = this.props

    if (isLoading) { return (&lt;Loader active inverted size='massive' className='animated fadeIn' /&gt;) }
    if (articleId) { return (&lt;MessengerList data={data} articleId={articleId} /&gt;) }

    return (
      &lt;Container&gt;
        &lt;Segment id='' className='m-b-1'&gt;
          &lt;Header as='h1'&gt;Title&lt;/Header&gt;
          &lt;MessengerList data={data} /&gt;
        &lt;/Segment&gt;
      &lt;/Container&gt;
    )
  }
}

class MessengerList extends Component {
  /* ... */
}

export default Messenger
</code></pre>

<p>Now I would like to do some unit testing for the main component using enzyme. This is how I am doing it, but the last test is failing as <code>MessengerList</code> is not defined. So how should this be done.</p>

<pre><code>import React from 'react'
import { expect } from 'meteor/practicalmeteor:chai'
import { shallow } from 'enzyme'

import { Container, Loader } from 'semantic-ui-react'
import Messenger from '/imports/ui/components/messenger.jsx'

describe('&lt;Messenger /&gt;', () =&gt; {
  const defaultProps = {
    data: [],
    articleId: '',
    isLoading: true
  }

  it('should show &lt;Loader /&gt; while loading data', () =&gt; {
    const wrapper = shallow(&lt;Messenger {...defaultProps} /&gt;);
    expect(wrapper.exists()).to.be.true
    expect(wrapper.find(Loader).length).to.equal(1)
  })
  it('should show &lt;Container /&gt; data has been loaded', () =&gt; {
    defaultProps.isLoading = false
    const wrapper = shallow(&lt;Messenger {...defaultProps} /&gt;);
    expect(wrapper.find(Container).length).to.equal(1)
    expect(wrapper.find(Loader).exists()).to.be.false
  })
  it('should show &lt;MessengerList /&gt; if articleID is given', () =&gt; {
    defaultProps.articleID = 'dummy'
    defaultProps.isLoading = false
    const wrapper = shallow(&lt;Messenger {...defaultProps} /&gt;);
    expect(wrapper.find(MessengerList).length).to.equal(1)
    expect(wrapper.find(Loader).exists()).to.be.false
  })
})
</code></pre>

<p>I do not want to change <code>export default Messenger</code></p>
",https://stackoverflow.com/questions/45598423/react-enzyme-how-to-test-for-subcomponent,"['javascript', 'reactjs', 'unit-testing', 'enzyme']",6174,TRUE,7,1
How can I write unit tests for WatchKit?,"<p>I want to write unit tests for my WatchKit app extension, but I'm not sure how it should be done. According to <a href=""https://www.raywenderlich.com/94672/watchkit-faq"" rel=""nofollow noreferrer"">this</a> faq I should be able to add a test target for the extension, but in the template panel I can only see 'iOS Unit Testing Bundle'. If I create one, I have no idea how to proceed from there. The project won't build because of a linker error <code>&lt;unit test build path&gt; compiled with newer version of Swift language (3.0) than previous files (2.0) for architecture x86_64</code>. Without the test target the project builds fine. I'm using Xcode 8.2.1</p>
",https://stackoverflow.com/questions/41827105/how-can-i-write-unit-tests-for-watchkit,"['swift', 'xcode8', 'watchkit']",252,FALSE,4,0
Create unit test for View() with a List in ASP.net core MVC application,"<p>I am new in unit testing. I have a controller - <code>StudentsController</code> with dependency injection and there my <code>Index()</code> method:</p>

<pre><code>public class StudentsController : Controller
{
    public readonly UniversityContext _context;//Database
    public StudentsController(UniversityContext context)
    {
        _context = context;    
    }//Constructor with database
    // GET: Students
    public async Task&lt;IActionResult&gt; Index()
    {
        return View(await _context.Students.ToListAsync());
    }
}
</code></pre>

<p>Next i need to write a correct unit test code, that check, if:</p>

<blockquote>
  <p>1) a View() have a list with my students</p>
  
  <p>2) The query with students is not null.</p>
</blockquote>

<p>I read about Mock objects, but I don't know how to write the correct code. My code that I wrote so far:</p>

<pre><code>public class StudentsControllerTests
{
    [Fact]
    public async Task Index_ReturnsAViewResult_WithAListOfStudents()
    {
        var mockRepo = new Mock&lt;UniversityContext&gt;();
        mockRepo.Setup(repo =&gt; repo.Students.ToList()).Returns(GetTestStudents());//There i get following error:Expression references a method that does not belong to the mocked object
        var controller = new StudentsController(mockRepo.Object);

        // Act
        var result = controller.Index();

        //// Assert
        var viewResult = Assert.IsType&lt;ViewResult&gt;(result);
        var model = Assert.IsAssignableFrom&lt;IEnumerable&lt;Student&gt;&gt;(
            viewResult.ViewData.Model);
        Assert.NotNull(model);//Second Condition

    }
    public List&lt;Student&gt; GetTestStudents()
    {
        var sessions = new List&lt;Student&gt;();
        sessions.Add(new Student()
        {
            bDate = new DateTime(1994, 7, 2),
            Name = ""Test One""
        });
        sessions.Add(new Student()
        {
            bDate = new DateTime(1995, 7, 1),
            Name = ""Test Two""
        });
        return sessions;
    }
}
</code></pre>

<p>Can someone explain me, how to correct my code?</p>
",https://stackoverflow.com/questions/45276907/create-unit-test-for-view-with-a-list-in-asp-net-core-mvc-application,"['entity-framework', 'unit-testing', 'asp.net-core', 'asp.net-core-mvc', 'moq']",1381,TRUE,1,1
Cannot Convert &#39;MyClass&#39; to &#39;MyClass&#39;,"<p>I am trying to create a Stub class for Unit Testing purposes.  The Stub points to the EXACT SAME <code>EmployeeData</code> class definition, but the compiler thinks they are different, somehow.  As a result I keep getting the following message:</p>

<blockquote>
  <p>Cannot implicitly convert type
  'MeasurementContracts.Business.Services.EmployeeData' to
  'EmployeeData'</p>
</blockquote>

<ul>
<li>There ARE NO OTHER definitions for 'EmployeeData'</li>
<li>For some reason it ""thinks"" there are 2</li>
</ul>

<p><strong>What would cause this?</strong></p>

<p><a href=""https://i.stack.imgur.com/ajA8K.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ajA8K.png"" alt=""enter image description here""></a></p>

<p><strong>THE CLASS LOOKS LIKE:</strong> <br/></p>

<pre><code>namespace MeasurementContracts.Business.Services
{
    /// &lt;summary&gt;A data service model&lt;/summary&gt;
    public class EmployeeData
    {
        public int EmployeeId { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public string MiddleName { get; set; }

        public string EmailAddress { get; set; }

        public string KnownAs { get; set; }

        public string Login { get; set; }

        public string DomainName { get; set; }

        public string EmployeeStatusName { get; set; }

        public string WorkNumber { get; set; }

        public string SystemPersonType { get; set; }

        public string PersonType { get; set; }

        public string CellPhoneNumber { get; set; }

        public string OrganizationOrCostCenter { get; set; }

        public string OrganizationalLevel1Description { get; set; }

        public string PositionName { get; set; }

        public int SupervisorId { get; set; }

        public string GetName(bool useKnowAs = true)
        {
            if (useKnowAs &amp;&amp; !string.IsNullOrWhiteSpace(this.KnownAs))
                return $""{this.KnownAs} {this.LastName}"";

            return $""{this.FirstName} {this.LastName}"";
        }

    }
}
</code></pre>

<p><strong>THE STUB LOOKS LIKE:</strong> <br/></p>

<pre><code>namespace MeasurementContracts.UnitTests
{
    using OData.Client;
    using MeasurementContracts.Business.Services;
    using System;
    using System.Collections.Generic;
    using System.Linq;

    /// &lt;summary&gt;A proxy stub&lt;/summary&gt;
    public class ODataProxyStub : ODataProxy
    {
        #region &lt;Constructors&gt;

        public ODataProxyStub()
        {
            Entities = new List&lt;EmployeeData&gt;();
        }

        #endregion

        #region &lt;Properties&gt;

        public List&lt;EmployeeData&gt; Entities { get; set; }

        #endregion

        #region &lt;Properties&gt;

        public override EmployeeData GetItem&lt;EmployeeData&gt;(string query)
        {
            // This is NOT working?
            return Entities.FirstOrDefault();
        }

        public override IEnumerable&lt;EmployeeData&gt; GetList&lt;EmployeeData&gt;(string query)
        {
            throw new NotImplementedException();
        }

        public override EmployeeData Post&lt;EmployeeData&gt;(string query, IEnumerable&lt;object&gt; parameters)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
</code></pre>

<p><strong>THE PROXY BASE LOOKS LIKE:</strong> <br/></p>

<pre><code>namespace OData.Client
{
    public class ODataProxy
    {
        protected readonly HttpClient Client;

        public ODataProxy();

        public string BaseUrl { get; set; }

        public virtual T GetItem&lt;T&gt;(string query);
        public virtual IEnumerable&lt;T&gt; GetList&lt;T&gt;(string query);
        public virtual T Post&lt;T&gt;(string query, IEnumerable&lt;object&gt; parameters);
    }
}
</code></pre>
",https://stackoverflow.com/questions/46055480/cannot-convert-myclass-to-myclass,"['c#', 'linq']",117,TRUE,1,1
C# Debugging an Action,"<p>I have a .net core w/ .Net Framework project with a respective Test project. I'm using the <a href=""http://xbehave.github.io/"" rel=""nofollow noreferrer"">xBehave</a> xunit extension for unit testing. xBehave allows you to write what looks like a string extension that takes an Action.</p>



<pre class=""lang-c# prettyprint-override""><code>public void Should_Create_Request()
 {
     ""Given a Create OrderCommand Request""
                    .x(() =&gt; _orderCommand = Create());
 }
</code></pre>

<p>When debugging  this unit test, if I set a breakpoint in the Create method, the breakpoint never gets hit. The tests run successful, however I need to be able to step into code contained within the expression body.</p>
",https://stackoverflow.com/questions/42255142/c-debugging-an-action,"['c#', 'debugging', 'xbehave.net']",766,FALSE,1,0
[Ext.Loader]: Some requested files failed to load,"<p>While running command as <strong>karma start karma.conf.js</strong> for <strong>extjs application unit testing with mocha</strong>, it is throwing the above error.
My code looks like this:
I have set the paths variable as: </p>

<pre><code>**var paths** = {
        'Demo': 'packages/demo/src',
        'NewR3': 'extjs/r3/app',
        'BasicFiles' : 'packages',
        'Portal': 'extjs/portal/app',
        'Ext.ux': 'frameworks/extjs/src/ux'
    };

Ext.Loader.setConfig({
    enabled: true,
    paths: paths,
    disableCaching: true    
});

Ext.require([
    'Ext.ux.grid.*',
    'Ext.ux.data.*',
    'Ext.ux.toolbar.Paging',
    'Ext.ux.form.MultiSelect',
    'Ext.ux.IFrame'
]);

Ext.require([
    'BasicFiles.deft.deft-debug',
    'BasicFiles.PM.PM-debug',
    'Portal.util.PortalDataProvider',
    'Portal.util.PortalUtil',

]);
</code></pre>

<p>WARN [web-server]: 404: /base/extjs/portal/app/util/Startup.js?_dc=1483346775630
WARN [web-server]: 404: /base/extjs/portal/app/util/ResourceLoader.js?_dc=1483346775630
WARN [web-server]: 404: /base/extjs/portal/app/view/Viewport.js?_dc=1483346775630
Warnings I get after running the above command:</p>
",https://stackoverflow.com/questions/41424570/ext-loader-some-requested-files-failed-to-load,"['extjs', 'karma-runner']",3199,TRUE,1,1
Adding unit tests for javascript in a C++ project,"<p>I'm working on a C++ codebase and I use CPPUnit as the unit testing framework. recently I added to the project a javascript browser addin that communicates with an external process using native messaging port.</p>

<p>I want to add unit tests for the javascript addin code and mock out the native messaging port. can I somehow do it from CPPUnit by wrapping the javascript code without setting up a new javascript unit tests framework? what are my options?</p>
",https://stackoverflow.com/questions/41997914/adding-unit-tests-for-javascript-in-a-c-project,"['javascript', 'c++', 'unit-testing', 'mocking']",48,FALSE,1,0
Why &quot;new&quot; keyword in constructor/fields is inflexible for unit tests?,"<p>I have been following some guidelines with Guice and it mentions that you should never use <code>new</code> in constructor or in fields, because than it is inflexible design preventing from proper unit testing. </p>

<p>What does that mean?</p>

<p>And an additional question, if my function reads an XML file and parses it, it is a scope of a unit test to try to catch all possible incorrect input values? In UI, we do not write unit tests for input validation..</p>
",https://stackoverflow.com/questions/42153571/why-new-keyword-in-constructor-fields-is-inflexible-for-unit-tests,"['java', 'unit-testing']",541,TRUE,1,1
Python Mock: How to inject an object at a specific point in a function?,"<p>Given multiple calls to an object (say subprocess calls) in a function, is it possible to mock a specific subprocess call? The goal would be to pinpoint a specific logic case to manipulate for unit testing. Or is this just a limitation of mocking (or SDET abilities), and I need to break up the bigger function into smaller ones so that they only contain one subprocess call and each one can be mocked and unit tested individually?</p>
",https://stackoverflow.com/questions/44016441/python-mock-how-to-inject-an-object-at-a-specific-point-in-a-function,"['python', 'python-2.7', 'unit-testing', 'mocking', 'python-unittest']",344,TRUE,1,1
UnitTest - Wait expectation ignored with NSPredicate,"<p>I'm having trouble with with waiting in unit testing with latest XCTestCase features. </p>

<p>this is what I have </p>

<pre><code>viewModel.getLocations()
let loaded = NSPredicate(format: ""boolAttribute == %@"", NSNumber(value: true))
let dataLoaded = XCTNSPredicateExpectation(predicate: loaded, object: viewModel.dataExist())
wait(for: [dataLoaded], timeout: 5)
</code></pre>

<p>So I need to wait for Network loading to happen to continue, and it does wait. But it always get timedOut although, when inspecting my vars, the data is set.</p>

<p>In the end the test will succeed if I catch the result of the waiting and then proceed even if timedOut, but it's just a hack...</p>

<p>Thx for your help</p>
",https://stackoverflow.com/questions/46914518/unittest-wait-expectation-ignored-with-nspredicate,"['ios', 'swift', 'xcode', 'unit-testing']",1190,TRUE,1,2
Kafka : Cannot create embedded kafka server,"<p>Update:</p>

<p>Here is the sample code I am trying to follow.</p>

<p><a href=""https://gist.github.com/asmaier/6465468"" rel=""nofollow noreferrer"">https://gist.github.com/asmaier/6465468</a></p>

<p>It should work with kafka 0.10.x</p>

<p>I am trying to create an embedded kafka server as</p>

<pre><code>        EmbeddedZookeeper zkServer = new EmbeddedZookeeper();
        String zkConnect = ZKHOST + "":"" + zkServer.port();
        ZkClient zkClient = new ZkClient(zkConnect, 30000, 30000, ZKStringSerializer$.MODULE$);
        ZkUtils zkUtils = ZkUtils.apply(zkClient, false);

        // setup Broker
        Properties brokerProps = new Properties();
        brokerProps.setProperty(""zookeeper.connect"", zkConnect);
        brokerProps.setProperty(""broker.id"", ""0"");
        brokerProps.setProperty(""log.dirs"", Files.createTempDirectory(""kafka-"").toAbsolutePath().toString());
        brokerProps.setProperty(""listeners"", ""PLAINTEXT://:"" + BROKERPORT);
        brokerProps.setProperty(""advertised.listeners"", ""PLAINTEXT://"" + BROKERHOST +"":"" + BROKERPORT);
        //brokerProps.setProperty(""security.inter.broker.protocol"",""PLAINTEXT"");
        KafkaConfig config = new KafkaConfig(brokerProps);
        Time mock = new MockTime();
        KafkaServer kafkaServer = TestUtils.createServer(config, mock);
        logger.info(""TestKafkaServer created"");
</code></pre>

<p>but i get</p>

<pre><code>java.lang.NoSuchFieldError: DEFAULT_SASL_ENABLED_MECHANISMS
    at kafka.server.Defaults$.&lt;init&gt;(KafkaConfig.scala:183)
    at kafka.server.Defaults$.&lt;clinit&gt;(KafkaConfig.scala)
    at kafka.log.Defaults$.&lt;init&gt;(LogConfig.scala:35)
    at kafka.log.Defaults$.&lt;clinit&gt;(LogConfig.scala)
    at kafka.log.LogConfig$.&lt;init&gt;(LogConfig.scala:246)
    at kafka.log.LogConfig$.&lt;clinit&gt;(LogConfig.scala)
    at kafka.server.KafkaConfig$.&lt;init&gt;(KafkaConfig.scala:270)
    at kafka.server.KafkaConfig$.&lt;clinit&gt;(KafkaConfig.scala)
    at kafka.server.KafkaConfig.&lt;init&gt;(KafkaConfig.scala:795)
    at kafka.server.KafkaConfig.&lt;init&gt;(KafkaConfig.scala:797)
    at com.ibm.whi.bap.helper.test.kafka.KafkaServerTest.&lt;init&gt;(KafkaServerTest.java:56)
    at com.ibm.whi.bap.helper.test.kafka.KafkaTest.checkAllProperties(KafkaTest.java:115)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
    at org.junit.rules.TestWatchman$1.evaluate(TestWatchman.java:48)
    at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

java.lang.NullPointerException
    at com.ibm.whi.bap.helper.test.kafka.KafkaTest.tearDown(KafkaTest.java:58)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:37)
    at org.junit.rules.TestWatchman$1.evaluate(TestWatchman.java:48)
    at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
</code></pre>

<p>at</p>

<pre><code>KafkaConfig config = new KafkaConfig(brokerProps);
</code></pre>

<p>what am i doing wrong? I tried to play with </p>

<pre><code>brokerProps.setProperty(""security.inter.broker.protocol"",""PLAINTEXT"");
</code></pre>

<p>but nothing worked. I just want to create an embedded kafka server for unit testing. I do not want to set up any sort of security at all.</p>

<p>here is my maven</p>

<pre><code>        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.kafka&lt;/groupId&gt;
            &lt;artifactId&gt;kafka-clients&lt;/artifactId&gt;
            &lt;version&gt;0.10.1.0&lt;/version&gt;
            &lt;classifier&gt;test&lt;/classifier&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.kafka&lt;/groupId&gt;
            &lt;artifactId&gt;kafka_2.11&lt;/artifactId&gt;
            &lt;version&gt;0.10.1.0&lt;/version&gt;
            &lt;classifier&gt;test&lt;/classifier&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
</code></pre>
",https://stackoverflow.com/questions/46914225/kafka-cannot-create-embedded-kafka-server,"['java', 'apache-kafka']",6690,TRUE,1,1
Angular unit test mockbackend SPEC HAS NO EXPECTATIONS,"<p>I am using Jasmine &amp; Karma for unit testing angular app . I have wrote unit test like this </p>

<pre><code>it('should match request object', inject([UserService, MockBackend], (userService: UserService, mockBackend) =&gt; {
    mockBackend.connections.subscribe((connection: MockConnection) =&gt; {
        expect(connection.request.method).toEqual(RequestMethod.Post);
        expect(connection.request.json().getUserProfileRequest).toEqual({
            userid: '1234',
        });

        connection.mockRespond(new Response(new ResponseOptions({
            body: UsersMockData.GET_USER_PROFILE,
        })));
    });

    usersService.getUserProfile(1234)
        .subscribe(data =&gt; {
            expect(data).toBe(UsersMockData.GET_USER_PROFILE);
        });
}));
</code></pre>

<p>Everything works fine and no issue now when I split test cases in to two separate test cases I write code like this </p>

<pre><code>it('Check userProfile request', inject([UserService, MockBackend], (userService: UserService, mockBackend) =&gt; {
    mockBackend.connections.subscribe((connection: MockConnection) =&gt; {
        expect(connection.request.method).toEqual(RequestMethod.Post);
        expect(connection.request.json()getUserProfileRequest).toEqual({
            userid: '1234',
        });
    });
}));

it('check return data from service', inject([UserService, MockBackend], (userService: UserService, mockBackend) =&gt; {

 connection.mockRespond(new Response(new ResponseOptions({
                body: UsersMockData.GET_USER_PROFILE,
            })));

  usersService.getUserProfile(1234)
    .subscribe(data =&gt; {
        expect(data).toBe(UsersMockData.GET_USER_PROFILE);
    });
}));
</code></pre>

<p>Both of these test cases are having expect statement but when I execute test cases , I see a message <strong>SPEC HAS NO EXPECTATIONS</strong> for both test cases . I am wondering why it shows spec has no expectations.</p>
",https://stackoverflow.com/questions/42145963/angular-unit-test-mockbackend-spec-has-no-expectations,"['angularjs', 'unit-testing', 'angular', 'jasmine', 'karma-jasmine']",2015,TRUE,1,1
Ceedling project file does not recognize paths and libraries,"<p>I wanted to use ceedling for unit testing C Code for STM32 family.
I installed it as shown on their page on <a href=""https://github.com/ThrowTheSwitch/Ceedling"" rel=""nofollow noreferrer"">GitHub Ceedling</a> and run successfully the example tests.</p>
<p>The <strong>project.yml</strong> file I have modified the paths because I have a different path for header files (path: include) as the source files (path: src):</p>
<pre><code>:paths:
  :test:
    - +:test/**
    - -:test/support
  :source:
    - build/STM32F2xx_StdPeriph_Driver/include/**
    - build/STM32F2xx_StdPeriph_Driver/src/**
    - include/**
    - src/**
  :support:
    - test/support


  :defines:
    :commmon: &amp;common_defines
      #Define for header files
      - STM32F2XX


:libraries:
  :placement: :end
  :flag: &quot;${1}&quot;  # or &quot;-L ${1}&quot; for example
  :common: &amp;common_libraries []
  :test:
    - *common_libraries
      #toolchain of STM32F2
    - build/STM32F2xx_StdPeriph_Driver/include/**
    - build/STM32F2xx_StdPeriph_Driver/src/**
    - build/STM32F2xx/include/
</code></pre>
<p>But somehow the path and libraries does not get recognized and I get error for unknown variables.</p>
<p>Is my <strong>.yml</strong> file wrong?</p>
",https://stackoverflow.com/questions/46068192/ceedling-project-file-does-not-recognize-paths-and-libraries,"['c', 'unit-testing', 'testing', 'makefile', 'stm32']",2105,TRUE,1,1
Executing a specific method from a source class using unit test,"<p>Is there an unit testing annotation or feature flag that I can insert in my java source code so that the method will only be triggered when running unit test? </p>

<p>For Example:</p>

<pre><code>public class A {        
    @Annotation
    public void fooA() { }

    public void fooB() { }
}
</code></pre>

<p>My Unit test class:</p>

<pre><code>public class TestA {
  ...
}
</code></pre>

<p>In this scenario, when I run my unit test class TestA, I want to execute <strong>fooA() and fooB()</strong>. </p>

<p>But if I would like to run my prod source code that includes classA, then only function <strong>fooB() will be executed and not fooA()</strong>.</p>
",https://stackoverflow.com/questions/43592683/executing-a-specific-method-from-a-source-class-using-unit-test,"['java', 'unit-testing']",79,TRUE,1,3
Use assertCountEqual for lists in an asserDictEqual?,"<p>I am new to unit testing, and I'm trying to run a test to check if two dictionaries are the same <em>without taking the order of the elements in values into account</em>. When I'm trying:</p>

<pre><code>import unittest
dic1 = {'key': [1,2]}
dic2 = {'key': [2,1]}

class TestExample (unittest.TestCase):

def test_dicEqual(self):
    self.assertDictEqual(dic1, dic2)

tester = TestExample()
tester.test_dicEqual()
</code></pre>

<p>I get :</p>

<pre><code>AssertionError                            Traceback (most recent call last)
AssertionError: {'key': [1, 2]} != {'key': [2, 1]}
- {'a': [1, 2]}
?         ---

+ {'a': [2, 1]}
?        +++
</code></pre>

<p>Is there a way to check the content of the dictionary without taking the order into account ? Right now the solution I have come up with is to iterate over the keys of the dictionary :</p>

<pre><code>def test_dictequal_iterate(self):
    for key, value in dic1 :
        self.assertCountEqual(value, dic2[key])
</code></pre>

<p>But this solution doesn't return an overview as clear as assertDictEqual.</p>
",https://stackoverflow.com/questions/42002115/use-assertcountequal-for-lists-in-an-asserdictequal,"['python', 'python-unittest']",778,FALSE,3,1
For what values is CORRECT used for Input or Ouput values?,"<p>I am learning the concept of Unit testing and came across below technique.</p>

<blockquote>
  <p>Right: Are the results right?</p>
  
  <p>B: Are all the Boundary conditions <strong>CORRECT</strong>?</p>
  
  <p>I: Can we check inverse relationships?</p>
  
  <p>C: Can we cross-check results using other means?</p>
  
  <p>E: Can we force error conditions to happen?</p>
  
  <p>P: Are performance characteristics within bounds?</p>
</blockquote>

<p>I am confused with the below area:</p>

<blockquote>
  <p>B: Are all the boundary conditions <strong>CORRECT</strong>?</p>
</blockquote>

<p>Q) What does CORRECT test, input or the output values?</p>
",https://stackoverflow.com/questions/41714377/for-what-values-is-correct-used-for-input-or-ouput-values,"['unit-testing', 'mocking', 'tdd']",51,TRUE,0,1
How to test gRPC APIs?,"<p>I have been assigned to test a gRPC API (written in Golang) but I don't know how to go about testing it and I couldn't find any tutorials online for this type of testing. The only method that I can think of is to write unit tests to test the methods themselves but I would like to also test it with a client. For example, I have tested REST APIs in the past using JMeter as a client to send requests and verify the response data. Is there a method for testing gRPC APIs with a client or is unit testing the only way?</p>
",https://stackoverflow.com/questions/47764448/how-to-test-grpc-apis,"['testing', 'go', 'rpc', 'grpc']",32678,TRUE,20,7
How do I use CliRunner to test a script?,"<p>I have a script that uses click to get input arguments. According to their <a href=""http://click.pocoo.org/4/testing/"" rel=""noreferrer"">documentation</a> CliRunner can be used to make unit testing:</p>

<pre><code>import click
from click.testing import CliRunner

def test_hello_world():
    @click.command()
    @click.argument('name')
    def hello(name):
        click.echo('Hello %s!' % name)

    runner = CliRunner()
    result = runner.invoke(hello, ['Peter'])
    assert result.exit_code == 0
    assert result.output == 'Hello Peter!\n'
</code></pre>

<p>This is done for a tiny hello-world function that is written in-line in the test.
My queation is:</p>

<p><strong>How do I perform the same test for a script in a different file??</strong></p>

<p>Example of script that uses click:</p>

<pre><code>import click
@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name', help='The person to greet.')
def hello(count, name):
    """"""Simple program that greets NAME for a total of COUNT times.""""""
    for x in range(count):
        click.echo('Hello %s!' % name)

if __name__ == '__main__':
    hello()
</code></pre>

<p>(from <a href=""http://click.pocoo.org/5/documentation/"" rel=""noreferrer"">click documentation</a>)</p>

<p><strong>EDIT:</strong></p>

<p>If I try to run it as suggested in Dan's answer, after a couple of hours it shows this error:</p>

<pre><code>test_hello_world (__main__.TestRasterCalc) ... ERROR

======================================================================
ERROR: test_hello_world (__main__.TestRasterCalc)
----------------------------------------------------------------------
Traceback (most recent call last):
  File ""/src/HelloClickUnitTest.py"", line 35, in test_hello_world
    result = runner.invoke(hello, ['Peter'])
  File ""/usr/local/lib/python2.7/dist-packages/click/testing.py"", line 299, in invoke
    output = out.getvalue()
MemoryError

----------------------------------------------------------------------
Ran 1 test in 9385.931s

FAILED (errors=1)
</code></pre>
",https://stackoverflow.com/questions/45235045/how-do-i-use-clirunner-to-test-a-script,"['python', 'python-unittest', 'python-click']",7679,TRUE,6,3
Ember confused on testing route hooks and actions,"<p>I am just starting looking at testing with Ember and I am bit confused on how to test the following:</p>

<p>1 - Route hooks</p>

<p>Here's an example what I have, I am not sure if should be done through unit testing or user acceptance testing? How do I triggers the hooks, wait the promise etc.?</p>

<pre><code>/**
 * Model hook.
 */
model() {
    return this.modelFor('new');
},

/**
 * AfterModel hook.
 */
afterModel() {
    /**
     * Setup provinces.
     */
    return new Ember.RSVP.Promise((resolve) =&gt; {
        const provinces = Ember.A([
            Ember.Object.create({
                code: 'AB',
                description: 'Alberta'
            }),
            Ember.Object.create({
                code: 'BC',
                description: 'British Columbia'
            }),
            Ember.Object.create({
                code: 'MB',
                description: 'Manitoba'
            }),
            Ember.Object.create({
                code: 'NB',
                description: 'New Brunswick'
            }),
            Ember.Object.create({
                code: 'NL',
                description: 'Newfoundland and Labrador'
            }),
            Ember.Object.create({
                code: 'NS',
                description: 'Nova Scotia'
            }),
            Ember.Object.create({
                code: 'NT',
                description: 'Northwest Territories'
            }),
            Ember.Object.create({
                code: 'NU',
                description: 'Nunavut'
            }),
            Ember.Object.create({
                code: 'ON',
                description: 'Ontario'
            }),
            Ember.Object.create({
                code: 'PE',
                description: 'Prince Edward Island'
            }),
            Ember.Object.create({
                code: 'QC',
                description: 'Quebec'
            }),
            Ember.Object.create({
                code: 'SK',
                description: 'Saskatchewan'
            }),
            Ember.Object.create({
                code: 'YK',
                description: 'Yukon'
            })
        ]);
        resolve(provinces);
    }).then((provinces) =&gt; {
        this.set('provinces', provinces);
    });
},

/**
 * Setup controller hook.
 * @param controller the controller
 * @param model The model
 */
setupController(controller, model) {
    this._super(controller, model);
    controller.set('provinces', this.get('provinces'));
}
</code></pre>

<p>2 - Controller/Route Actions</p>

<p>Here I mostly just either going to different route or displaying error message, is this something that should be unit tested? if so how? </p>

<pre><code>actions: {
    /**
     * Go previous step
     */
    back() {
        this.transitionToRoute('new.step1');
    },
    /**
     * Go to next step.
     */
    next() {
        this.get('model').save().then(() =&gt; {
            this.transitionToRoute('new.step3');
        }).catch(() =&gt; {
            this.get('notificationService')
                .notifyError('common.error.system_error');
        });
    }
}
</code></pre>
",https://stackoverflow.com/questions/41875368/ember-confused-on-testing-route-hooks-and-actions,"['ember.js', 'ember-qunit']",509,TRUE,3,1
TableControllers Unit test,"<p>So I'm trying to write a simple tablecontroller Unit test for my backend??</p>

<p>I havent been able to do so, all I've achieve is writing unit testing for ApiControllers but is there a way to write a Unit test for TableControllers?</p>

<p>What I'll like to do is this:</p>

<pre><code>public class AuctionController : TableController&lt;Auction&gt;
{
    protected override void Initialize(HttpControllerContext controllerContext)
    {
        base.Initialize(controllerContext);
        MobileServiceContext context = new MobileServiceContext();
        DomainManager = new EntityDomainManager&lt;Auction&gt;(context, Request);
    }

    // GET tables/Auction
    public IQueryable&lt;Auction&gt; GetAllAuction()
    {
        return Query(); 
    }

    // GET tables/Auction/48D68C86-6EA6-4C25-AA33-223FC9A27959
    public SingleResult&lt;Auction&gt; GetAuction(string id)
    {
        return Lookup(id);
    }

    // PATCH tables/Auction/48D68C86-6EA6-4C25-AA33-223FC9A27959
    public Task&lt;Auction&gt; PatchAuction(string id, Delta&lt;Auction&gt; patch)
    {
        return UpdateAsync(id, patch);
    }

    // POST tables/Auction
    public async Task&lt;IHttpActionResult&gt; PostAuction(Auction item)
    {
        Auction current = await InsertAsync(item);
        return CreatedAtRoute(""Tables"", new { id = current.Id }, current);
    }

    // DELETE tables/Auction/48D68C86-6EA6-4C25-AA33-223FC9A27959
    public Task DeleteAuction(string id)
    {
        return DeleteAsync(id);
    }
}
</code></pre>

<p>and i wish to make a test controller like this one:</p>

<pre><code>[TestClass]
public class AuctionControllerTests
{
    private readonly AuctionController _controller;

    public AuctionControllerTests()
    {
        _controller = new AuctionController();
    }

    [TestMethod]
    public void Fetch_all_existing_items()
    {
        Assert.Equal(2, _controller.GetAllTodoItems().ToList().Count);
    }
}
</code></pre>

<p>how can I possibly be able to get this to work??? Please I would appreciate your help a lot.</p>
",https://stackoverflow.com/questions/41728417/tablecontrollers-unit-test,"['c#', 'unit-testing', 'azure']",613,TRUE,0,2
How to pass Unit test after implementing ngx-bootstrap/datepicker?,"<p>I created independent component with <code>ngx-bootstrap/datepicker</code> on <code>angular-cli</code> project.
Everything works fine but Unit test is failing.
But I am new on Unit Testing, and I tried to test but it saying fails.</p>

<p>Here is Travic-CI build log.</p>

<p><a href=""https://travis-ci.org/webcat12345/webcat-black-page/builds/221961698"" rel=""nofollow noreferrer"">https://travis-ci.org/webcat12345/webcat-black-page/builds/221961698</a></p>

<p>Here is my project version and code.</p>

<pre><code>@angular/cli: 1.0.0
node: 7.6.0
os: linux x64
@angular/cli: 1.0.0
@angular/common: 4.0.2
@angular/compiler: 4.0.2
@angular/compiler-cli: 4.0.2
@angular/core: 4.0.2
@angular/forms: 4.0.2
@angular/http: 4.0.2
@angular/platform-browser: 4.0.2
@angular/platform-browser-dynamic: 4.0.2
@angular/router: 4.0.2
</code></pre>

<p><strong>Template</strong></p>

<pre><code>&lt;datepicker class=""well well-sm main-calendar"" [(ngModel)]=""dt"" [minDate]=""minDate"" [showWeeks]=""false"" [dateDisabled]=""dateDisabled""&gt;&lt;/datepicker&gt;
</code></pre>

<p><strong>Component</strong> (sorry for posting full code. it is just sample code from ngx-bootstrap demo)</p>

<pre><code>import { Component, OnInit } from '@angular/core';
import * as moment from 'moment';

@Component({
  selector: 'app-sidebar-datepicker',
  templateUrl: './sidebar-datepicker.component.html',
  styleUrls: ['./sidebar-datepicker.component.scss']
})
export class SidebarDatepickerComponent implements OnInit {

  public dt: Date = new Date();
  public minDate: Date = void 0;
  public events: any[];
  public tomorrow: Date;
  public afterTomorrow: Date;
  public dateDisabled: {date: Date, mode: string}[];
  public formats: string[] = ['DD-MM-YYYY', 'YYYY/MM/DD', 'DD.MM.YYYY',
    'shortDate'];
  public format: string = this.formats[0];
  public dateOptions: any = {
    formatYear: 'YY',
    startingDay: 1
  };
  private opened: boolean = false;

  constructor() {
    (this.tomorrow = new Date()).setDate(this.tomorrow.getDate() + 1);
    (this.afterTomorrow = new Date()).setDate(this.tomorrow.getDate() + 2);
    (this.minDate = new Date()).setDate(this.minDate.getDate() - 1000);
    (this.dateDisabled = []);
    this.events = [
      {date: this.tomorrow, status: 'full'},
      {date: this.afterTomorrow, status: 'partially'}
    ];
  }

  ngOnInit() {

  }

  public getDate(): number {
    return this.dt &amp;&amp; this.dt.getTime() || new Date().getTime();
  }

  public today(): void {
    this.dt = new Date();
  }

  public d20090824(): void {
    this.dt = moment('2009-08-24', 'YYYY-MM-DD')
      .toDate();
  }

  public disableTomorrow(): void {
    this.dateDisabled = [{date: this.tomorrow, mode: 'day'}];
  }

  // todo: implement custom class cases
  public getDayClass(date: any, mode: string): string {
    if (mode === 'day') {
      let dayToCheck = new Date(date).setHours(0, 0, 0, 0);

      for (let event of this.events) {
        let currentDay = new Date(event.date).setHours(0, 0, 0, 0);

        if (dayToCheck === currentDay) {
          return event.status;
        }
      }
    }

    return '';
  }

  public disabled(date: Date, mode: string): boolean {
    return ( mode === 'day' &amp;&amp; ( date.getDay() === 0 || date.getDay() === 6 ) );
  }

  public open(): void {
    this.opened = !this.opened;
  }

  public clear(): void {
    this.dt = void 0;
    this.dateDisabled = undefined;
  }

  public toggleMin(): void {
    this.dt = new Date(this.minDate.valueOf());
  }
}
</code></pre>

<p><strong>Test Code</strong></p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { DatepickerModule } from 'ngx-bootstrap/datepicker';
import { SidebarDatepickerComponent } from './sidebar-datepicker.component';

describe('SidebarDatepickerComponent', () =&gt; {
  let component: SidebarDatepickerComponent;
  let fixture: ComponentFixture&lt;SidebarDatepickerComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ SidebarDatepickerComponent ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      imports: [DatepickerModule.forRoot()]
    })
    .compileComponents();
  }));

  beforeEach(async() =&gt; {
    fixture = TestBed.createComponent(SidebarDatepickerComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p>Please help me to figure out this issue.</p>

<p>Thank you!</p>
",https://stackoverflow.com/questions/43405036/how-to-pass-unit-test-after-implementing-ngx-bootstrap-datepicker,"['unit-testing', 'angular', 'datepicker', 'angular-cli', 'ngx-bootstrap']",3512,TRUE,3,1
How should I approach or shouldn&#39;t unit test?,"<p>I have a huge codebase written by someone else its not unit tested at all. I want to add unit testing to a spring application.but the code is very much of decoupled and some times the code is not testable. how should I approach this should I start with the low level objects or the high level once and can you give me a step by step example of how to write unit tests for a spring application.</p>
",https://stackoverflow.com/questions/46209879/how-should-i-approach-or-shouldnt-unit-test,"['java', 'spring', 'unit-testing']",70,TRUE,0,2
Run a SQL script in spring-test root startup,"<p>I have a spring project, and I am doing unit testing of my project with spring-test in a PostgreSQL database for the test (I have a database for test and another for development). And I want to initialize my database with a SQL script in the startup (root) of all tests. </p>

<p>I need some direction, I found ""flyway"" but first I am looking for something with basic spring or something like that or any idea. Thanks</p>
",https://stackoverflow.com/questions/45568566/run-a-sql-script-in-spring-test-root-startup,"['java', 'spring', 'junit', 'spring-test']",868,FALSE,0,2
Angular 2 http stub,"<p>Angular Experts,</p>

<p>I'm unit testing my application and I'm experimenting a little. </p>

<p>Specifically I'd like to unit test the Components with the real Services by just mocking the Http object. Right now I'm trying to stub the object by myself so I made the <strong>StubHttp</strong> class below.</p>

<p>Angular 2: verson 2.4.7 + Karma, Jasmine.</p>

<p>this is its simplified version: </p>

<pre><code>let mockTest = '{""name"":'John', // ...};

export class StubHttp {
  public post(url: string, body: any, options?: RequestOptionsArgs) 
            :Observable&lt;Response&gt; {
    let response = new ResponseOptions({body: JSON.stringify(mockTest)});
    return Observable.of(new Response(response));
  }
}
</code></pre>

<p>If I put a log in my controller: </p>

<pre><code>this.UsersService.getAll().subscribe(( data: any ) =&gt; {
   console.log('data = ', data);
});
</code></pre>

<p>and the service:</p>

<pre><code>getAll( event: LazyLoadEvent) {
    return this.http.post( this.url + this.params, JSON.stringify( this.body ),new RequestOptions({headers: this.header}) )
        .map( response =&gt; response.json() )
        .catch( this.handleError );
}
</code></pre>

<p>this is the output: </p>

<pre><code>LOG: 'data = ', Promise{}
</code></pre>

<p>where is the mistake? </p>
",https://stackoverflow.com/questions/45553175/angular-2-http-stub,"['angular', 'unit-testing', 'karma-jasmine', 'angular2-services']",453,TRUE,0,1
Meteor mocha watch mode displays lines of code instead of assertion messages,"<p>I am using <code>practicalmeteor:mocha</code> in watch mode and have written some UI tests (unit testing Template-components). </p>

<p>I have the weird issue, that my failed tests do not reveal the assertion message but a code snippet instead.</p>

<p>I have attached an image with an example output:</p>

<p><a href=""https://i.stack.imgur.com/pPJfC.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/pPJfC.png"" alt=""enter image description here""></a></p>

<p>Unfortunately I did not find any information about a configuration related to this in the documentation of the package or mocha itself.</p>

<p>My test command is the following:</p>

<pre><code>meteor test --driver-package practical meteor:mocha
</code></pre>

<p>The test code is the following:</p>

<pre class=""lang-js prettyprint-override""><code>// PACKAGES
import {Meteor} from 'meteor/meteor';
import {Template} from 'meteor/templating';
import {$} from 'meteor/jquery';
import {Random} from 'meteor/random';
import {chai, assert} from 'meteor/practicalmeteor:chai';
import StubCollections from 'meteor/hwillson:stub-collections';
import {sinon} from 'meteor/practicalmeteor:sinon';

// HELPERS
import {withRenderedTemplate, renderTemplate, withDiv} from '../../test-helpers.js';

// COMPONENTS
import '../../../startup/both/schemaDefaults';
import {loadingClassName} from '../../components/loading/loading';
import {Comments} from '../../../api/comments/Comments';
import '../comments.js';


describe(""UI/Comments"", function () {

    beforeEach(function () {
        StubCollections.stub(Comments);
        Template.registerHelper('_', key =&gt; key);
    });

    afterEach(function () {
        Template.deregisterHelper('_');
        StubCollections.restore();
        Meteor.subscribe.restore();
    });

    ////////////////////////////////////////////////////////    

    it(""renders a loading symbol on load"", function (done) {

        sinon.stub(Meteor, 'subscribe', () =&gt; ({
            subscriptionId: Random.id(),
            ready: () =&gt; false,
        }));

        withRenderedTemplate(Template.comments, {}, el =&gt; {
            const target = $(el);
            chai.assert.equal(target.find('.' + loadingClassName).length, 1);
            done();
        });

    });

    ////////////////////////////////////////////////////////

    it(""displays a message if no comments exist for the given document"", function (done) {

        sinon.stub(Meteor, 'subscribe', () =&gt; ({
            subscriptionId: Random.id(),
            ready: () =&gt; true,
        }));

        withRenderedTemplate(Template.comments, {docId: Random.id()}, el =&gt; {
            const target = $(el);
            chai.assert.equal(target.find('.' + loadingClassName).length, 0);
            chai.assert.equal(target.find('.no-comments').length, 1);
            done();
        });

    });

    ////////////////////////////////////////////////////////

    it(""displays comments, if comments are found"", function (done) {

        sinon.stub(Meteor, 'subscribe', () =&gt; ({
            subscriptionId: Random.id(),
            ready: () =&gt; true,
        }));

        const userId = Random.id();
        const commentDoc = {
            title: Meteor.user().username,
            status: 0,
            docId: Random.id(),
            description: ""this is a comment"",
            createdAt: new Date().getTime(),
            updatedAt: new Date().getTime(),
            createdBy: userId,
            updatedBy: userId,
        };

        Comments.insert(commentDoc);

        withRenderedTemplate(Template.comments, {docId: Random.id()}, el =&gt; {
            const target = $(el);
            assert.equal(target.find('.' + loadingClassName).length, 0);
            assert.equal(target.find('.no-comments').length, 0);
            assert.isAbove(target.find('.comment-entry').length, 0);
            done();
        });
    });

    ////////////////////////////////////////////////////////

    it(""displays a comment of self different than comments of others"", function (done) {
        assert.fail(""not yet implemented"");
    })
});
</code></pre>
",https://stackoverflow.com/questions/46785828/meteor-mocha-watch-mode-displays-lines-of-code-instead-of-assertion-messages,"['unit-testing', 'meteor', 'mocha.js']",63,TRUE,0,1
How to create a regular expression to exclude more files and folders in vue-cli default project?,"<p>I have a project created with vue-cli which uses mocha for unit testing (default setting). I want to write a unit test, but I fail with following setting:</p>

<p>My project folder:</p>

<p><a href=""https://i.stack.imgur.com/r0WD9.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/r0WD9.png"" alt=""enter image description here""></a></p>

<p>I fail with the following error messages:</p>

<pre><code>WARNING in ./src/assets/css/variables.styl
Module build failed: ParseError: /Users/kevin.hu/Documents/vreditor/src/assets/css/variables.styl:4:154
   1| // style-loader: Adds some css to the DOM by adding a &lt;style&gt; tag
   2|
   3| // load the styles
   4| var content = require(""!!../../../node_modules/css-loader/index.js??ref--12-1!../../../node_modules/stylus-loader/index.js??ref--12-2!./variables.styl"");
---------------------------------------------------------------------------------------------------------------------------------------------------------------^
   5| if(typeof content === 'string') content = [[module.id, content, '']];
   6| if(content.locals) module.exports = content.locals;
   7| // add the styles to the DOM
</code></pre>

<p>So I want to run the test skipping the assets folder or other ones. The default setting just excludes main.js. How to write a regular expression to acheive what I want?</p>

<p>Note: this is the default setting:</p>

<pre><code>const srcContext = require.context('../../src', true, /^\.\/(?!main(\.js)?$)/)
srcContext.keys().forEach(srcContext)
</code></pre>
",https://stackoverflow.com/questions/44585852/how-to-create-a-regular-expression-to-exclude-more-files-and-folders-in-vue-cli,"['regex', 'unit-testing', 'vue.js', 'mocha.js']",752,TRUE,0,1
AssertThat error: Cannot access path (java.nio.file.Path not found),"<p>I want to use Robolectric for Unit Testing but I am trying a simple test with robolectric and I am stuck at the beginning. I followed the manual, I did the same with the examples and even other posts couldn't help me. Every time I get the error message: cannot access path. class file for java.nio.file.Path not found.</p>

<p>My build.gradle is:</p>

<pre><code>testCompile ""org.robolectric:robolectric:3.3.2""
testCompile ""org.robolectric:shadows-support-v4:3.3.2""
testCompile 'junit:junit:4.12'
</code></pre>

<p>My Test class is:</p>

<pre><code>package com.dev.mann.chronoly;
import android.support.v7.widget.RecyclerView;
import org.junit.runner.RunWith;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowToast;
import org.robolectric.shadows.support.v4.SupportFragmentTestUtil;
import static 
org.robolectric.shadows.support.v4.SupportFragmentTestUtil.startFragment;

@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class CrngyMasterFragmentTestClass{
private CrngyMasterFragment mFrag;
RecyclerView mMainRecyclerView;
MainActivity activity;

@Before
public void setup() {
   activity = Robolectric.buildActivity(MainActivity.class).create().start().visible().get();
   //SupportFragmentTestUtil.startVisibleFragment(mFrag, MainActivity.class, R.id.master_frag_container);
}


@Test
public void checkEmptyFragments() throws Exception {
    //SupportFragmentTestUtil.startVisibleFragment(mFrag, AppCompatActivity.class, R.id.master_frag_container);
    assertThat(true);
    // check the recyclerview items
    //RecyclerView recyclerView = (RecyclerView) mFrag.getActivity().findViewById(R.id.mainRecyclerView);
    //assertThat(recyclerView.isShown());
}
</code></pre>

<p>}</p>

<p>But every settings doesn't work. 
Any help is much appreciated, thanks for any help.</p>
",https://stackoverflow.com/questions/45100659/assertthat-error-cannot-access-path-java-nio-file-path-not-found,"['java', 'android', 'junit', 'robolectric', 'assertj']",888,TRUE,0,1
Spring Junit4 Testing error : no DataSource specified,"<p>Hello I am a college student living in Korea.
I've been studying the process and I'm getting an error during the unit testing (Junit) of the project I'm working on</p>

<p>I tried Googleing for 3 days, but it did not work out. so, I need help.</p>

<p>This works well for UserDaoTest. However, one method of BoardDaoTest is not tested. I attach my source code here.</p>

<ol>
<li><p>JdbcTemplate.java</p>

<pre><code> public class JdbcTemplate extends JdbcDaoSupport {
      private static final Logger logger =  LoggerFactory.getLogger(JdbcTemplate.class);

      public static Connection conn;
      public PreparedStatement pstmt;
      public PreparedStatement pstmt2;
      public ResultSet rs;

      @PostConstruct
      public void initialize() {
        DataSource ds = getDataSource();
        logger.info(""get Data Source success!"");
        conn = DataSourceUtils.getConnection(ds);
        logger.info(""Conn = "" + conn);
        logger.info(""database initialized success!"");
      } { ... }
</code></pre></li>
<li><p>applicationContext.xml</p>

<pre><code>&lt;context:annotation-config /&gt;

&lt;context:property-placeholder location=""classpath*:application-properties.xml"" /&gt;

&lt;bean id=""applicationContextProvider"" class=""viser.service.ApplicationContextProvider"" /&gt;

&lt;bean id=""dataSource"" class=""org.apache.commons.dbcp.BasicDataSource""
    p:driverClassName=""${database.driverClassName}"" 
    p:url=""${database.url}""
    p:username=""${database.username}"" 
    p:password=""${database.password}"" 
/&gt;

&lt;bean id=""jdbcTemplate"" class=""viser.service.support.jdbc.JdbcTemplate""
    p:dataSource-ref=""dataSource""
/&gt;

&lt;bean id=""userDAO"" class=""viser.dao.user.UserDAO""&gt;
    &lt;property name=""dataSource"" ref=""dataSource"" /&gt;
&lt;/bean&gt;

&lt;bean id=""boardDAO"" class=""viser.dao.board.BoardDAO""&gt;
    &lt;property name=""dataSource"" ref=""dataSource"" /&gt;
&lt;/bean&gt;
</code></pre>

<p></p></li>
<li><p>UserDAOTest.java ( Successful testing )</p>

<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(""classpath:/applicationContext.xml"")
public class UserDAOTest {

  @Autowired
  private UserDAO userDAO;
  private User user;

  @Before
  public void setUp() {
    user = UserTest.TEST_USER;
  }

  @After
  public void returns() throws SQLException {
    userDAO.removeUser(user.getUserId());
  }

  @Test
  public void crud() throws Exception {
   { ... }
  }

  @Test
  public void getWhenNotExsitUser() throws Exception {
   { ... }
  }
</code></pre></li>
<li><p>BoardDAOTest.java (crud() -> success, getList() -> fail)</p>

<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(""classpath:/applicationContext.xml"")
public class BoardDAOTest {
private static final Logger logger = LoggerFactory.getLogger(BoardDAOTest.class);

 public static Board TEST_BOARD = new Board(""TEST_BOARD"", 
`ProjectDAOTest.TEST_PROJECT.getProjectName());`
          @Autowired
          private BoardDAO boardDAO;
          private ProjectDAO projectDAO;

          @Before
          public void setup() throws SQLException {
            boardDAO = new BoardDAO();
            projectDAO = new ProjectDAO();
            projectDAO.addProject(ProjectDAOTest.TEST_PROJECT);
          }

          @After
          public void returns() throws SQLException {
            projectDAO.removeProject(ProjectDAOTest.TEST_PROJECT.getProjectName());
          }

          @Test
          public void crud() throws SQLException {
            {...}
          }

          @Test
          public void getList() throws SQLException {
            logger.debug(""list : {}"", boardDAO.getBoardList(ProjectDAOTest.TEST_PROJECT.getProjectName()));  assertNotNull(boardDAO.getBoardList(ProjectDAOTest.TEST_PROJECT.getProjectName()));
      }
</code></pre></li>
</ol>

<p><a href=""https://i.stack.imgur.com/X7aGg.png"" rel=""nofollow noreferrer""> (errorImageFile) </a></p>
",https://stackoverflow.com/questions/45660056/spring-junit4-testing-error-no-datasource-specified,"['java', 'spring', 'model-view-controller', 'junit4']",910,FALSE,0,2
"Using JUnit, how do I mock this public constructor that calls some protected method?","<p>In my code, I have lineItems.getList() calling a protected method within that class.  </p>

<pre><code>public class Itemized {
    List&lt;String&gt; itemList = new ArrayList&lt;String&gt;();
    public void execute {
        try {
            //Establish some logic here
            Items lineItems= new Items (order1, order2);
            itemList = lineItems.getList();
        }
        catch (Exception e) {
          .....
        }
        finally {
            (if itemList !=null &amp;&amp; !itemList.isEmpty()) {
                //do something here
        }
</code></pre>

<p>And here is my test case</p>

<pre><code>@Mock
private Items items = Mockito.mock(Items.class);  
@Injectmocks
Itemized itemized;  

@Test
public void testItemized() throws Exception {
    List&lt;String&gt; mockItemList = new ArrayList&lt;String&gt;();
    mockItemList.add(""ABC"");
    mockItemList.add(""DEF"");
    PowerMockito.whenNew(Items.class).withAnyArguments().thenReturn(items);
    PowerMockito.when(items.getList()).thenReturn(mockItemList);
    mockItemList = items.getList();
    itemized.execute();
}
</code></pre>

<p>When I tried to system.out.println the mockTestList from test case, it returns the list.  However, in my Itemized class, it's always return empty, hence, it never makes it to the finally block.</p>

<p><strong>UPDATE</strong> Here is the class that I'm trying to mock</p>

<pre><code>public class Items {
    private List&lt;String&gt; items = new ArrayList&lt;String&gt;();
    public List&lt;String&gt; getList() {
        return items;

    .....
    //other protected methods that call addItems
    ......

    private void addItems(String item) {
    items.add(item);
    }
]
</code></pre>

<p>I'm still fairly new with unit testing so perhaps I incorrectly mocked somewhere along the line.</p>
",https://stackoverflow.com/questions/46592462/using-junit-how-do-i-mock-this-public-constructor-that-calls-some-protected-met,"['unit-testing', 'junit', 'mockito', 'powermockito']",56,FALSE,0,1
OUnit: assert value is instance of type,"<p>Using the <a href=""http://ounit.forge.ocamlcore.org/api-ounit/OUnit2.html"" rel=""nofollow noreferrer"">OUnit</a> unit testing framework in OCaml, I would like to test that the result of evaluating a function is an instance of a specified type.</p>

<p>Defining such a test in Python's <a href=""http://doc.pytest.org/en/latest/"" rel=""nofollow noreferrer"">PyTest</a> would be done as follows:</p>

<pre><code>def test_foo():
    assert isinstance(foo(2), int)
</code></pre>

<p><strong>How can this logic be translated to OUnit? That is, how are assertions of type membership specified?</strong></p>

<p>I'm aware that, assuming the function under test is annotated with the proper type signature, this testing might be unnecessary.</p>
",https://stackoverflow.com/questions/41472699/ounit-assert-value-is-instance-of-type,"['unit-testing', 'ocaml', 'ounit']",538,TRUE,0,1
How to run scala test case using Maven,"<p>I have written my project in java and scala.
I have written one scala test case for unit testing scala code.
However, I am not sure about the path it has to be stored to because maven says,</p>

<blockquote>
  <p>T E S T S</p>
  
  <p>------------------------------------------------------- There are no tests to run.</p>
  
  <p>Results :</p>
  
  <p>Tests run: 0, Failures: 0, Errors: 0, Skipped: 0</p>
</blockquote>

<p>Can anybody help me with how can I have maven pick my scala test file stored under src/test/scala?</p>

<p><a href=""https://i.stack.imgur.com/eOHzD.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/eOHzD.png"" alt=""code structure""></a>
<a href=""https://i.stack.imgur.com/MeqOT.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/MeqOT.png"" alt=""pom-part1[![][1][1]""></a><a href=""https://i.stack.imgur.com/3cwDG.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/3cwDG.png"" alt=""pom-part2[![][3]""></a>]<a href=""https://i.stack.imgur.com/jw1vN.png"" rel=""nofollow noreferrer"">4</a></p>
",https://stackoverflow.com/questions/43540488/how-to-run-scala-test-case-using-maven,"['maven', 'scalatest']",2481,FALSE,2,1
Ionic 2 : Test with jasmine and karma error &#39;ng test&#39;,"<p>I try to follow this tutorial : </p>

<p><a href=""http://lathonez.com/2017/ionic-2-unit-testing/"" rel=""nofollow noreferrer"">http://lathonez.com/2017/ionic-2-unit-testing/</a></p>

<p>And when I run ""ng test"" I have this error : </p>

<pre><code>C:\xampp\htdocs\AppFineMobile&gt;ng test
27 03 2017 11:55:00.556:ERROR [preprocess]: Can not load ""angular-cli"", it is not registered!
  Perhaps you are missing some plugin?
No provider for ""framework:angular-cli""! (Resolving: framework:angular-cli)
Error: No provider for ""framework:angular-cli""! (Resolving: framework:angular-cli)
    at error (C:\xampp\htdocs\AppFineMobile\node_modules\di\lib\injector.js:22:12)
    at Object.get (C:\xampp\htdocs\AppFineMobile\node_modules\di\lib\injector.js:9:13)
    at Injector.get (C:\xampp\htdocs\AppFineMobile\node_modules\di\lib\injector.js:54:19)
    at C:\xampp\htdocs\AppFineMobile\node_modules\karma\lib\server.js:143:20
    at Array.forEach (native)
    at Server._start (C:\xampp\htdocs\AppFineMobile\node_modules\karma\lib\server.js:142:21)
    at Injector.invoke (C:\xampp\htdocs\AppFineMobile\node_modules\di\lib\injector.js:75:15)
    at Server.start (C:\xampp\htdocs\AppFineMobile\node_modules\karma\lib\server.js:103:18)
    at Promise (C:\xampp\htdocs\AppFineMobile\node_modules\@angular\cli\tasks\test.js:35:25)
    at Class.run (C:\xampp\htdocs\AppFineMobile\node_modules\@angular\cli\tasks\test.js:15:16)
    at Class.run (C:\xampp\htdocs\AppFineMobile\node_modules\@angular\cli\commands\test.js:99:25)
    at Class.&lt;anonymous&gt; (C:\xampp\htdocs\AppFineMobile\node_modules\@angular\cli\ember-cli\lib\models\command.js:134:17)
    at process._tickCallback (internal/process/next_tick.js:103:7)
</code></pre>

<p>I don't understand what I have to do. I had run this command at first : </p>

<pre><code>npm install --save-dev @angular/cli @types/jasmine @types/node jasmine-core jasmine-spec-reporter karma karma-chrome-launcher karma-cli karma-jasmine karma-jasmine-html-reporter karma-coverage-istanbul-reporter
</code></pre>

<p>It work well, and I add all file mentioned in the tutorial ...</p>

<p>In my test.ts file I have an error in my import :</p>

<pre><code>import { getTestBed, TestBed } from '@angular/core/testing';
</code></pre>

<p>I have : Cannot find module '@angular/core/testing', but it exist in my module folder...</p>

<p>Someone have an idea ?</p>
",https://stackoverflow.com/questions/43043428/ionic-2-test-with-jasmine-and-karma-error-ng-test,"['node.js', 'angular', 'testing', 'ionic2', 'karma-jasmine']",2132,TRUE,2,2
How to test a service/component which depends on another service which in turn depends on Http service?,"<p>I have question about unit testing a component with service as a dependency and this server depends on <code>Http</code>.
I am reading this docs: <a href=""https://angular.io/docs/ts/latest/guide/testing.html#!#component-with-async-service"" rel=""nofollow noreferrer"">Test a component with an async service</a></p>

<p>I have really same code like in this example:</p>

<pre><code>  ngOnInit(): void {
    this.twainService.getQuote().then(quote =&gt; this.quote = quote);
  }
</code></pre>

<p>By the way here is my code: <a href=""https://github.com/sharikovvladislav/ng2-goods-list/blob/33399d254ef0d3ccda689c78de78bde54947a922/src/app/goods/goods.component.ts#L16"" rel=""nofollow noreferrer"">code</a></p>

<p>The docs says that when I test component which depends on another service, I have to:</p>

<ol>
<li>set this service as module provider</li>
<li><p>get service injected into the component: <code>twainService = fixture.debugElement.injector.get(TwainService);</code></p></li>
<li><p>setup spy on it: <code>spy = spyOn(twainService, 'getQuote').and.returnValue(Promise.resolve(testQuote));</code></p></li>
</ol>

<p>I do same: 
Here is my spec file: <a href=""https://github.com/sharikovvladislav/ng2-goods-list/blob/b5894e657492559f90e1894ed4daeee71bab33a7/src/app/goods/goods.component.spec.ts"" rel=""nofollow noreferrer"">spec file</a>. 
I provide service in line 21, I get injected service in 29 and I setup spy in 32.</p>

<p>So the question: If I do everything like docs says I am getting error: <code>Error: No provider for Http!</code>. Obviously this error appears because my <code>GoodsDataService</code> depends on <code>Http</code> service. How should I handle it? I did this: I created simple javascript object and I mocked my real <code>GoodsDataService</code> with it. I also added <code>getGoods</code> method stub in this object. All this things allow me to test main component without injecting real <code>GoodsDataService</code>. But I am not sure at all about this solution. I think it is dirty and not correct. What is correct way of unit testing component/service which depends on another service which in turn depends on <code>Http</code> service? Any thoughts?</p>
",https://stackoverflow.com/questions/44272683/how-to-test-a-service-component-which-depends-on-another-service-which-in-turn-d,"['angular', 'unit-testing', 'http']",1329,TRUE,3,2
Subclass XCTestCase results in cannot load underlying module XCTest,"<p>I'm writing a library for testing purposes. So I need XCTest within my main target and not within my Unit-Testing target. Currently working with Xcode 9.</p>

<p>When I import XCTest I get the error ""Cannot load underlying module for 'XCTest'"".</p>

<p>I know the main target is not linking against the framework, but adding it into linked frameworks (required) doesn't change anything.</p>

<p>I've also looked into Quicks Project settings but wasn't able to find anything out of the ordinary.</p>

<p>What am I missing?</p>
",https://stackoverflow.com/questions/47015355/subclass-xctestcase-results-in-cannot-load-underlying-module-xctest,"['ios', 'swift', 'xcode', 'xctest']",1588,TRUE,2,3
Remove Unit Tests in XCode 8,"<p>XCode auto-generates unit tests for projects, and these OFTEN fail due to bugs in XCode/OSX etc (plus, we have external unit testing an all of our ""important"" source code)</p>

<p>I want to completely remove these auto-generated unit tests from the project, but it seems that the strategies used for each previous version of xcode no longer exist with XCode8.</p>

<p>Does anyone know how to disable/remove the auto-generated ""Tests"" folder created by XCode in XCode 8?</p>
",https://stackoverflow.com/questions/42807509/remove-unit-tests-in-xcode-8,['xcode8'],393,TRUE,2,1
Is it possible to run a single test method from a python unittest.TestCase with a reference to the method?,"<p>Suppose I have the following <code>TestCase</code></p>

<pre><code>class TestSomething(unittest.TestCase):
    def test_a(self):
        # Do some testing

    def test_b(self):
        # Do some other testing
</code></pre>

<p>Is it possible for me to run <code>TestSomething.test_a</code> if I have a reference to that test? What I am looking to do is something like:</p>

<pre><code>def run_test(test):
    # Somehow runs the test
    # HERE IS THE PART I AM REALLY STUCK ON

run_test(TestSomething.test_a)
</code></pre>

<p>I know that it's an awkward thing to do for normal unit testing. What I am trying to do is provide a test to be run as an argument to a function decorator. Essentially:</p>

<pre><code>@corresponding_test(TestSomething.test_a)
def my_function_a():
    # Something here
</code></pre>

<p>And then in the decorator basically check if the test for that function passes before running the function.</p>
",https://stackoverflow.com/questions/46531212/is-it-possible-to-run-a-single-test-method-from-a-python-unittest-testcase-with,"['python', 'unit-testing', 'automated-tests', 'decorator', 'python-unittest']",628,TRUE,2,1
Laravel 5 Unit Test - Call to a member function connection() on null,"<p>I tried creating a unit test for the relationships between my <code>User</code> and <code>Shop</code> models, however when I run <code>vendor\\bin\\phpunit</code> this error(s) are thrown, I have no idea about this since I'm a newbie in unit testing. I tried to run my code on my controller to see if the relationship actually works, and fortunately it is working as expected, but not when run in phpunit. What have I done wrong for this phpunit not to work with Models?</p>
<blockquote>
<p><strong><code>Fatal error:</code></strong> <em><code>Uncaught Error: Call to a member function connection() on null in E:\projects\try\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php:1013</code></em></p>
<p><strong><code>Stack trace:</code></strong>
<em><code>E:\projects\try\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php(979): Illuminate\Database\Eloquent\Model::resolveConnection(NULL)</code></em></p>
</blockquote>
<p>This is my UserTest.php</p>
<pre><code>&lt;?php

namespace Tests\Unit;

use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

use App\User;
use App\Shop;

class UserTest extends TestCase
{

    protected $user, $shop;

    function __construct()
    {
        $this-&gt;setUp();
    }
    
    function setUp()
    {
        $user = new User([
            'id' =&gt; 1,
            'first_name' =&gt; 'John',
            'last_name' =&gt; 'Doe',
            'email' =&gt; 'JohnDoe@example.com',
            'password' =&gt; 'secret',
            'facebook_id' =&gt; null,
            'type' =&gt; 'customer',
            'confirmation_code' =&gt; null,
            'newsletter_subscription' =&gt; 0,
            'last_online' =&gt; null,
            'telephone' =&gt; null,
            'mobile' =&gt; null,
            'social_security_id' =&gt; null,
            'address_1' =&gt; null,
            'address_2' =&gt; null,
            'city' =&gt; null,
            'zip_code' =&gt; null,
            'signed_agreement' =&gt; 0,
            'is_email_confirmed' =&gt; 0
        ]);

        $user = User::find(1);
        $shop = new Shop([
            'id' =&gt; 1,
            'user_id' =&gt; $user-&gt;id,
            'name' =&gt; 'PureFoods Hotdog2',
            'description' =&gt; 'Something that describes this shop',
            'url' =&gt; null,
            'currency' =&gt; 'USD'
        ]);
        $user-&gt;shops()-&gt;save($shop);

        $shop = new Shop([
            'id' =&gt; 2,
            'user_id' =&gt; $user-&gt;id,
            'name' =&gt; 'PureFoods Hotdog',
            'description' =&gt; 'Something that describes this shop',
            'url' =&gt; null,
            'currency' =&gt; 'USD'
        ]);

        $user-&gt;shops()-&gt;save($shop);

        $this-&gt;user = $user;

    }

    /** @test */
    public function a_user_has_an_id(){
        $user =  User::find(1);
        $this-&gt;assertEquals(1, $user-&gt;id);
    }

    /** @test */
    public function a_user_has_a_first_name()
    {
        $this-&gt;assertEquals(&quot;John&quot;, $this-&gt;user-&gt;first_name);
    }

    /** @test */
    public function a_user_can_own_multiple_shops()
    {
        $shops = User::find(1)-&gt;shops()-&gt;get();
        var_dump($this-&gt;shops);
        $this-&gt;assertCount(2, $shops);
    }
}
</code></pre>
<p>It seems, this error is caused by this line of code:
<code>$user-&gt;shops()-&gt;save($shop);</code> - this code actually works when run in my sample routes or Controller but is throwing <code>errors</code> when run in <code>phpunit</code></p>
<p><strong>User.php</strong></p>
<pre><code>&lt;?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    protected $guarded = [ 'id' ];
    protected $table = &quot;users&quot;;   

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];


    /**
     * returns the Shops that this user owned
     */
    public function shops()
    {
        return $this-&gt;hasMany('App\Shop');
    }
}
</code></pre>
<p><strong>Shop.php</strong></p>
<pre><code>&lt;?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Shop extends Model
{
    protected $guarded = [ 'id' ];
    protected $table = &quot;shops&quot;;

    /**
     * returns the Owner of this Shop
     */
    public function owner()
    {
        return $this-&gt;belongsTo('App\User');
    }
}
</code></pre>
<p>Any help will be very much appreciated. Thanks!</p>
",https://stackoverflow.com/questions/42512676/laravel-5-unit-test-call-to-a-member-function-connection-on-null,"['php', 'unit-testing', 'laravel-5', 'eloquent', 'phpunit']",27416,TRUE,29,8
Testing a method that delegates to another object,"<p>This is a model in my project - </p>

<pre><code>class Subscription &lt; ActiveRecord::Base
  def active?
    SubscriptionValidationPolicy.new(self).active?
  end
end
</code></pre>

<p>When I'm unit testing <code>active?</code>, should I setup a <code>subscription</code> for active and inactive states and assert on that or should I make a double for <code>SubscriptionValidationPolicy</code>, inject it in somehow and then assert whether <code>active?</code> was called on it?</p>

<p>Or is it all just opinionated how I go about testing this. I'm going to be testing <code>SubscriptionValidationPolicy</code> anyway, so it feels redundant to do a ""state based"" test for the <code>Subscription#active?</code> method. </p>

<p>Would love some thoughts on this :)</p>
",https://stackoverflow.com/questions/46646516/testing-a-method-that-delegates-to-another-object,"['ruby-on-rails', 'ruby', 'unit-testing', 'rspec']",1380,TRUE,2,1
Verifying File.Delete was called with Moq,"<p>I am new to unit testing. I am trying to test something very simple:</p>

<pre><code>[HttpPost]
public ActionResult EditProfile(ProfileViewModel model)
{
    if (ModelState.IsValid)
    {
        // Retrieve current user
        var userId = User.Identity.GetUserId();
        var user = _dataRepository.GetUserById(userId);

        //If it isn't the single-instance default picture, delete the current profile
        // picture from the Profile_Pictures folder
        if (!String.Equals(user.ProfilePictureUrl, _defaultPic))
            System.IO.File.Delete(Server.MapPath(user.ProfilePictureUrl));
</code></pre>

<p>In this section of code, I am creating a condition where this line will evaluate as true:</p>

<pre><code>if (!String.Equals(user.ProfilePictureUrl, _defaultPic))
</code></pre>

<p>I would like to verify that <code>System.IO.File.Delete</code> is called. </p>

<p>What is the best way to do this? </p>

<p>Do I need to refactor by wrapping the <code>System.IO.File.Delete</code> call in my own class that implements an interface so that I can mock it and verify that it was called? </p>

<p>I am using Moq.</p>
",https://stackoverflow.com/questions/46227992/verifying-file-delete-was-called-with-moq,"['c#', 'asp.net-mvc', 'unit-testing', 'moq']",741,TRUE,2,1
Is it better to write methods that return a value or operate on the data directly?,"<p>When writing a class in typescript (or even javascript) is it better to write methods that return a value or to operate on the data directly?  In the end, I need the value of the original variable changed.</p>

<pre><code>let x: number = 4;

addFive(myInput: number): number {
  return myInput + 5;
}

addSix(): void {
  this.x += 6;
}

console.log(x);  // 4

x = addFive(x);
console.log(x);  // 9

addSix(x);
console.log(x);  // 15
</code></pre>

<p>This is a very simple example and the actual methods that I'm writing are specific to the original data and cannot be reused generally.</p>

<p>For unit testing purposes, I see the advantage of returning value, but sometimes it just seems like overkill.</p>
",https://stackoverflow.com/questions/45825820/is-it-better-to-write-methods-that-return-a-value-or-operate-on-the-data-directl,"['angular', 'typescript']",50,FALSE,2,0
Is it possible to stub out or spy on the setState method in React when doing unit tests?,"<p>I have the following function in my component:</p>

<pre><code>method(args) {
 fetch(args)
  .then((response) =&gt; {
    this.setState({
      element: response
      error: false
    });
  })
  .catch((error) =&gt; {
    this.setState({
      error: true
    });
  });
}
</code></pre>

<p>I am trying to write a unit test for it so I have mocked out the fetch call using fetch-mock with a custom response. I want to check if the state was updated when this method is called and it doesn't seem to be working.  I am using enzyme, expect, and sinon and have been unsuccessful in getting the spy to be called when I set component.setState = sinon.spy or stubbing it out. How can I check to see if setState was called with certain elements or is my approach to unit testing this wrong?</p>
",https://stackoverflow.com/questions/43701425/is-it-possible-to-stub-out-or-spy-on-the-setstate-method-in-react-when-doing-uni,"['unit-testing', 'reactjs', 'sinon', 'enzyme']",12288,TRUE,13,4
How to mock exec.Command for multiple unit tests in Go lang?,"<p>I just learnt unit testing functions that uses <code>exec.Command()</code> i.e., mocking <code>exec.Command()</code>. I went ahead to added more unit cases, but running into issues of not able to mock the output for different scenarios.</p>

<p><strong>Here is a sample code <code>hello.go</code> I'm trying to test...</strong></p>

<pre><code>package main

import (
    ""fmt""
    ""os/exec""
)

var execCommand = exec.Command

func printDate() ([]byte, error) {
    cmd := execCommand(""date"")
    out, err := cmd.CombinedOutput()
    return out, err
}

func main() {
    fmt.Printf(""hello, world\n"")
    fmt.Println(printDate())
}
</code></pre>

<p><strong>Below is the test code <code>hello_test.go</code>...</strong></p>

<pre><code>package main

import (
    ""fmt""
    ""os""
    ""os/exec""
    ""testing""
)

var mockedExitStatus = 1
var mockedDate = ""Sun Aug 20""
var expDate = ""Sun Aug 20""

func fakeExecCommand(command string, args ...string) *exec.Cmd {
    cs := []string{""-test.run=TestHelperProcess"", ""--"", command}
    cs = append(cs, args...)
    cmd := exec.Command(os.Args[0], cs...)
    cmd.Env = []string{""GO_WANT_HELPER_PROCESS=1""}
    return cmd
}

func TestHelperProcess(t *testing.T) {
    if os.Getenv(""GO_WANT_HELPER_PROCESS"") != ""1"" {
        return
    }

    // println(""Mocked Data:"", mockedDate)
    fmt.Fprintf(os.Stdout, mockedDate)
    os.Exit(mockedExitStatus)
}

func TestPrintDate(t *testing.T) {
    execCommand = fakeExecCommand
    defer func() { execCommand = exec.Command }()

    out, err := printDate()
    print(""Std out: "", string(out))
    if err != nil {
        t.Errorf(""Expected nil error, got %#v"", err)
    }
    if string(out) != expDate {
        t.Errorf(""Expected %q, got %q"", expDate, string(out))
    }
}

func TestPrintDateUnableToRunError(t *testing.T) {
    execCommand = fakeExecCommand
    defer func() { execCommand = exec.Command }()

    mockedExitStatus = 1
    mockedDate = ""Unable to run date command""
    expDate = ""Unable to run date command""

    out, err := printDate()
    print(""Std out: "", string(out))
    if err != nil {
        t.Errorf(""Expected nil error, got %#v"", err)
    }
    if string(out) != expDate {
        t.Errorf(""Expected %q, got %q"", expDate, string(out))
    }
}
</code></pre>

<p><strong><code>go test</code> fails for the second test <code>TestPrintDateUnableToRunError</code>...</strong></p>

<pre><code>$ go test hello
Std out: Sun Aug 20Std out: Sun Aug 20--- FAIL: TestPrintDateTomorrow (0.01s)
    hello_test.go:62: Expected ""Unable to run date command"", got ""Sun Aug 20""
FAIL
FAIL    hello   0.017s
</code></pre>

<p>Even though I'm trying to set the global <code>mockedDate</code> value inside the test case, it's still getting the global value that it was initialized with. <strong>Is the global value not getting set? Or the changes to that global var is not getting updated in <code>TestHelperProcess</code>?</strong></p>
",https://stackoverflow.com/questions/45789101/how-to-mock-exec-command-for-multiple-unit-tests-in-go-lang,"['unit-testing', 'go']",8211,TRUE,7,2
C# AssemblyInitialize not running,"<p>I'm trying to do unit testing on my C# ASP.NET project but need to run some initialization code for all tests:</p>

<pre><code>[TestClass()]
public class Init
{

    [AssemblyInitialize]
    public static void initialize()
    {
            ContextProvider.setContext(new TestContext());
    }
}
</code></pre>

<p>That's all I need to run before my tests, but it is not running. I tried to debug all my tests and put a breakpoint in that line but it is not hit. If I comment out the <code>[AssemblyInitialize]</code> and run one particular test that does not require this initialization, it runs successfully. However, with this line in, no tests run (and no breakpoints at all are hit)</p>

<p>What am I missing here?</p>
",https://stackoverflow.com/questions/41465239/c-assemblyinitialize-not-running,"['c#', 'asp.net']",5665,TRUE,7,4
How to create a Java 8 Clock for a specific date,"<p>Regarding date dependent unit tests I am figuring out the right way of creating a Java 8 Clock for a specific date. According to the approach proposed in <a href=""https://stackoverflow.com/q/27067049/1140754"">Unit testing a class with a Java 8 Clock</a>, I am trying it with the <a href=""https://docs.oracle.com/javase/8/docs/api/java/time/Clock.html#fixed-java.time.Instant-java.time.ZoneId-"" rel=""nofollow noreferrer""><code>Clock.fixed</code></a> method. However, I am not realizing a short way of doing it. </p>

<p>Is this the right and best way of creating a Java 8 Clock for a specific date?</p>

<h3>version 2 (according to suggestions of <a href=""https://stackoverflow.com/questions/43253334/how-to-create-a-java-8-clock-for-a-specific-date?noredirect=1#comment73577690_43253334"">@Meno</a>, <a href=""https://stackoverflow.com/questions/43253334/how-to-create-a-java-8-clock-for-a-specific-date?noredirect=1#comment73576057_43253334"">@LakiGeri</a> and <a href=""https://stackoverflow.com/questions/43253334/how-to-create-a-java-8-clock-for-a-specific-date?noredirect=1#comment73726059_43253334"">@basil-bourque</a>)</h3>

<pre><code>private static Clock utcClockOf(int year, int month, int day) {
    ZoneOffset offset = ZoneOffset.UTC;
    Instant inst = LocalDate
            .of(year, month, day)
            .atStartOfDay(offset)
            .toInstant();
    return Clock.fixed(inst, offset.normalized());
}
</code></pre>

<h3>version 1</h3>

<pre><code>static Clock clockOf(int year, int month, int day) {
    LocalDate now = LocalDate.of(year, month, day);
    long days = now.toEpochDay();
    long secs = days*24*60*60;
    Instant inst = Instant.ofEpochSecond(secs);
    return Clock.fixed(inst, ZoneId.systemDefault());
}
</code></pre>
",https://stackoverflow.com/questions/43253334/how-to-create-a-java-8-clock-for-a-specific-date,"['java-8', 'java-time']",4377,FALSE,4,0
H2 Insert via stored procedure,"<p>I'm trying to write an H2 stored procedure to insert some values into a table. I'm doing this because in my unit testing environment, I'd rather connect to an in-memory than a real database. Here's what I have (note that I'm doing this in groovy, not java, but I don't think that matters).</p>

<pre><code>Sql sql = new Sql(JdbcConnectionPool.create(""jdbc:h2:mem:test;DB_CLOSE_DELAY=-1"", ""user"", ""password""))
sql.executeUpdate(""CREATE TABLE data (key VARCHAR(255) PRIMARY KEY,value VARCHAR(1023) )"")
sql.execute(""CREATE ALIAS insertInto FOR \""com.vanguard.fig.batch.core.StoredProcs.insertInto\"""")
sql.execute(""CALL insertInto(?,?)"", val1, val2)
sql.eachRow(""Select * From data"") { row -&gt;
                println row             
            }
</code></pre>

<p>And my procedure is as follows</p>

<pre><code>public class StoredProcs {
    void insertInto(java.sql.Connection con, String val1, String val2) throws Exception {
        String resultValue=null;
        Sql sql = new Sql(con)
        sql.executeInsert(""Insert Into data VALUES(?, ?)"", val1, val2)
    }
}
</code></pre>

<p>The examples were all fairly confusing and I'm not sure I'm doing this right. Here's the error</p>

<pre><code>WARNING: Failed to execute: CALL insertInto(?,?) because: Parameter ""#1"" is not set; SQL statement:
</code></pre>

<p>Insert Into data VALUES(?, ?) [90012-193]</p>
",https://stackoverflow.com/questions/43743004/h2-insert-via-stored-procedure,"['java', 'h2']",567,FALSE,1,1
Xunit and Mock data with Moq,"<p>I'm new to unit testing, can anyone advise how to test public method (CreateUser) below using xUnit and Moq, thanks!</p>

<pre><code>public async Task&lt;bool&gt; CreateUser(UserDTO newUser)
{
  newUser.CustomerId = _userResolverService.GetCustomerId();
  if (await CheckUserExists(newUser)) return false;
  var salt = GenerateSalt(10);
  var passwordHash = GenerateHash(newUser.Password, salt);

  await _usersRepository.AddAsync(new User()
  {
    Role = newUser.Role,
    CretedOn = DateTime.Now,
    CustomerId = newUser.CustomerId,
    Email = newUser.Email,
    FirstName = newUser.FirstName,
    LastName = newUser.LastName,
    PasswordHash = passwordHash,
    Salt = salt,
    UpdatedOn = DateTime.Now
  });

  return true;
}
</code></pre>

<p>Private methods below
Check if user exists simply returns number of existing users </p>

<pre><code>private async Task&lt;bool&gt; CheckUserExists(UserDTO user)
    {
      var users = await _usersRepository.GetAllAsync();
      var userCount = users.Count(u =&gt; u.Email == user.Email);
      return userCount &gt; 0;
    }
</code></pre>

<p>Hash Generation</p>

<pre><code>private static string GenerateHash(string input, string salt)
{
  var bytes = System.Text.Encoding.UTF8.GetBytes(input + salt);
  var sha256 = SHA256.Create();
  var hash = sha256.ComputeHash(bytes);

  return ByteArrayToString(hash);
}
</code></pre>

<p>Salt Generaion</p>

<pre><code>private static string GenerateSalt(int size)
{
  var rng = RandomNumberGenerator.Create();
  var buff = new byte[size];
  rng.GetBytes(buff);
  return Convert.ToBase64String(buff);
}



private static string ByteArrayToString(byte[] ba)
{
  var hex = new StringBuilder(ba.Length * 2);
  foreach (byte b in ba)
    hex.AppendFormat(""{0:x2}"", b);
  return hex.ToString();
}
</code></pre>

<p>Thanks,
J</p>

<p><b>EDIT 1</b></p>

<p>This is what I have so far:</p>

<pre><code>    [Fact]
        public async void CreateUser_True()
        {
          //arrange
          var dataSource = new Mock&lt;IRepository&lt;User, int&gt;&gt;();
          var userResolverService = new Mock&lt;IUserResolverService&gt;();
          var tokenService = new Mock&lt;ITokenService&gt;();

      var users = new List&lt;User&gt;();
      users.Add(new User()
      {
        Email = ""test@test.com"",
        CustomerId = 1
      });
      dataSource.Setup(m =&gt; m.GetAllAsync()).ReturnsAsync(users); // Error Here with converting async task to IEnumerable...

          var accountService = new AccountService(dataSource.Object,userResolverService.Object,tokenService.Object);


          //act


          //assert


        }
</code></pre>

<p>Main problem is that I have no idea how to Mock, set up behavior of private Method ""CheckUserExists"", as it's calling IRepository which is mocked for class, so will this in this case return my mock setup for GetAllAsync from this private method?</p>

<p>EDIT 2</p>

<pre><code>public async Task&lt;TEntity&gt; AddAsync(TEntity entity)
{
  if (entity == null)
  {
    throw new ArgumentNullException(nameof(entity));
  }
  _entities.Add(entity);
  await _context.SaveChangesAsync();
  return entity;
}
</code></pre>

<p><b>EDIT 3</b></p>

<pre><code>[Fact]
public async void CreateUser_True()
{
  //arrange
  var users = new List&lt;User&gt;();
  users.Add(new User()
  {
    Email = ""test@test.com"",
    CustomerId = 1
  });
  _dataSource.Setup(m =&gt; m.GetAllAsync()).ReturnsAsync(users);
  _dataSource.Setup(m =&gt; m.AddAsync(It.IsAny&lt;User&gt;())).Returns&lt;User&gt;(Task.FromResult);
  var accountService = new AccountService(_dataSource.Object, _userResolverService.Object, _tokenService.Object);


  //act
  var result = await accountService.CreateUser(new UserDTO()
  {
    Email = ""truetest@test.com""
  });

  var updatedUsersList = await _dataSource.Object.GetAllAsync();
  var usersCount = updatedUsersList.Count();

  //assert
  Assert.True(result);
  Assert.Equal(2, usersCount);

}
</code></pre>
",https://stackoverflow.com/questions/45525519/xunit-and-mock-data-with-moq,"['c#', '.net', 'unit-testing', 'moq', 'xunit']",46578,TRUE,7,2
How to test a react component renders a list with jest,"<p>I'm trying to understand how unit testing works and have built a small React app that renders out a list of Pokemon.
What I am trying to do is write a unit test that checks to see if the list is rendering properly. However, the snapshot that is generated shows that it only renders the 'loading ...' text which is what it is supposed to do while waiting for a response from the API.
What am I doing wrong?</p>

<p><strong>PokemonList.test.js</strong></p>

<pre><code>import React from 'react';
import PokemonList from '../components/PokemonList';
import renderer from 'react-test-renderer';

describe('PokemonList component renders a list of Pokemon', () =&gt; {
    it('renders correctly', () =&gt; {
        const fetched = true;
        const loading = true;
        const species = [{
            ""0"": {""name"": ""bulbasaur""},
            ""1"": {""name"": ""ivysaur""},
            ""2"": {""name"": ""venusaur""}
        }];
        const rendered = renderer.create(
            &lt;PokemonList fetched={fetched} loading={loading} species={species} /&gt;
        );
        expect(rendered.toJSON()).toMatchSnapshot();
    });
});
</code></pre>

<p><strong>PokemonList.js</strong></p>

<pre><code>// The PokemonList component show nothing when it mounts for the first time.
// But right before it mounts to the DOM, it makes an API call to fetch the
// first 151 Pokemon for the API and then displays them using the Pokemon component.

import React from 'react';
import Pokemon from './Pokemon';

class PokemonList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            species: [],
            fetched: false,
            loading: false,
        };
    }

    componentWillMount() {
        this.setState({
            loading: true
        });
        fetch('http://pokeapi.co/api/v2/pokemon?limit=151').then(res=&gt;res.json())
        .then(response=&gt;{
            this.setState({
                species: response.results,
                loading: true,
                fetched: true
            });
        });
    }

    render() {
        const {fetched, loading, species} = this.state;
        let content ;
        if (fetched) {
            content = &lt;div className=""pokemon--species--list""&gt;{species.map((pokemon, index) =&gt; &lt;Pokemon key={pokemon.name} id={index+1} pokemon={pokemon} /&gt;)}&lt;/div&gt;
        } else if (loading &amp;&amp; !fetched) {
            content = &lt;p className=""loading""&gt; Loading ...&lt;/p&gt;
        } else {
            content = &lt;div/&gt;
        }
        return (
            &lt;div&gt;
                {content}
            &lt;/div&gt;
        )
    }
}

export default PokemonList;
</code></pre>

<p><strong>PokemonList.test.js.snap</strong></p>

<pre><code>exports[`PokemonList component renders a list of Pokemon renders correctly 1`] = `
&lt;div&gt;
  &lt;p
    className=""loading""&gt;
     Loading ...
  &lt;/p&gt;
&lt;/div&gt;
`;
</code></pre>
",https://stackoverflow.com/questions/44308754/how-to-test-a-react-component-renders-a-list-with-jest,"['javascript', 'unit-testing', 'reactjs', 'jestjs', 'snapshot']",4376,TRUE,1,1
Error when trying to test my React-native Component. `TypeError: _this._scrollView.scrollTo is not a function`,"<p>I'm trying to do some unit testing for my React-native application, but I'm facing a weird issue here. I don't know where the issue is coming from. I looked on React-native GitHub and StackOverFlow, but i didn't find any solution for it.</p>

<p>So when i try to run this code on my test file <code>App.test.js</code></p>

<pre><code>import React from 'react';
import App from '../../App';

import renderer from 'react-test-renderer';

it('renders without crashing', () =&gt; {
  const rendered = renderer.create(&lt;App /&gt;).toJSON();
  expect(rendered).toBeTruthy();
});
</code></pre>

<p>For my <code>Package.json</code></p>

<pre><code>{
  ""name"": ""Flashcards"",
  ""version"": ""0.1.0"",
  ""private"": true,
  ""devDependencies"": {
    ""jest-cli"": ""20.0.4"",
    ""jest-expo"": ""^21.0.2"",
    ""react-dom"": ""^16.0.0"",
    ""react-native-scripts"": ""1.5.0"",
    ""react-script"": ""^2.0.5"",
    ""react-test-renderer"": ""^16.0.0""
  },
  ""main"": ""./node_modules/react-native-scripts/build/bin/crna-entry.js"",
  ""scripts"": {
    ""start"": ""react-native-scripts start"",
    ""eject"": ""react-native-scripts eject"",
    ""android"": ""react-native-scripts android"",
    ""ios"": ""react-native-scripts ios"",
    ""test"": ""node node_modules/jest/bin/jest.js --watch""
  },
  ""jest"": {
    ""preset"": ""jest-expo""
  },
  ""dependencies"": {
    ""array-shuffle"": ""^1.0.1"",
    ""date-fns"": ""^1.29.0"",
    ""expo"": ""^21.0.0"",
    ""prop-types"": ""^15.6.0"",
    ""react"": ""16.0.0-alpha.12"",
    ""react-native"": ""^0.48.4"",
    ""react-native-keyboard-aware-scroll-view"": ""^0.4.1"",
    ""react-navigation"": ""^1.0.0-beta.15"",
    ""remote-redux-devtools"": ""^0.5.12""
  }
}
</code></pre>

<p>The error that i'm having every time i try running <code>yarn test</code> or <code>npm test</code></p>

<pre><code> FAIL  src/__test__/App.test.js
  ● renders without crashing

    TypeError: _this._scrollView.scrollTo is not a function

      at TabViewPagerScroll._this._scrollTo (node_modules/react-native-tab-view/src/TabViewPagerScroll.js:90:19)
      at TabViewPagerScroll.componentDidMount (node_modules/react-native-tab-view/src/TabViewPagerScroll.js:113:259)
      at commitLifeCycles (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:5461:24)
      at commitAllLifeCycles (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:6250:9)
      at Object.invokeGuardedCallback$1 (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:2159:10)
      at invokeGuardedCallback (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:2106:29)
      at commitAllWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:6371:9)
      at workLoop (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:6643:13)
      at Object.invokeGuardedCallback$1 (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:2159:10)
      at invokeGuardedCallback (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:2106:29)

  ✕ renders without crashing (62ms)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        0.143s, estimated 1s
Ran all test suites related to changed files.

  console.error node_modules/react-native/Libraries/Core/ExceptionsManager.js:73
    The above error occurred in the &lt;TabViewPagerScroll&gt; component:
        in TabViewPagerScroll (created by TabViewAnimated)
        in View (created by View)
        in View (created by TabViewAnimated)
        in TabViewAnimated (created by TabView)
        in TabView (created by withCachedChildNavigation(TabView))
        in withCachedChildNavigation(TabView)
        in Unknown (created by Navigator)
        in Navigator (created by NavigationContainer)
        in NavigationContainer (created by App)
        in View (created by View)
        in View (created by App)
        in Provider (created by App)
        in App

    Consider adding an error boundary to your tree to customize error handling behavior.
    You can learn more about error boundaries at
</code></pre>

<p>Here is my App.js. By the way the app work perfectly fine</p>

<pre><code>import React from 'react';
import {View} from 'react-native'
import AppNavigation from './src/navigation/AppNavigation'
import AppStatusBar from './src/navigation/AppStatusBar'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import reducer from './src/utils/reducers'
import { setLocalNotification } from './src/utils/helpers'

export default class App extends React.Component {
  componentDidMount() {
    setLocalNotification()
  }

  render () {
    return (
      &lt;Provider store={createStore(reducer)}&gt;
        &lt;View style={{flex: 1}}&gt;
          &lt;AppStatusBar /&gt;
          &lt;AppNavigation /&gt;
        &lt;/View&gt;
      &lt;/Provider&gt;
    )
  }
}
</code></pre>

<p>Thank you </p>
",https://stackoverflow.com/questions/46985134/error-when-trying-to-test-my-react-native-component-typeerror-this-scrollvi,"['javascript', 'node.js', 'react-native', 'jestjs']",1327,FALSE,1,0
Google Test C Function With Wait Loop,"<p>I'm crafting unit-tests for an embedded C application (<strong>NOTE</strong>: C, not C++).  This very low-end 8-bit application does not use threading or an RTOS.  Instead, I've gone old-school with a round-robin task dispatcher.</p>

<p>I'm using Google Test because that's what's readily available here.  It's been working for the vast majority of my cases, but I've come across one corner case.</p>

<p>I have this function here:</p>

<pre><code>bool UartPutsWithWait(char *str)
{
    while (sUartData.m_flags.m_TxBusy)
    {
        /* Wait for previous transmission to complete */
    }
    return UartPuts(str);
}   /* UartPutsWithWait */
</code></pre>

<p>The ""TxBusy"" flag is set within an interrupt routine on the target.
""UartPuts"" has undergone unit testing successfully.</p>

<p>My question is: <em>Does anybody have a useful way of setting up Google Test (or Google Mock) to set the ""TxBusy"" flag after one or two iterations?</em></p>

<p>My target is VERY memory-constrained (8KB of Flash for the high-end products), so re-implementing with threads and/or tasks is unlikely to be a useful answer.</p>

<p>If all else fails, I'll have to wear the risk of not unit-testing that particular line of code as thoroughly as I'd like.</p>

<p>I note also that my task dispatcher loop in my main() function is going to have to be tweaked to allow use of Google Mock.  That, I can live with.</p>

<p>Regards,</p>

<p>Geoff</p>
",https://stackoverflow.com/questions/47344749/google-test-c-function-with-wait-loop,"['c', 'unit-testing', 'googletest']",2569,FALSE,2,2
how to test python functions that use database connections using pytest?,"<p>I am new to unit-testing and using Pytest for testing my code. Writing tests for basic functions is easy using pytest, but I am not able to wrap my head around the concept of ""monkey-patching"" and ""mocking"" for testing functions that query database.</p>

<p>This is my code without the use of monkeypatching and mocking, I am actually querying the DB, which I don't want to do -</p>

<pre><code>def test_execute_sql():
    conn = data_platform.DataPlatformConnection()
    sql_out = conn.execute_sql(""SELECT sid, name, code FROM prod.school WHERE sid = 1158;"")
    # sql_out = [(1158, 'Lakeview Elementary School', '4141034')]
    assert sql_out[0] == (1158, 'Lakeview Elementary School', '4141034')

def test_execute_sql_return_single_value():
    conn = data_platform.DataPlatformConnection()
    sql_out = conn.execute_sql(""SELECT code FROM prod.school WHERE sid = 1158;"")
    # sql_out = [('4141034',)]
    assert sql_out[0][0] == '4141034'

    # testing exception
    with pytest.raises(Exception) as excinfo:
        conn.execute_sql("""")
    assert 'The sql clause parameter is blank' in str(excinfo.value)
</code></pre>

<p>can someone please explain to me the concept of mocking in pytest? so that I can start using it.</p>
",https://stackoverflow.com/questions/47600164/how-to-test-python-functions-that-use-database-connections-using-pytest,"['python-2.7', 'pytest']",5166,TRUE,4,1
Powermock and FileUtils package,"<p>Can we mock the static methods of FileUtils package using PowerMock ? I have a requirement where my business code call a copyFileToURL(url,file) of FileUtils package and for unit testing I have to mock it using Powermock which gives unfinished stubbing exception.</p>

<p>This link <a href=""https://stackoverflow.com/questions/28437313/org-mockito-exceptions-misusing-unfinishedstubbingexception-unfinished-stubbing"">org.mockito.exceptions.misusing.UnfinishedStubbingException Unfinished stubbing detected</a> , it is suggested that we cannot mock the classes of java.lang package to which these file utils belong? I do not want to create wrapper around this class. Is there any other way ? </p>
",https://stackoverflow.com/questions/43344893/powermock-and-fileutils-package,"['java', 'junit', 'mockito', 'powermock']",1025,TRUE,1,1
golang how to live test an http server?,"<p>I use gotests, and gorilla mux and I can unit test my http handlefunc handlers, but they do not respond to the proper http request methods as they should under the gorilla mux. How I can do a ""live server"" version of the test?</p>

<pre><code>func main() {
    router := mux.NewRouter()
    router.HandleFunc(""/"", views.Index).Methods(""GET"")
}

func Index(w http.ResponseWriter, r *http.Request) {
    w.Header().Set(""Content-Type"", ""application/json; charset=UTF-8"")
    w.WriteHeader(http.StatusOK)

    fmt.Fprintf(w, ""INDEX\n"")
}

func TestIndex(t *testing.T) {

    req, _ := http.NewRequest(""GET"", ""/"", nil)
    req1, _ := http.NewRequest(""POST"", ""/"", nil)
    rr := httptest.NewRecorder()

    handler := http.HandlerFunc(Index)

    type args struct {
        w http.ResponseWriter
        r *http.Request
    }
    tests := []struct {
        name string
        args args
    }{
        {name: ""1: testing get"", args: args{w: rr, r: req}},
        {name: ""2: testing post"", args: args{w: rr, r: req1}},
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            handler.ServeHTTP(tt.args.w, tt.args.r)
            log.Println(tt.args.w)
        })
    }
}
</code></pre>

<p>The problem here is that the function responds to both the get and post requests and
doens't take into account my main router. This is fine for unit testing the function,
but I think it would be better to just write an integrated test that tests the whole
thing and gets everything out of the way in one go. </p>
",https://stackoverflow.com/questions/42474259/golang-how-to-live-test-an-http-server,['go'],9810,TRUE,12,1
Can&#39;t import component in spec.ts,"<p>I'm running into something weird...</p>

<p>I'm using Karma, Jasmine and Angular2 in a ionic 2 app.</p>

<p>I want to do some unit testing and I achieved to create a basic one which is always successful <code>expect(true).toBe(true);</code></p>

<p>Now I want to test my components, but whenever I do <code>import { MyComponent } from './myComponent';</code> I get an error as follows:</p>

<pre><code>START:
Chrome 58.0.3029 (Linux 0.0.0) WARN: 'asmCrypto seems to be load from an insecure origin; this may cause to MitM-attack vulnerability. Consider using secure transport protocol.'
17 05 2017 22:41:28.303:WARN [reporter]: SourceMap position not found for trace: undefined
Chrome 58.0.3029 (Linux 0.0.0) ERROR
  Uncaught TypeError: Cannot read property 'prototype' of undefined
  at src/test.ts:168035

Finished in 1.318 secs / 0 secs @ 22:41:28 GMT+0200 (CEST)

SUMMARY:
✔ 0 tests completed
</code></pre>

<p>It probably has to do with the relative path as I tried to include a component from node_modules and terminal returned a success response.</p>

<p>Did anyone run into this error ?</p>
",https://stackoverflow.com/questions/44034876/cant-import-component-in-spec-ts,"['angular', 'testing', 'jasmine', 'components', 'karma-runner']",740,FALSE,1,0
How to unit test a component that depends on React Router?,"<p>I'm pretty new with unit testing React, not unit testing in general and I have a couple of questions.</p>

<p>I do have a component which represents a page on which a user can authenticate.
Now, I do want to test this component, but I'm unsure which functionalities I should test and which functionalities I don't test.</p>

<p>For example, my component has some internal state which holds the currently entered username, password, an error for the username field, a password for the username field, ...</p>

<p>Should the state be tested in general or should I test the UI using <code>find</code> in enzyme.
For example, when I update the field containing the username, the updated username is stored in the state, and the button to authenticate becomes activated.</p>

<p>So, should I test that when I enter a value in the input field, that the state is updated, or should I test that the DOM is updated by chechking for a class on the submit button?</p>

<p>Also, this component has <code>Link</code> components in it using react router which makes it difficult to test.</p>

<p>Therefore, I'm using the following HOC to render a component and pass in a router stub.</p>

<pre><code>export const stubRouterContext = (Component, props) =&gt; {
    function RouterStub() { }

    Object.assign(RouterStub, {
        makePath() {},
        makeHref() {},
        transitionTo() {},
        replaceWith() {},
        goBack() {},
        getCurrentPath() {},
        getCurrentRoutes() {},
        getCurrentPathname() {},
        getCurrentParams() {},
        getCurrentQuery() {},
        isActive() {},
        getRouteAtDepth() {},
        setRouteComponentAtDepth() {}
    });

    /**
     * Defines the component which contains stubbed router.
     *
     * @class RouterContextComponent
     * @extends {React.Component}
     */
    class RouterContextComponent extends React.Component {

        /**
         * Gets the child context of the component.
         *
         * @returns
         *
         * @memberof RouterContextComponent
         */
        getChildContext() {
            return {
                router: RouterStub,
                routeDepth: 0
            };
        }

        /**
        * Returns the HTML that represent the component.
        *
        * @memberof RouterContextComponent
        */
        render() {
            return &lt;Component {...props} /&gt;
        }
    }

    /**
     * Defines the child context types of the component.
     */
    RouterContextComponent.childContextTypes = {
        router: React.PropTypes.func,
        routeDepth: React.PropTypes.number
    };

    // Return the component that contains a stubbed router.
    return RouterContextComponent;
};
</code></pre>

<p>Now, I do have a unit test, but I'm unsure what to test.</p>

<pre><code>let wrappedComponent = stubRouterContext(LoginPageComponent, {
    startBackgroundOperation: () =&gt; {},
    stopBackgroundOperation: () =&gt; {}
});

// Act.
const wrapper = mount(
    &lt;wrappedComponent /&gt;
);
</code></pre>

<p>Any guidance is highly appreciated.</p>
",https://stackoverflow.com/questions/43745381/how-to-unit-test-a-component-that-depends-on-react-router,"['unit-testing', 'reactjs', 'enzyme']",245,FALSE,2,0
Remove Side Effect from an angular function,"<p>I am making a method that receive two parameters, <code>options</code> and <code>data</code>, but in the return values only return <code>options</code>, I want to implement unit testing on this project and I want to avoid <strong>side effects</strong> on this method to do it testeable, I am figure out witch is the best approach to do this, return an array with two values for each one or split this method in two small methods that return different values.</p>

<p>This is my method simplified for demostration:</p>

<pre><code>private setEst(data, options): object {

    const numCols: number = data.getColNumber();    
    const indxRows: Array&lt;Number&gt; = data.getIndexRows();
    const otherArray: : object[] = [];

    // Creating options output that will be returned
    for (let col = 1; col &lt; numCols; col++) {
        // Do something with options to modify the value of this param
        ...

        // Read data to create an array that will be used by the next process
        otherArray.push({
          id: data(col).getId();
        });
      }
    }

    // Output data as a side effect
    indxRows.forEach(indx =&gt; {
      for (let col = 1; col &lt; numCols; col++) {

        // Do something with data object and otherArray const, 
        // data is modified and returned as side effect...
        ...


      }
    });

    return options;
}
</code></pre>
",https://stackoverflow.com/questions/45112703/remove-side-effect-from-an-angular-function,"['javascript', 'angular', 'unit-testing', 'typescript', 'side-effects']",53,FALSE,1,0
Unit test case incase of no output channel for my Integration flow,"<p>I have only one handle() and then get(), no output channel. On sending the message to this handle getting the Object I am sending back in flow. But in unit test I am getting back boolean value. How to get the expected object back in unit testing also?</p>

<p>below is code unit test.</p>

<p>In Unit test - boolean value is coming on sending the message instead of expected object</p>

<p>Object o = this.acknowledgeAlarmInputChannel.send(message);
  System.out.println(""output: "" + o); // printing boolean value true
Code:</p>

<pre><code>@Bean
public IntegrationFlow acknowledgeAlarmGatewayFlow() {
    return IntegrationFlows.from(""acknowledgeAlarmInputChannel"")
            .handle(this::createAlarmAckEvent)
            .get();
}
</code></pre>

<p>Unit test:</p>

<pre><code>@Test
public void testEvent() {
    String expectedEMResponse = ""{\n"" +
            ""  \""data\"": {\n"" +
            ""    \""id\"": 19,\n"" +
            ""    \""type\"": \""alarms\"",\n"" +
            ""    \""attributes\"": {}\n"" +
            ""  }\n"" +
            ""}"";
    MessageHandler mockMessageHandler = mock(MessageHandler.class);
    this.acknowledgeAlarmInputChannel.subscribe(mockMessageHandler);

    MockRestServiceServer server = MockRestServiceServer.bindTo(restTemplate).build();
    server.expect(requestTo(emAcknowledgeEventUrl.replace(""{hostID}"", ""12"")))
            .andRespond(withSuccess(expectedEMResponse, MediaType.APPLICATION_JSON));

    AlarmInstance alarmInstance = new AlarmInstance();
    alarmInstance.setAlarmName(""a1"");
    alarmInstance.setInstanceId(""1"");
    alarmInstance.setAcknowledgedAt(new Date());
    alarmInstance.setAcknowledgedBy(""u1"");
    alarmInstance.setComponentName(""x1"");
    GenericMessage&lt;AlarmInstance&gt; message = new GenericMessage&lt;AlarmInstance&gt;(alarmInstance);

    Object o = this.acknowledgeAlarmInputChannel.send(message);
    System.out.println(""output: "" + o);
}
</code></pre>
",https://stackoverflow.com/questions/44250639/unit-test-case-incase-of-no-output-channel-for-my-integration-flow,['spring-integration'],148,TRUE,1,1
Angular2 Unit Test Mouse Events,"<p>I want to test one of methods which helps in closing Modal Window when closed outside of Modal Window container.</p>

<p><strong>Component Method</strong></p>

<pre><code>public hide(): void {
    this.visibleAnimate = false;
    setTimeout(() =&gt; { this.visible = false; }, 200);
  }

public onModalClicked(event: MouseEvent): void {
    if ((&lt;HTMLElement&gt;event.target).classList.contains('dialog-container')) {
      this.hide();
    }
  }
</code></pre>

<p><strong>Unit Test</strong></p>

<pre><code>it('should call hide method', fakeAsync(() =&gt; {
    component.hide();
    fixture.detectChanges();
    fixture.whenStable().then(() =&gt; {
      expect(component.visible).toEqual(false);
      tick(200);
      expect(component.visibleAnimate).toEqual(false);
    });
  }));



it('should call onModalClicked()', () =&gt; {
    const mockEvent = new Event('click'); --&gt; Error
    component.onModalClicked(mockEvent);
    console.log(component.visible);
  });
</code></pre>

<p>My Unit test runs fine on <code>hide()</code> method and please let me know if i am doing it in right way or not.</p>

<p>But i am really stuck how to test <code>onModalClicked()</code> method because that takes <em>MouseEvent</em> as parameter.</p>

<blockquote>
  <p>In my unit testing method, Event and MouseEvent mismatch error occurs, which is obviouse biut how to cover this method?</p>
</blockquote>
",https://stackoverflow.com/questions/45326847/angular2-unit-test-mouse-events,"['angular', 'unit-testing', 'karma-jasmine', 'angular2-testing']",7512,TRUE,1,1
How to write data-driven tests using Hspec?,"<p>I'm learning Haskell, and being a good developer, writing unit tests as I go. I implemented various sorting algorithms, and corresponding tests. However, I feel that separate tests are redundant, because the input and output are not varying, only the algorithms used to sort the input are. Is there a way to create data-driven tests or data tables as possible in various other unit testing frameworks?</p>

<pre><code>module RecursionSpec (main, spec) where

import Test.Hspec
import Recursion

main :: IO ()
main = hspec spec

spec :: Spec
spec = do
  let input = [3, 1, 5, 2, 4]
      output = [1, 2, 3, 4, 5]
  describe ""bubblesort"" $ do
    it (""sorts "" ++ show input) $ do
      bubblesort input `shouldBe` output

  describe ""mergesort"" $ do
    it (""sorts "" ++ show input) $ do
      mergesort input `shouldBe` output

  describe ""quicksort"" $ do
      it (""sorts "" ++ show input) $ do
        quicksort input `shouldBe` output
</code></pre>

<p>Also, I get the following warning that I'd like to understand and eliminate.</p>

<pre><code>warning: [-Wtype-defaults]
    • Defaulting the following constraints to type ‘Integer’
        (Show a0)
          arising from a use of ‘show’ at test/RecursionSpec.hs:14:21-30
        (Eq a0)
          arising from a use of ‘shouldBe’ at test/RecursionSpec.hs:15:7-40
        (Ord a0)
          arising from a use of ‘bubblesort’ at test/RecursionSpec.hs:15:7-22
        (Num a0)
          arising from the literal ‘1’ at test/RecursionSpec.hs:12:17
        (Num a0)
          arising from the literal ‘3’ at test/RecursionSpec.hs:11:16
    • In the second argument of ‘(++)’, namely ‘show input’
      In the first argument of ‘it’, namely ‘(""sorts "" ++ show input)’
      In the expression: it (""sorts "" ++ show input)
</code></pre>
",https://stackoverflow.com/questions/47967600/how-to-write-data-driven-tests-using-hspec,"['haskell', 'hspec']",505,TRUE,1,1
Unable to Autowire spring Component into camel Component,"<p>I'm guessing something is wrong integrating my spring and camel contexts.</p>

<p>I'm unit testing a Camel Component, and I'm trying to inject a bean (MainframeEncoderProvider) generated by spring component-scan. I can see that the bean is being constructed (breakpointing an init block), and I can autowire it into ToFalinkProducerTest, but it's not getting into the camel Component. The component is instantiated via META-INF auto-discovery, if that's relevant (<a href=""http://camel.apache.org/how-do-i-add-a-component.html"" rel=""nofollow noreferrer"">http://camel.apache.org/how-do-i-add-a-component.html</a>)</p>

<p>Test class setup:</p>

<pre><code>@RunWith(CamelSpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {""classpath*:spring-config/testContext.xml""})
public class ToFalinkProducerTest extends CamelTestSupport{

[some tests...]

@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {

        public void configure() {
            //@formatter:off

            from(""direct:start"")
                    .to(""tofalink:x?encoderName=test"")
                    .to(""mock:result"");
            //@formatter:on
        }
    };
}
</code></pre>

<p>testContext:</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;beans xmlns=""http://www.springframework.org/schema/beans""
       xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
       xmlns:context=""http://www.springframework.org/schema/context""
       xmlns:camel=""http://camel.apache.org/schema/spring""
       xsi:schemaLocation=""
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd

        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd

        http://camel.apache.org/schema/spring
        http://camel.apache.org/schema/spring/camel-spring.xsd
        ""&gt;

    &lt;!-- lightweight testcontext --&gt;
    &lt;context:annotation-config/&gt;
    &lt;context:component-scan base-package=""net.mo""/&gt;

    &lt;camel:camelContext&gt;
            &lt;camel:contextScan/&gt;
    &lt;/camel:camelContext&gt;


&lt;/beans&gt;
</code></pre>

<p>component:</p>

<pre><code>/**
 * Represents the component that manages {@link ToFalinkEndpoint}.
 */
public class ToFalinkComponent extends DefaultComponent {

    @Autowired
    private MainframeEncoderProvider provider;

    protected Endpoint createEndpoint(String uri, String remaining, Map&lt;String, Object&gt; parameters) throws Exception {
        Endpoint endpoint = new ToFalinkEndpoint(uri, this);
        setProperties(endpoint, parameters);
        return endpoint;
    }

    protected MainframeEncoderProvider getProvider() {
        return this.provider;
    }
}
</code></pre>
",https://stackoverflow.com/questions/44520685/unable-to-autowire-spring-component-into-camel-component,"['java', 'spring', 'apache-camel']",1320,TRUE,0,1
"How to assert variable content in unit test (Flask, Python3, Nose2)","<p>I have a Flask app where some page content comes from a global variable. I'm trying to set up some unit testing to assert the data, but I can't seem to get even a local variable to work:</p>

<pre><code>TEST_STRING = foo

self.assertIn(b['TEST_STRING'], response.data)
</code></pre>

<p>fails with:</p>

<pre><code>NameError: name 'b' is not defined
</code></pre>

<p>If I reference the plain variable:</p>

<pre><code>self.assertIn(TEST_STRING, response.data)
</code></pre>

<p>I get the expected failure:</p>

<pre><code>TypeError: a bytes-like object is required, not 'str'
</code></pre>

<p>The test succeeds if I hard-code the variable data into the test, but I'd rather not have to update the test if the variable changes. What am I missing here?</p>
",https://stackoverflow.com/questions/45778578/how-to-assert-variable-content-in-unit-test-flask-python3-nose2,"['python', 'python-3.x', 'unit-testing', 'flask', 'nose2']",590,TRUE,-1,1
Safely write unit tests that depend on the same file resource?,"<p>I'm writing unit tests for a C# project using Visual Studio's built-in unit testing tools, and many of these tests require the use of a file <code>TestData.xlsx</code>.</p>

<p>Currently when I run my tests I'm noticing that the previous test is not releasing its hold on the file in time for the next test to use it. This causes the test to fail. How am I supposed to write my tests in order to prevent this from happening?</p>

<p>Here is an example of what I'm dealing with:</p>

<pre><code>    [TestClass]
    public class ExcelWorksheetExtensionTests
    {
        private ExcelPackage excelPackage;

        private ExcelWorksheet excelWorksheet;

        [TestInitialize]
        [DeploymentItem(@""Assets\TestData.xlsx"")]
        public void TestInitialize()
        {
            FileInfo fileInfo = new FileInfo(@""Assets\TestData.xlsx"");
            this.excelPackage = new ExcelPackage(fileInfo);
            this.excelWorksheet = this.excelPackage.Workbook.Worksheets[""Sheet1""];
        }

        [TestCleanup]
        public void TestCleanup()
        {
            this.excelPackage.Dispose();
        }

        // This test may succeed...
        [TestMethod]
        public void TestGetRowIndexForExistingName()
        {
            Assert.AreEqual(this.excelWorksheet.GetRowIndex(""Object49"").Value, 6);
        }

        // ...But this test will fail because TestInitialize re-runs too quickly.
        [TestMethod]
        public void TestGetRowIndexForMissingName()
        {
            Assert.IsFalse(this.excelWorksheet.GetRowIndex(""NonExistentName"").HasValue);
        }
    }
</code></pre>
",https://stackoverflow.com/questions/46771585/safely-write-unit-tests-that-depend-on-the-same-file-resource,"['c#', 'visual-studio', 'unit-testing']",672,TRUE,3,1
Writing a testable Finagle Resolver,"<p>I'd like to test a Finagle Resolver properly.</p>

<p>Let's get a sample code:</p>

<pre class=""lang-scala prettyprint-override""><code>import com.twitter.finagle.{Addr, Address, Resolver}
import com.twitter.util._

class DummyResolver extends Resolver {

  override val scheme: String = ""sample""

  override def bind(arg: String): Var[Addr] = {

    val delegate = SomeFactory.fromArgs(arg).build()

    Var.async(Addr.Pending: Addr)(u =&gt; addrOf(u)(delegate))
  }
}
</code></pre>

<p>The use of a static factory prevents me from unit-testing the resolver.</p>

<p>As far as I know, the only way to provide the resolver to Finagle is to declare it into the <code>com.twitter.finagle.Resolver</code> file in <code>META-INF/services</code>. Thus, I cannot provide an instance myself.</p>

<p>Given those constraints, how to design the resolver to either:</p>

<ul>
<li>be able to provide an instance of the <code>delegate</code>,</li>
<li>or be able to properly test the behavior (and mock the delegate)?</li>
</ul>
",https://stackoverflow.com/questions/42646354/writing-a-testable-finagle-resolver,"['finagle', 'twitter-finagle']",97,FALSE,3,0
How to manage test output with google test in Eclipse CDT?,"<p>I am developing C++ code with Eclipse CDT. For unit testing I use google test which I integrated into Eclipse via the ""C++ Unit Testing"" plugin. A problem now occurs when tests generate output to stdout, e.g., as in the example below.</p>

<p>Test.cpp:</p>

<pre><code>#include &lt;iostream&gt;
#include &lt;string&gt;

#include ""gtest/gtest.h""

TEST(TestSuite, TestCase) {
    std::string s = ""str"";
    std::cout &lt;&lt; s;
    ASSERT_STREQ(s.c_str(), s.c_str());
}
</code></pre>

<p>AllTest.cpp</p>

<pre><code>#include ""gtest/gtest.h""

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&amp;argc, argv);
  return RUN_ALL_TESTS();
}
</code></pre>

<p>After building and running a suitable run configuration (for ""C/C++ Unit"" with ""Google Tests Runner""), the ""C/C++ Unit"" tab displays an error message on the top: ""Unkown error during parsing Google Test module output: Unexpected test module output.""</p>

<p>When I run the test inside Eclipse as an application, it passes and the console shows the correct output. Tests also pass with the plugin as long as they do not generate any output (e.g., change the string in Test.cpp to the empty string, <code>std::string s = """";</code>)</p>

<p>Is there any workaround to allow the execution of tests that generate output via the plugin? I know that I could, e.g., write the output to an ostream and and set that to be an ofstream during testing. However, I would prefer to test without any changes to the source code. Any ideas?</p>

<p>I am not so used to programming in C++, so thanks a lot for any advice.</p>

<p>P.S.: I am using Eclipse Oxygen (4.7.0).</p>
",https://stackoverflow.com/questions/46340935/how-to-manage-test-output-with-google-test-in-eclipse-cdt,"['c++', 'eclipse', 'unit-testing', 'eclipse-plugin', 'eclipse-cdt']",1279,TRUE,1,1
angular mouse enter unit test is not working,"<p>I am trying to test a mouse enter in angular 4 karma unit testing, There are not errors but the mouse enter is not calling the method binded to the mouse enter event.</p>

<pre><code>  &lt;div class=""contacts-content row no-gutters justify-content-between""
       (mouseover)=""onMouseEnter($event)""
       (mouseout)=""onMouseLeave($event)""
       (click)=""click()""
       [ngClass]=""{'edit': hover}""&gt;

  &lt;/div&gt;
</code></pre>

<p>In the component class I am calling below methods</p>

<pre><code>  onMouseEnter(event: any) {
    this.hover = true;
    this.elementRef.nativeElement.addClass = 'edit';
  }

  onMouseLeave(event: any) {
    this.hover = false;
    this.elementRef.nativeElement.addClass = 'un-edit';
  }
</code></pre>

<p>Testing the mouse enter:</p>

<pre><code>  it('should mouse over show the edit options to the user', () =&gt; {
    const div = fixture.nativeElement.querySelector('.contacts-content');
    const event = new Event('mouseenter');
    div.dispatchEvent(event);
    expect(component.hover).toBeTruthy('true');
    expect(fixture.nativeElement.querySelector('.col-1').getAttribute('display')).toBeTruthy('inline-block !important');
  });
</code></pre>

<p>In my test I am trying to call the mouse enter event but the expected result is not matching. More over when I see the code coverage, The method is even not called.</p>

<p>ny idea?</p>
",https://stackoverflow.com/questions/46456571/angular-mouse-enter-unit-test-is-not-working,"['angular', 'angular-unit-test', 'angular-test']",3500,TRUE,0,1
Ionic jasmine testing controller and scope undefined on it block,"<p>I am trying to create this unit testing using karma-jasmine for a existing Ionic 1 app; every is setup and running, but when I try my first test below both the var scope and controller are undefined; I already looked into several tutorials and blog but everything is like I did here.</p>

<p>status.tests.js</p>

<pre><code>describe('statusController', function(){
    var $controller, scope;    
    beforeEach(module('clerk'));

    beforeEach(inject(function($rootScope, _$controller_, $stateParams, $localStorage, $ionicPopup, 
            $cordovaGoogleAnalytics, $cordovaNetwork, ItemsService, OrdenService, ClientesService){

        scope = $rootScope.$new();

        // The injector unwraps the underscores (_) from around the parameter names when matching
        $controller = _$controller_('StatusCtrl', { $scope: scope });
        spyOn(scope, 'printReporte');
    }));

    afterEach(function() {
        scope.$destroy();
    });    

    describe('cierre', function(){
        it('cierre ejecutado', function() {
            console.log('scope: ' + JSON.stringify(scope));
            console.log('controller: ' + JSON.stringify($controller));

            expect($controller).toBeDefined();
            expect(scope).toBeDefined();
            expect(scope.printReporte).toHaveBeenCalledTimes(2);
        });    
    });
});
</code></pre>

<p>status.js</p>

<pre><code> angular.module('clerk.controllers')

 .controller('StatusCtrl', function ($scope, $rootScope, $stateParams, $localStorage, $ionicPopup, 
    $cordovaGoogleAnalytics, $cordovaNetwork, ItemsService, OrdenService, ClientesService) {

    $cordovaGoogleAnalytics.trackView('status');

    $scope.printReporte = function(){      
        OrdenService.printReporte($scope.dataStorage.ordenes, $scope.productosVendidos, $scope.totalClientes, $scope.total);
    }
..........
})
</code></pre>

<p>console log</p>

<pre><code>[vns@localhost clerk]$ gulp test
(node:30301) fs: re-evaluating native module sources is not supported. If you are using the graceful-fs module, please update it to a more recent version.
[11:59:03] Using gulpfile ~/workspace/clerk/gulpfile.js
[11:59:03] Starting 'test'...
WARN `start` method is deprecated since 0.13. It will be removed in 0.14. Please use 
  server = new Server(config, [done])
  server.start()
instead.
20 05 2017 11:59:04.166:INFO [karma]: Karma v1.7.0 server started at http://0.0.0.0:9876/
20 05 2017 11:59:04.167:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
20 05 2017 11:59:04.174:INFO [launcher]: Starting browser PhantomJS
20 05 2017 11:59:04.432:INFO [PhantomJS 2.1.1 (Linux 0.0.0)]: Connected on socket cndxz1n_qRnaz85aAAAA with id 60468258
LOG: 'scope: undefined'
LOG: 'controller: undefined'
PhantomJS 2.1.1 (Linux 0.0.0) statusController cierre cierre ejecutado FAILED
    www/lib/ionic/js/ionic.bundle.js:17918:53
    forEach@www/lib/ionic/js/ionic.bundle.js:13691:24
    loadModules@www/lib/ionic/js/ionic.bundle.js:17878:12
    createInjector@www/lib/ionic/js/ionic.bundle.js:17800:30
    workFn@www/lib/angular-mocks/angular-mocks.js:2922:60
    loaded@http://localhost:9876/context.js:162:17
    Expected undefined to be defined.
    tests/controllers/status.tests.js:26:44
    loaded@http://localhost:9876/context.js:162:17
    Expected undefined to be defined.
    tests/controllers/status.tests.js:27:38
    loaded@http://localhost:9876/context.js:162:17
    TypeError: undefined is not an object (evaluating 'scope.printReporte') in tests/controllers/status.tests.js (line 28)
    tests/controllers/status.tests.js:28:25
    loaded@http://localhost:9876/context.js:162:17
    TypeError: undefined is not an object (evaluating 'scope.$destroy') in tests/controllers/status.tests.js (line 18)
    tests/controllers/status.tests.js:18:14
    loaded@http://localhost:9876/context.js:162:17
PhantomJS 2.1.1 (Linux 0.0.0): Executed 1 of 2 (1 FAILED) (skipped 1) ERROR (0.048 secs / 0.016 secs)
[11:59:04] Finished 'test' after 911 ms
</code></pre>

<p>jasmine files</p>

<pre><code>files: [
  'www/lib/ionic/js/ionic.bundle.js',
  'www/lib/angular-mocks/angular-mocks.js',
  'www/lib/ngCordova/dist/ng-cordova.js', 
  'www/lib/ionic/js/angular/angular-resource.js',           
  'www/js/app.js',
  'www/js/controllers.js',
  'www/js/orden.js',
  'www/js/status.js',
  'www/js/cliente.js',
  'www/js/services/clientes.js',
  'www/js/services/items.js',
  'www/js/services/login.js',
  'www/js/services/orden.js',
  //'www/js/**/*.js',
  'tests/**/*tests.js'
]
</code></pre>

<p>using: 
ionic 1.3.1
jasmine 2.6.0
Node Version: 6.10.2</p>

<p>UPDATE:
karma config</p>

<pre><code>// list of files / patterns to load in the browser
files: [      
  ""www/lib/ionic/js/ionic.bundle.js"",
  ""www/lib/angular/angular.js"",
  ""www/lib/angular-mocks/angular-mocks.js"",      
  ""www/lib/ngCordova/dist/ng-cordova.js"", 
  'www/lib/ionic/js/angular/angular-resource.js',           
  'www/js/app.js',
  'www/js/services/clientes.js',
  'www/js/services/items.js',
  'www/js/services/login.js',
  'www/js/services/orden.js',            
  'www/js/controllers.js',
  'www/js/orden.js',
  'www/js/status.js',
  'www/js/cliente.js',
  //'www/js/**/*.js',
  'tests/**/*tests.js'
]
</code></pre>

<p>Also changed $rootScope to <strong>$rootScope</strong> underscore for every injection.</p>

<p>app.js</p>

<pre><code>angular.module('clerk', ['ionic', 'ionic.cloud','clerk.controllers', 'clerk.services', 'ngSanitize', 'ngCordova']) ....
</code></pre>
",https://stackoverflow.com/questions/44088043/ionic-jasmine-testing-controller-and-scope-undefined-on-it-block,"['javascript', 'angularjs', 'angular', 'ionic-framework', 'jasmine']",116,FALSE,0,0
How do I tell TextFieldParser to parse from a provided filesystem?,"<p>I'm writing a method which validates csv-files. I'm also unit-testing, so I'm setting up a mock file system with mock csv-files using <code>System.IO.Abstractions</code> I want to use <code>TextFieldParser</code> to read through the csv-file, but I'm unsure how I tell it to read from the path in the <code>IFileSystem</code> (from <code>System.IO.Abstractions</code>) provided.</p>

<p>Basically, the code looks something like this:</p>

<pre><code>    internal static bool ValidateCsvFile(IFileSystem fileSystem, string path)
    {
        var validated = false;
        using (var csvReader = new TextFieldParser(path))
        {
            //validation
        }
    }
</code></pre>

<p>And I want to know how I essentially tell the <code>TextFieldParser</code> to parse from a path using the filesystem provided, instead of using the local computer.</p>
",https://stackoverflow.com/questions/44888535/how-do-i-tell-textfieldparser-to-parse-from-a-provided-filesystem,"['c#', 'csv', 'textfieldparser']",312,TRUE,-1,2
How to define a macro that expands to a conditional statement in C++?,"<p>I want to create some context-sensitive macros. The macro</p>

<pre><code> #define LOG_WARNING(x) qWarning()().noquote().nospace() &lt;&lt; x
</code></pre>

<p>works fine, it is located in file <code>Macros.h</code>. I want to define a macro, which does not print log messages when called from unit testing routine. So, I modified  like</p>

<pre><code>#define LOG_INFO(x) if(!UNIT_TESTING) qInfo().noquote().nospace() &lt;&lt; x
</code></pre>

<p>Since in this way the macro will depend on <code>UNIT_TESTING</code>, I provided in the same <code>Macros.h</code></p>

<pre><code>extern bool UNIT_TESTING;   // Whether in course of unit testing
</code></pre>

<p>However, the compilers tells </p>

<pre><code>declaration does not declare anything [-fpermissive]
 extern bool UNIT_TESTING; // Whether in course of unit testing
        ^
</code></pre>

<p>At the same time, if the external is declared in the file from which <code>Macros.h</code> is included, it works fine. Do I wrong something?</p>
",https://stackoverflow.com/questions/45880958/how-to-define-a-macro-that-expands-to-a-conditional-statement-in-c,"['c++', 'qt', 'macros']",96,TRUE,0,1
How do I unit test HTTP requests?,"<p>As the title asks how do I test HTTP requests with Mocha and Chai?</p>

<p>I've recently started learning unit testing and I'm still getting confused with certain aspects of testing. I can get by fine testing methods that return a value but I'm confused on how to test methods that make HTTP/IO requests.</p>

<p>For example I have the following code:</p>

<pre><code>module.exports = someRequest =&gt; new Promise((resolve, reject) =&gt; 
    http.get('http://google.com', resp =&gt; {
        if(resp.headers['content-type'] !== 200) {
            reject(new Error('Failed to connect to Google'));
        }
        resolve('Connected to Google');
    })
);
</code></pre>

<p>I want to test 2 cases:</p>

<ol>
<li>The request to Google succeed</li>
<li>The request to Google failed</li>
</ol>

<p>Do I have to mock these requests and if so what's the purpose of mocking a method that is intended to make a HTTP request?</p>
",https://stackoverflow.com/questions/46531433/how-do-i-unit-test-http-requests,"['node.js', 'unit-testing', 'mocha.js', 'chai']",18979,TRUE,11,4
angular 4 unit test input text box (behavior) click / focus,"<p>I'm trying to unit test my component and in one test i want to focus / click the input text box. This is because when we click input text it opens a modal and i want to make sure the action happens.</p>

<p>This may be possible in e2e test but wanted to achieve it in unit testing due to a requirement.</p>

<p><strong>HTML template</strong></p>

<pre><code>&lt;input type=""text"" class=""search""/&gt;
</code></pre>

<p><strong>component.spec.ts</strong></p>

<p>assuming that the test bed module configuration is fine.</p>

<pre><code>...
it('focus the input element', () =&gt; {
   let searchTextBox: DebugElement = this.fixture.debugElement.query(By.css('search')).nativeElement;
   serachTextBox.click(); // is this possible or anything else
   fixture.detectChanges();
   ...
});
</code></pre>

<p><em>i am sorry that i couldn't share the entire code.</em></p>
",https://stackoverflow.com/questions/47209354/angular-4-unit-test-input-text-box-behavior-click-focus,"['angular', 'unit-testing', 'jasmine', 'angular-test']",926,FALSE,0,1
Should an exception be thrown and handled if it cannot happen?,"<p>I have a function that takes three parameters (day, month &amp; year) and creates a new dateTime. It's a public function that gets called when any of three comboboxes are dropped down. </p>

<p>When unit testing I accidentally entered an invalid value and it threw a invalid date time exception, but this won't be possible in the application as the comboboxes are pre-populated with valid values only.</p>

<p>So question is should I still check and handle this exception in the function?</p>
",https://stackoverflow.com/questions/45905677/should-an-exception-be-thrown-and-handled-if-it-cannot-happen,"['c#', 'validation', 'exception']",97,TRUE,0,3
Log statement during unit test,"<p>I am currently starting to unit test my android application. I am having problems when the unit test exercise code that has log statements in it. Here is a specific case. I have a class called ServiceManager that has a <code>setSystemPause()</code> and a <code>getSystemPause()</code> method. I just want a simple unit test that exercise that logic</p>

<p>ServiceManager class:</p>

<pre><code> public class ServiceManager implements IServiceManager {

    private final static String TAG = ""ServiceManager"";

    private boolean mSystemPauseStatus = false;

    public boolean getSystemPause () {
        Log.i (""TAG"", ""getSystemPause: "" + mSystemPauseStatus);
        return mSystemPauseStatus;
    }

    public void setSystemPause (boolean pauseStatus){
        Log.i (""TAG"", ""setSystemPause: "" + pauseStatus);
        mSystemPauseStatus = pauseStatus;
    }
}
</code></pre>

<p>The unit test:</p>

<pre><code>public class ServiceManagerTest {

    @Test
    public void testSystemPause() throws Exception {
        ServiceManager serviceManager = new ServiceManager();

        serviceManager.setSystemPause(false);
        assert (! serviceManager.getSystemPause());

        serviceManager.setSystemPause(true);
        assert (serviceManager.getSystemPause());
    }
}
</code></pre>

<p>The problem are the ""Log.i"" statements in my code. That causes the following error:</p>

<pre><code>java.lang.RuntimeException: Method i in android.util.Log not mocked.
</code></pre>

<p>I understand what is happening, during unit test the android.jar library that is used does not contain the real code and I need to mock that call to ""Log.i"". </p>

<p>But the code base that I am going to test contains a lot of Log statements. I don't want to mock each usage of the Log facility.</p>

<p>My question is how do people do unit testing in Android while having Log statements in their code. Is there another log facility that I can use in my code instead of the Log class.</p>

<p>I also read the page here:
<a href=""https://developer.android.com/training/testing/unit-testing/local-unit-tests.html"" rel=""nofollow noreferrer"">https://developer.android.com/training/testing/unit-testing/local-unit-tests.html</a></p>

<p>They suggest doing this in my build.gradle file:</p>

<pre><code>android {
  ...
  testOptions {
    unitTests.returnDefaultValues = true
  }
}
</code></pre>

<p>I don't want to resort to that because I just want the Log to appear. I want to properly mock all other facilities I will use in Android.</p>
",https://stackoverflow.com/questions/41509794/log-statement-during-unit-test,"['android', 'unit-testing']",579,FALSE,1,2
how to unittest and mock for open funtion,"<p>I have read many article over the last 6 hours and i still don't understand mocking and unit-testing. I want to unit test a open function, how can i do this correctly?</p>

<p>i am also concerned as the bulk of my code is using external files for data import and manipulation. I understand that i need to mock them for testing, but I am struggling to understand how to move forward. </p>

<p>Some advice please. Thank you in advance</p>

<p><strong>prototype5.py</strong></p>

<pre><code>import os
import sys
import io
import pandas
pandas.set_option('display.width', None)

def openSetupConfig (a):
""""""
SUMMARY
Read setup file
    setup file will ONLY hold the file path of the working directory
:param a: str
:return: contents of the file stored as str
""""""
try:
    setupConfig = open(a, ""r"")
    return setupConfig.read()

except Exception as ve:
    ve = (str(ve) + ""\n\nPlease ensure setup file "" + str(a) + "" is available"")
    sys.exit(ve)
dirPath = openSetupConfig(""Setup.dat"")
</code></pre>

<p><strong>test_prototype5.py</strong></p>

<pre><code>import prototype5
import unittest

class TEST_openSetupConfig (unittest.TestCase):
""""""
Test the openSetupConfig function from the prototype 5 library
""""""
def test_open_correct_file(self):
   result = prototype5.openSetupConfig(""Setup.dat"")
   self.assertTrue(result)


if __name__ == '__main__':
unittest.main()
</code></pre>
",https://stackoverflow.com/questions/45540691/how-to-unittest-and-mock-for-open-funtion,"['python', 'function', 'mocking', 'python-unittest']",94,FALSE,0,1
How to define global final variable that not changes for all tests under class?,"<p>I write unit test in Swift.</p>

<p>I call my app method and through <code>delegate</code> get back JSON object that represents request.</p>

<p>Now I want to validate all fields of JSON. Each validation should be in separate test.</p>

<p>This is what I wrote:</p>

<pre><code>class LaunchTests: XCTestCase, TestServerHandlerDelegate {

    var theExpectation:XCTestExpectation?

    var launchRequest:String? = nil   

    public func onSend(_ data: Data!) {        
        launchRequest = NSString(data: data, encoding: String.Encoding.utf8.rawValue)         
        theExpectation?.fulfill()
    }

override func setUp() {
        super.setUp()

        // we wait in setUp till get 'launchRequest'
        if launchRequest == nil {

            theExpectation = expectation(description: ""initialized"") 

             MyApp.shared().setDelegate(self)            
             MyApp.shared().launch()

            // Loop until the expectation is fulfilled in onDone method
            waitForExpectations(timeout: 500, handler: { error in XCTAssertNil(error, ""Oh, we got timeout"")})
        }
    }

override func tearDown() {
    super.tearDown()
}

func test___01_platform(){
    if let _ = fetchJsonValue(key: ""somekey"", value: launchRequest){
        //...
    }
}

func test___02_platform(){
    if let _ = fetchJsonValue(key: ""platform"", value: launchRequest){
        //...
    }
}
</code></pre>

<p>The problem is: for each run <code>launchRequest</code> is <code>nil</code>. I know that its right behavior but I want to call <code>MyApp.shared().launch()</code> once only and run multiple tests for <code>launchRequest</code> data.</p>

<p>How can I achieve it?</p>

<p>(I know its not good practice for unit testing but anyways)</p>

<p>Thanks,</p>
",https://stackoverflow.com/questions/42857491/how-to-define-global-final-variable-that-not-changes-for-all-tests-under-class,"['swift', 'unit-testing']",228,FALSE,3,2
Run karma on file change from command line/npm script,"<p>I have unit testing for an app set up with karma &amp; mocha &amp; reporting through istanbul.</p>

<p>npm script:</p>

<pre><code>""test"": ""cross-env BABEL_ENV=test karma start tests/karma.conf.js --single-run"",
</code></pre>

<p>What I want to do is have a script to run during development that will watch test &amp; app files for changes and re-run the tests as needed.</p>

<p>I tried replacing <code>--single-run</code> with <code>--auto-watch</code>:</p>

<pre><code>""test:watch"": ""cross-env BABEL_ENV=test karma start tests/karma.conf.js --auto-watch"",
</code></pre>

<p>but this re-runs continuously - as soon as one round of tests are finished, it starts over.</p>

<p>karma.conf.js:</p>

<pre><code>var webpackConfig = require('../build/webpack.conf.test');

module.exports = function (config) {
  config.set({
    browsers: ['PhantomJS'],
    frameworks: ['mocha', 'sinon-chai', 'phantomjs-shim'],
    reporters: ['spec', 'coverage'],
    files: ['./index.js'],
    preprocessors: {
      './index.js': ['webpack', 'sourcemap'],
    },
    webpack: webpackConfig,
    webpackMiddleware: {
      noInfo: true
    },
    coverageReporter: {
      dir: './coverage',
      reporters: [
        { type: 'lcov', subdir: '.' },
        { type: 'text' }
      ]
    }
  });
};
</code></pre>

<p>webpack.conf.test.js</p>

<pre><code>var path = require('path');
var webpack = require('webpack');
var vueLoaderConfig = require('./vue-loader.conf.js');
var eslintFormatter = require('eslint-friendly-formatter');
var HtmlWebpackPlugin = require('html-webpack-plugin');

function resolve(dir) {
  return path.join(__dirname, '..', dir);
}

module.exports = {
  devtool: '#inline-source-map',
  output: {
    path: path.resolve(__dirname, '../dist/js'),
    filename: 'build.js',
    publicPath: '/ntx/js/'
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      '@': resolve('src')
    }
  },
  resolveLoader: {
    alias: {
      'scss-loader': 'sass-loader'
    }
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': { NODE_ENV: '""testing""' }
    })
  ],
  // use inline sourcemap for karma-sourcemap-loader
  module: {
    rules: [
      { test: /\.css$/, use: ['vue-style-loader', { loader: 'css-loader', options: { minimize: false, sourceMap: false } }] },
      { test: /\.postcss$/, use: ['vue-style-loader', { loader: 'css-loader', options: { minimize: false, sourceMap: false } }] },
      { test: /\.less$/, use: ['vue-style-loader', { loader: 'css-loader', options: { minimize: false, sourceMap: false } }, { loader: 'less-loader', options: { sourceMap: false } }] },
      { test: /\.sass$/, use: ['vue-style-loader', { loader: 'css-loader', options: { minimize: false, sourceMap: false } }, { loader: 'sass-loader', options: { sourceMap: false, indentedSyntax: true } }] },
      { test: /\.scss$/, use: ['vue-style-loader', { loader: 'css-loader', options: { minimize: false, sourceMap: false } }, { loader: 'scss-loader', options: { sourceMap: false } }] },
      { test: /\.stylus$/, use: ['vue-style-loader', { loader: 'css-loader', options: { minimize: false, sourceMap: false } }, { loader: 'stylus-loader', options: { sourceMap: false } }] },
      { test: /\.styl$/, use: ['vue-style-loader', { loader: 'css-loader', options: { minimize: false, sourceMap: false } }, { loader: 'stylus-loader', options: { sourceMap: false } }] },
      { test: /\.(js|vue)$/,
        loader: 'eslint-loader',
        enforce: 'pre',
        include: [resolve('src'), resolve('test')],
        options: {
          formatter: eslintFormatter
        }
      }, {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
            css: ['vue-style-loader', { loader: 'css-loader', options: { minimize: false, souremap: false } }],
            postcss: ['vue-style-loader', { loader: 'css-loader', options: { minimize: false, souremap: false } }],
            less: ['vue-style-loader', { loader: 'css-loader', options: { minimize: false, souremap: false } }, { loader: 'less-loader', options: { sourceMap: false } }],
            sass: ['vue-style-loader', { loader: 'css-loader', options: { minimize: false, souremap: false } }, { loader: 'sass-loader', options: { sourceMap: false, indentedSyntax: true } }],
            scss: ['vue-style-loader', { loader: 'css-loader', options: { minimize: false, souremap: false } }, { loader: 'scss-loader', options: { sourceMap: false } }],
            stylus: ['vue-style-loader', { loader: 'css-loader', options: { minimize: false, souremap: false } }, { loader: 'stylus-loader', options: { sourceMap: false } }],
            styl: ['vue-style-loader', { loader: 'css-loader', options: { minimize: false, souremap: false } }, { loader: 'stylus-loader', options: { sourceMap: false } }],
          },
          transformToRequire: {
            video: 'src',
            source: 'src',
            img: 'src',
            image: 'xlink:href'
          }
        }
      }, {
        test: /\.js$/,
        loader: 'babel-loader',
        include: [resolve('src'), resolve('test')]
      }, {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: path.posix.join('./dist/img', 'img/[name].[hash:7].[ext]')
        }
      }
    ]
  }
};
</code></pre>

<p>Is there a way to do what I'm looking for?</p>
",https://stackoverflow.com/questions/45593809/run-karma-on-file-change-from-command-line-npm-script,"['javascript', 'node.js', 'karma-mocha', 'npm-scripts']",1289,FALSE,0,1
Spring RESTful webservice testing,"<p>I'm trying to figure out what type of testing i should do for my project layers.
I have made Controller->Service->DAO project model.
So I need to test DAO layer with unit tests and integration tests?
And Controller with unit tests and integration tests?
I just want to know how it has to be done in a professional way that code wont be overloaded :) And maybe some one has any links to of unit testing and integration testing for my case?</p>
",https://stackoverflow.com/questions/46858387/spring-restful-webservice-testing,"['spring', 'rest', 'unit-testing', 'integration-testing']",42,FALSE,0,1
karma html reporter not working as expected,"<p>I am working on a MEAN stack app using karma-jasmine as unit testing framework I am trying to find a good html reporter for unit testing results</p>

<p>first I tried <a href=""https://www.npmjs.com/package/karma-jasmine-html-reporter"" rel=""nofollow noreferrer"">karma-jasmine-html-reporter</a> but it not live reload the debug page I had to refresh it maually and this cause me stuck many times and thought the issue is in my code till I remember I have to reload the page! </p>

<p>I found this one also <a href=""https://www.npmjs.com/package/karma-jasmine-html-reporter-livereload"" rel=""nofollow noreferrer"">karma-jasmine-html-reporter-livereload</a> but it not working at all the debug page is blank and an error in the console</p>

<blockquote>
  <p>jasmineRequire is not defined</p>
</blockquote>

<p>Finally I tried this one <a href=""https://www.npmjs.com/package/karma-html-live-reporter"" rel=""nofollow noreferrer"">karma-html-live-reporter</a> the debug page is empty but with no errors in console and I can see the result of the tests logged in the console</p>

<p><strong>EDIT:</strong> 
I found a solution with this one when I read the log carefully I found that live html reporter is not working on debug page as expected but on localhost:5060 !! which is very strange
but when I go there I found everything working perfect </p>

<p>how to configure karma to open this port automatically?</p>

<p><strong>package.json</strong>:</p>

<pre><code>""jasmine-core"": ""^2.5.2"",
""karma"": ""^1.6.0"",
""karma-chrome-launcher"": ""^2.0.0"",
""karma-jasmine"": ""^1.1.0"",
""karma-jasmine-html-reporter"": ""^0.2.2"",
""karma-jasmine-html-reporter-livereload"": ""^1.0.0"",
</code></pre>

<p>please anyone has a similar situtaion could help or suggest something!<br>
Thanks in advance! </p>
",https://stackoverflow.com/questions/43584423/karma-html-reporter-not-working-as-expected,"['karma-runner', 'karma-jasmine', 'livereload']",576,FALSE,1,0
Is there a way to combine dependency injection with IDisposable?,"<p>A colleague and I were just talking about unit testing when I realised that I write code differently in certain circumstances...</p>

<p>If I'm using Entity Frameworks on its own, I'll tend to use the <code>IDisposable</code> interface via a <code>using</code> block:</p>

<pre><code>using (Context ctx = new Context()) { whatever(); }
</code></pre>

<p>But when I'm writing code that will be unit tested, I move the instantiation of the context into a constructor, so that I can pass in mocks to be used instead. I understand that this is a type of dependency injection, specifically ""constructor injection"".</p>

<p>Taking only a cursory look, I see this latter pattern recommended in a couple of articles:</p>

<ul>
<li><a href=""https://learn.microsoft.com/en-us/aspnet/web-api/overview/testing-and-debugging/mocking-entity-framework-when-unit-testing-aspnet-web-api-2"" rel=""nofollow noreferrer"">Mocking Entity Framework when Unit Testing ASP.NET Web API 2</a></li>
<li><a href=""https://msdn.microsoft.com/en-us/library/dn314429(v=vs.113).aspx#Anchor_5"" rel=""nofollow noreferrer"">Entity Framework Testing with a Mocking Framework (EF6 onwards)</a></li>
</ul>

<p>The problem with this (as my colleague and I reflected) is that the dispose method is never called. I suppose these objects get finalised as they move out of scope, but it seems less than ideal.</p>

<p>So, my question: <strong>is there a way to combine dependency injection with use of IDisposable?</strong></p>

<p>I can imagine three possible categories of answer:</p>

<ol>
<li>""Yes, there is a way and here's how...""</li>
<li>""No, there isn't a way. This is something you'll have to live with.""</li>
<li>""Tom, you have completely misunderstood something.""</li>
</ol>

<p>Whichever it is, we'd be really grateful!</p>
",https://stackoverflow.com/questions/45013293/is-there-a-way-to-combine-dependency-injection-with-idisposable,"['.net', 'entity-framework', 'unit-testing', 'dependency-injection', 'constructor-injection']",126,TRUE,1,1
How come this test fails?,"<p>I'm new to unit testing with jest &amp; enzyme.</p>

<p>I want to test if the component has a class name 'comment-box' or not.</p>

<p>In the component I conduct a unit test, I do have a div with class name 'comment-box'.</p>

<p>But, when I run a test, it fails.</p>

<p>Probably, Im making an easy mistake since Im new to jest &amp; enzyme.</p>

<p>Could anyone please help me to find out the problem?
Thanks!</p>

<h1>Log in my test runner.</h1>

<pre><code> FAIL  src/__tests__/components/CommentBox.test.js
  ● CommentBox › has the right class

    expect(received).toBe(expected)

    Expected value to be (using ===):
      true
    Received:
      false
</code></pre>

<h1>CommentBox.js</h1>

<pre><code>import React, { Component } from 'react';

class CommentBox extends Component {

    constructor(props) {
        super(props);
    }

    render() {
        return (
            &lt;div class=""comment-box""&gt;
                &lt;textarea&gt;&lt;/textarea&gt;
                &lt;button&gt;Submit&lt;/button&gt;
            &lt;/div&gt;
        )
    }
}

export default CommentBox;
</code></pre>

<h1>CommentBox.test.js</h1>

<pre><code>import React, { Component } from 'react';
import { shallow, mount, render } from 'enzyme';

import CommentBox from '../../components/CommentBox';
jest.unmock('../../components/CommentBox');


describe('CommentBox', () =&gt; {

    it('has the correct class', () =&gt; {

        const component = shallow(&lt;CommentBox /&gt;);

        expect(component.find('div').hasClass('comment-box')).toBe(true);

        // I tried this one as well.
        // expect(component.find('div').first().hasClass('comment-box')).toBe(true);


    });

});
</code></pre>
",https://stackoverflow.com/questions/44754916/how-come-this-test-fails,"['unit-testing', 'reactjs', 'enzyme', 'jestjs']",44,TRUE,0,1
Defining the path to a module in Windows (Where the module is the test file being run),"<p>I'm trying to run a simple automated test script. My code looks like:</p>

<pre><code>import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import os
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

gecko = os.path.normpath(os.path.join(os.path.dirname(__file__), 'geckodriver'))
binary = FirefoxBinary('C:\Program Files (x86)\Mozilla Firefox\Firefox.exe')
driver = webdriver.Firefox(firefox_binary=binary, executable_path=gecko+'.exe')


class PythonOrgSearch(unittest.TestCase):
def setUp(self):
    self.driver = driver

def test_search_in_python_org(self):
    driver = self.driver
    driver.get(""http://www.python.org"")
    self.assertIn(""Python"", driver.title)
    elem = driver.find_element_by_name(""q"")
    elem.send_keys(""pycon"")
    elem.send_keys(Keys.RETURN)
    assert ""No results found."" not in driver.page_source


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

if __name__ == ""__main__"":
    unittest.main()
</code></pre>

<p>When I run it, I get the error:
 Error while finding module specification for 'test_file.py' (AttributeError: module 'test_file' has no attribute '<strong>path</strong>')</p>

<p>I have been searching all over stack overflow for how to resolve this or define a path. I am new to Windows operating systems and unit testing so I'm very lost on how to resolve this. If you have any insight, it would be much appreciated.</p>
",https://stackoverflow.com/questions/44291734/defining-the-path-to-a-module-in-windows-where-the-module-is-the-test-file-bein,"['python', 'unit-testing', 'selenium', 'webdriver', 'geckodriver']",58,FALSE,0,0
EmbeddedCassandraServer getting &quot;java.lang.reflect.InvocationTargetException&quot;,"<p>Im using Cassandra-Unit 3.1.3.2 for doing unit testing.</p>

<p>Below is my code snippet</p>

<pre><code>EmbeddedCassandraServerHelper.startEmbeddedCassandra(EmbeddedCassandraServerHelper.CASSANDRA_RNDPORT_YML_FILE);
    appConfig.setCassandraPort(EmbeddedCassandraServerHelper.getNativeTransportPort());
    appConfig.setCassandraSession(Cluster.builder().addContactPoints(InetAddress.getByName(""localhost"").getHostAddress())
        .withPort(54567).build().connect());
    CqlSchemaInitializer cqlSchemaInitializer = new CqlSchemaInitializer(Arrays.asList(""create_keyspace.cql""));
    cqlSchemaInitializer.initialize(appConfig.getCassandraSession());
    appConfig.setCassandraLodgingCommerceContentDao(new CassandraLodgingCommerceContentDao(appConfig.getCassandraSession()));
</code></pre>

<p>appConfig is just the pojo which has setter/getter.
Im getting the below error,</p>

<blockquote>
  <p>Caused by: java.lang.reflect.InvocationTargetException    at
  sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at
  sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at
  sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
    at
  com.datastax.driver.core.NettyUtil.newEventLoopGroupInstance(NettyUtil.java:134)
    ... 35 more Caused by: java.lang.NoSuchFieldError:
  DEFAULT_MAX_PENDING_TASKS     at
  io.netty.channel.epoll.EpollEventLoop.(EpollEventLoop.java:84)
    at
  io.netty.channel.epoll.EpollEventLoopGroup.newChild(EpollEventLoopGroup.java:114)
    at
  io.netty.util.concurrent.MultithreadEventExecutorGroup.(MultithreadEventExecutorGroup.java:64)
    at
  io.netty.channel.MultithreadEventLoopGroup.(MultithreadEventLoopGroup.java:49)
    at
  io.netty.channel.epoll.EpollEventLoopGroup.(EpollEventLoopGroup.java:93)
    at
  io.netty.channel.epoll.EpollEventLoopGroup.(EpollEventLoopGroup.java:80)
    at
  io.netty.channel.epoll.EpollEventLoopGroup.(EpollEventLoopGroup.java:61)
    ... 40 more</p>
</blockquote>
",https://stackoverflow.com/questions/42850523/embeddedcassandraserver-getting-java-lang-reflect-invocationtargetexception,"['java', 'cassandra', 'server', 'pojo', 'cassandra-3.0']",1276,TRUE,2,1
PHPUnit Test Exception and AssertEquals,"<p>I'm actually trying to understand PHPUNIT and unit testing with PHP.</p>

<p>I have a classic divide methode. </p>

<pre><code> public function divide($firstNumber, $secondNumber){
    if( !is_numeric($firstNumber) ||  !is_numeric($secondNumber) ){
        throw new Exception(""Not a number"") ; 
    }
    if(  $secondNumber == 0 ) throw new Exception(""Can't divide by zero"") ; 

    return $firstNumber/$secondNumber ; 
}
</code></pre>

<p>As you can see It can return a Number or Exception.
Here is the testDivide code that I used. </p>

<pre><code> /**
 * @dataProvider diviserDateProvider
 * @covers MyTools::diviser     
 */
public function testDivide($firstNumber, $secondNumber, $expected) {
    $myToolsClasse = new MyTools();
    $this-&gt;assertEquals($expected, $myToolsClasse-&gt;diviser($firstNumber, $secondNumber));



}

public function diviserDateProvider() {
    return array(
        array(1, 0, new Exception(""Can't divide by zero"")),
        array(1, 2, 0.5),
        array("""", """", 0.5)
    );
}
</code></pre>

<p>As you can see there is a DataProvider with multiple testing values.
The problem is I have to Except/Assert an Exception which is the best way to do it ? </p>

<p>Should I use @exceptException and use try catch in my testDivide code ? 
Thanks for your help
have a nice day! </p>
",https://stackoverflow.com/questions/42748745/phpunit-test-exception-and-assertequals,"['php', 'unit-testing', 'testing', 'phpunit']",4064,TRUE,2,2
Mock PreferenceManager with Mockito,"<p>I am new in Android unit testing and I want to add some unit tests in an existing project. I am using the MVP design architecture. Inside my presenter, I have a call to <code>PreferenceManager</code> in order to get the default <code>SharedPrefences</code> but it always returns null. I have followed some tutorials and advices across stackoverflow on how to mock <code>PreferenceManager</code> and <code>SharedPreferences</code> but I can't make it work. This is my presenter class</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)
public class SettingsPresenterTest {
    @Mock
    private SettingsView mView;
    @Mock
    private LocalConfiguration conf;
    private SettingsPresenter mPresenter;

    public SettingsPresenterTest() {
        super();
    }

    @Before
    public void startUp() throws Exception {
        MockitoAnnotations.initMocks(LocalConfiguration.class);
        MockitoAnnotations.initMocks(PreferenceManager.class);


        mPresenter = new SettingsPresenter(mView);


        final SharedPreferences sharedPrefs = 
        Mockito.mock(SharedPreferences.class);
        final Context context = Mockito.mock(Context.class);

       Mockito.when(PreferenceManager.getDefaultSharedPreferences(context)).
       thenReturn(sharedPrefs);
    }


    @Test
    public void notificationsEnabledClicked() throws Exception {
        boolean notifsEnabled = false;
        mPresenter.notificationsEnabledClicked(notifsEnabled);

        Mockito.verify(mView).setNotificationsView(notifsEnabled);
    }
}
</code></pre>

<p>and here is the method where the <code>SharedPreferences</code> are returned null</p>

<pre><code>public class LocalConfiguration { 
    public TerritoryDto getLastSavedTerritory() {
           SharedPreferences preferences = 
           PreferenceManager.getDefaultSharedPreferences(H.getContext());
           String terrritoryString = preferences.getString(SAVED_TERRITORY, 
           null);
           return 
           SerializerHelper.getInstance().deserialize(terrritoryString, 
           TerritoryDto.class);
    }
}
</code></pre>

<p>Could you give me some guidelines on how to resolve this error?</p>
",https://stackoverflow.com/questions/46886351/mock-preferencemanager-with-mockito,"['android', 'unit-testing', 'junit', 'mockito', 'tdd']",1243,TRUE,5,1
IHttpActionResult vs HttpResponseMessage,"<p>I want to talk again about differences about <code>IHttpActionResult</code> and <code>HttpResponseMessage</code>. I know that <code>IHttpActionResult</code> is more flexible and good to use with unit testing. But currently I'm working on the project, that was migrated from WebAPI to WebAPi 2, and I want to try replace all usings of <code>HttpResponseMessage</code> with <code>IHttpActionResult</code>. 
I found in the code next lines:</p>

<pre><code>catch (Exception ex)
{
    return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
}
</code></pre>

<p>I want to clarify what is equivalent approach with <code>IHttpActionResult</code>. Is the result in code below will be equivalent to the result in the code above:</p>

<pre><code>catch (Exception ex)
{
    return Content(HttpStatusCode.InternalServerError, ex.Message);
}
</code></pre>

<p>Or should I use something else?</p>
",https://stackoverflow.com/questions/46159197/ihttpactionresult-vs-httpresponsemessage,"['c#', 'asp.net', 'asp.net-web-api']",2573,TRUE,2,2
jest unit test to mock events,"<p>I have a utility file that determines the enter key-down and triggers the click event of all the button type submit present in the document. </p>

<p>I need help to simulate key-down of enter key, and mock buttons with type submit so as to trigger their click.</p>

<p>I am using jest and enzyme for testing .</p>

<p>Below is the utility code :</p>

<pre><code>const runSubmitEventListener = () =&gt; {
    document.onkeydown = (e) =&gt; {
        e = e || window.event;
        if(e.key &amp;&amp; e.key.toLowerCase() === 'enter'){
            document.querySelector('button[type=""submit""]') &amp;&amp; document.querySelectorAll('button[type=""submit""]').click();
        }
    }
}

export default{
    runSubmitEventListener
}
</code></pre>

<p>Also, have started writing the test cases for which below is the file. Please suggest further steps, as I am new to jest unit testing.</p>

<pre><code>import events from './events';

describe('events utility', () =&gt; {
    it('should have runSubmitEventListener to be defined', () =&gt; {
        expect(events.runSubmitEventListener).toBeDefined();
    });
    it('should trigger click of button type submit on keydown enter key', () =&gt; {
        const event = new keyBoardEvent('keydown', {'key': 'enter', 'keycode': 13});
        document.dispatchEvent(event);
        // expect(events.runSubmitEventListener).toHaveBeenCalled();
    });
});
</code></pre>
",https://stackoverflow.com/questions/47694036/jest-unit-test-to-mock-events,"['unit-testing', 'enzyme', 'jestjs']",1660,FALSE,2,0
How do we unit-test functions which use randomness?,"<p>I am interested in best-practice techniques, if any, for unit-testing functions which use randomness. To be clear, I am <strong>not</strong> concerned with testing the distribution of random number generators.</p>

<p>As a toy example, let's consider this function:</p>

<pre><code>// Returns a random element from @array. @array may not be empty.
int GetRandomElement(int[] array);
</code></pre>

<p>Answers to <a href=""https://softwareengineering.stackexchange.com/questions/147134/how-should-i-test-randomness"">this question</a> suggest that we may inject a mock source of randomness, which makes sense. But I'm not sure exactly how I might use the mock. For example, let's assume that we have this interface:</p>

<pre><code>// A mock-friendly source of randomness.
interface RandomnessSource {
  // Returns a random int between @min (inclusive) and @max (exclusive).
  int RandomInt(int min, int max);
}
</code></pre>

<p>...And change the signature of <code>GetRandomElement()</code> to this:</p>

<pre><code>// Returns a random element from @array, chosen with @randomness_source.
// @array may not be empty.
int GetRandomElement(int[] array, RandomnessSource randomness_source);
</code></pre>

<p>All right, now a test could look like:</p>

<pre><code>MockRandomnessSource mock = new MockRandomnessSource();
mock.ExpectCall(RandomnessSource::RandomInt(0, 5)).Return(2);
AssertEquals(GetRandomElement({0, 10, 20, 30, 40}, mock), 20);
</code></pre>

<p>...which could work fine, but only if the implementation looks like this:</p>

<pre><code>// A fairly intuitive implementation.
int GetRandomElement(int[] array, RandomnessSource randomness_source) {
  // Pick a random number between [0..n), where @n is the @array's legnth.
  return array.Get(randomness_source.RandomInt(0, array.Length()));
}
</code></pre>

<p>...But nothing in the function specification prevents an implementation like this:</p>

<pre><code>// Less intuitive, but still a conforming implementation.
int GetRandomElement(int[] array, RandomnessSource randomness_source) {
  // Pick a random number between [1..n+1), only to subtract 1 from it.
  return array.Get(randomness_source.RandomInt(1, array.Length() + 1) - 1);
}
</code></pre>

<p>One idea which leaps to mind is that we may further constrain the function's contract, like this:</p>

<pre><code>// Returns a random element from @array, chosen with @randomness_source by
// by calling @RandomnessSource::RandomInt to pick a random index between
// 0 and the length of @array.
int GetRandomElement(int[] array, RandomnessSource randomness_source);
</code></pre>

<p>...But I can't quite get over the impression that this is placing too heavy a constraint on the function contract.</p>

<p>I also suspect that there might be better ways to define the interface <code>RandomnessSource</code> to make its callers more amenable to unit tests, but I'm not quite sure what/how.</p>

<p>...Which brings me to the question: What are the best-practice techniques (if any) for unit-testing functions which use randomness?</p>
",https://stackoverflow.com/questions/47966071/how-do-we-unit-test-functions-which-use-randomness,"['unit-testing', 'random']",116,FALSE,0,1
Test Database Class in java,"<p>I have a class which does basic db operations such as save, retrieve and delete object in the DB. It has an <code>establishConnection()</code> method which is called before each operation.</p>

<p>I also have another class which calls the <code>saveObject</code> method from the DB class to store a graph it creates if it does not exist just before returning it in the getter. To test this getter I tried junit but it fails at the part where it stores the object and gives me <code>java.lang.ExceptionInInitializerError</code> when i first set the graph and then just try to retrieve it but when i call the getter without setting the graph first so that the graph will be created then i get a <code>java.lang.NoClassDefFoundError</code>. I need to test both the classes with unit testing but I am not able to find any simple to follow example.</p>

<p>DB class outline:</p>

<pre><code>public final class DbUtils {

    private static Connection connectionDB;

    private static void establishConnection() { 
     ...
    }

    private static void closeConnection() {
     ... 
    }

    public static void saveObject(final Object graph, final Object map) {

        establishConnection();

        //convert Objects to Byte and store it;

        closeConnection();
    }

    public static Map&lt;String, Object&gt; retrieveObject(final String key) {
        establishConnection();
        //read byte and convert to object
        closeConnection();
        return multireturn;
    }

    public static boolean deleteObject(final String key) {
        establishConnection();
        //delete all object except object with key
        closeConnection();
        return (affectedRow &gt;= 1);

    }

}
</code></pre>

<p>GraphCreation class:</p>

<pre><code>public class GraphCreation {
    Graph graph;
    ...
    private createGraph(){....}

    public void setGraph(Graph G){
        this.graph=G;
    }

    public Graph getGraph(){
        if(this.graph==null){
            createGraph();
        }
        saveToDB(graph, map);
        return this.graph
    }

}
</code></pre>

<p>Current Test:</p>

<pre><code>@Mock
GraphCreation graph;

@Test
public void testSettingDependencyGraph() {
    graphCreation.setGraph(graph);
    Assert.assertEquals(Graph, graphCreation.getGraph());
}

@Test
public void testCreatingGraph(){
    graphCreation.setApplicationContext(applicationContext);
    graphCreation.setGraph(new Graph());
    moduleRegistrationBeans = new HashMap&lt;String, ModuleRegistration&gt;();
    ModuleRegistration m1 = new ModuleRegistration();
    m1.setName(""module1"");
    SDF1 = new TestSourceDataFactoryTemplate();
    VM1 = new TestModuleTemplate();
    m1.setSourceDataFactory(SDF1);
    m1.setModule(VM1);
    moduleRegistrationBeans.put(""module_1"", m1);
    PowerMock.reset(BeanFactoryUtils.class);
    PowerMock.mockStatic(BeanFactoryUtils.class);
    EasyMock.expect(BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ModuleRegistration.class)).andReturn(moduleRegistrationBeans);
    PowerMock.replay(BeanFactoryUtils.class);
    graphCreation.getDependencyGraph();
}
</code></pre>

<p>Both the tests fails at the saveToDB() method in the GraphCreation class.
I am new to unit-testing and these test were written by some other dev, i added a DB feature and now the unit test fails. 
Can someone help me or guide me towards how can i fix this and create unit test for the DB class.</p>
",https://stackoverflow.com/questions/43900007/test-database-class-in-java,"['java', 'unit-testing', 'junit', 'mockito', 'powermock']",771,TRUE,0,1
How big is console.assert() overhead?,"<p>I use <code>console.assert</code> at a lot of places in my Javascript library. It's a good practice from software development point of view (it's easiest form of unit testing). But I would like to know how much it will affect the performance of my library when run in production.</p>

<ul>
<li>Can browsers skip <code>console.assert</code>s when they get some kind of indication that the code is not running in development environment? e.g. Devtools is not open in Chrome</li>
<li>Can the bundling utilitiles like JS minifiers or Webpack/Browserify allow options to filter out <code>console.assert</code>s?</li>
</ul>
",https://stackoverflow.com/questions/46281603/how-big-is-console-assert-overhead,"['javascript', 'assert']",341,FALSE,4,0
Spring Boot test - overriding bootstrap.properties,"<p>We are using bootstrap.properties in a Spring Boot app to configure Spring Cloud Config related properties. </p>

<p>We want to ignore these properties during the testing as we don't want to connect to config server for unit testing. So we are looking for a way to completely undo properties from main <code>bootstrap.properties</code> and provide a new one for testing or override selective properties.</p>

<p>We tried with creating <code>src/test/resources/bootstrap.properties</code>, <code>src/test/resources/bootstrap-test.properties</code> with <code>spring.cloud.config.enabled=false</code> property but it didn't work.</p>

<p>we tried to set as below before starting the TestClass </p>

<pre><code>static {
    System.setProperty(""spring.cloud.config.enabled"", ""false"");
}
</code></pre>

<p>and it didn't work.</p>

<p>While Spring Boot documentation is pretty good about how application.properties works, I couldn't find even one reference to <code>bootstrap.properties</code>.</p>

<p>Any help is much appreciated on a reliable way to override <code>bootstrap.properties</code> during testing.</p>
",https://stackoverflow.com/questions/41985262/spring-boot-test-overriding-bootstrap-properties,"['spring', 'spring-boot']",24233,TRUE,20,3
How to unit test a library that uses JNI?,"<p>Unit testing best practices call for the use of inversion of control to ensure that unit tests run independently of each other even if they depend on singleton instances (each test gets their own ""singleton"").</p>

<p>What is the recommendation for testing a library that uses JNI to manipulate a native resource that only exists once per Process (e.g. the terminal)?</p>

<p>I'm not asking about testing the actual JNI code but rather the Java code that depends on the native code as a side-effect.</p>
",https://stackoverflow.com/questions/41663539/how-to-unit-test-a-library-that-uses-jni,"['java', 'unit-testing', 'java-native-interface', 'inversion-of-control']",2611,TRUE,1,1
How to generate a websocket error,"<p>I am writing a library that has server and client components that use websockets as the transport. I'm testing on a variety of browsers and need to test some behaviors tied to errors and the sockets unexpectedly closing. </p>

<p>Is there a way to cause an error in the websocket (aside from trying to connect to an invalid url/non-websocket server)?</p>

<p><strong>NOTE:</strong> I am <strong>not</strong> unit testing. I need to test how clients interact with servers, within different browsers, so mocking the websockets is not an option.</p>
",https://stackoverflow.com/questions/46146225/how-to-generate-a-websocket-error,"['javascript', 'websocket', 'integration-testing']",699,TRUE,1,1
Unit testing angularJS controller where data is updated using angular.copy from a factory after a GET call,"<p>I'm really new to Angular Unit testing using Karma and Jasmine, and I'm unable to find anything that would guide me in the right direction with regards to my problem. I have my Angular app called <code>myApp</code>. The app has multiple components each defined as their own modules that are then injected in the app.</p>

<p><strong>App</strong></p>

<pre><code>angular.module('myApp', ['ngRoute', 'ui-bootstrap', 'dashboard', 'projects']);
</code></pre>

<p><strong>Controller</strong></p>

<pre><code>angular.module('dashboard', []).controller('dashboardController', 
['dashboardService', '$rootScope', '$scope', '$http', function() {

  $scope.teamMemebrs = dashboardService.teamMembers;
  dashboardService.getTeamMemebrs();

}]);
</code></pre>

<p><strong>Service</strong></p>

<pre><code>angular.module('dashboard').service('dashboardService',
['$http', '$q', function($http, $q) {
    let loadTeamMembers = () =&gt; {
       return $http.get(APIendPoint).then( (response) =&gt; {
         return response;
       }, (response) =&gt; {
         return response;
       } ); 
    };

    let dashboardService = {
      teamMembers : [],
      getTeamMembers() {
        return $q.when(loadTeamMembers()).then( (response) =&gt; {
          let team = response.status === 200 ? response.data : [];
          angular.copy(team, dashboardService.teamMemebrs);
        });
      }          
    };
    return dashboardService;
  }
]);
</code></pre>

<p>I am trying to test the controller and my test looks as follows, but the test fails because scope.teamMembers is undefined. What am I doing wrong?</p>

<p><strong>Test Spec</strong></p>

<pre><code>describe('Dashboard', () =&gt; {

    let scope, dashboardController, dashboardService, $httpBackend;

    //This is what API call is expected to return
    let sampleResponse = [ {name: 'Jane Doe'},
                           {name: 'Amy Smith'},
                           {name: 'John Hopkins'} ];

    beforeEach(angular.mock.module('myApp'));
    beforeEach(angular.mock.module('dashboard'));

    beforeEach(angular.mock.inject( (_$rootScope_, _$controller_, _dashboardService_, _$httpBackend_) =&gt; {

        scope = _$rootScope_.$new();
        $controller = _$controller_;
        dashboardService = _dashboardService_;

        spyOn(dashboardService, 'getTeamMembers').and.callThrough();

        dashboardController = $controller('dashboardController', { $scope: scope, dashboardService: dashboardService });

        scope.$apply();
    }));

    it('should exist', () =&gt; {
        expect(dashboardController).toBeDefined();
    });

    it('call dashboardService and populate scope.teamMembers', () =&gt; {
        expect(dashboardService.getTeamMembers).toHaveBeenCalled();
        expect(scope.teamMemebrs).toEqual(sampleResponse);
    });
});
</code></pre>
",https://stackoverflow.com/questions/46854940/unit-testing-angularjs-controller-where-data-is-updated-using-angular-copy-from,"['javascript', 'angularjs', 'unit-testing', 'testing', 'karma-jasmine']",121,FALSE,1,0
Setting up cookies for Guzzle CookieJar,"<p>I am doing unit testing in PHP for a site that requires authentication. Authentication is cookie based, so I need to be able to put a cookie like this in the cookie jar:</p>

<pre><code>[ 'user_token' =&gt; '2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae' ] 
</code></pre>

<p>The web application can then use this known good token for the testing data, and will be able to authenticate under testing conditions to interact with the data fixtures.</p>

<p>Also, it must be a secure cookie, and I (obviously) need to set the domain.</p>

<p>Problem is: I don't know how to make and set this cookie and stick it in the jar. How do you do that?</p>
",https://stackoverflow.com/questions/42057302/setting-up-cookies-for-guzzle-cookiejar,"['php', 'cookies', 'guzzle']",25003,TRUE,9,3
How should I autoload WordPress plugin classes using composer for testing?,"<p>I'm working in a WordPress plugin, following the WordPress Coding Standards.</p>

<p>This is the current structure for the plugin:</p>

<pre><code>.
├── includes
├── languages
├── views
├── class-plugin-admin.php
├── class-plugin.php
└── plugin.php
</code></pre>

<p>That said, I would like to use the Composer autoloader to load both classes (for unit testing purposes).</p>

<p>Today I've been loading them like this:</p>

<pre><code>""autoload-dev"": {
    ""files"": [
        ""class-plugin.php"",
        ""class-plugin-admin.php""
    ]
}
</code></pre>

<p>However, not sure if this one would be the best way to do it.</p>

<p>So here are the questions:</p>

<ul>
<li>Should I move my classes to a subdirectory in the plugin?</li>
<li>Which one would be the best way to load them via composer?</li>
</ul>
",https://stackoverflow.com/questions/46017908/how-should-i-autoload-wordpress-plugin-classes-using-composer-for-testing,"['php', 'wordpress', 'phpunit', 'composer-php']",834,TRUE,1,1
Is the trait Owner useful in unit tests?,"<p>In 2012, Visual Studio has introduced the concept of trait, as described in this <a href=""https://learn.microsoft.com/en-us/visualstudio/test/run-unit-tests-with-test-explorer"" rel=""nofollow noreferrer"">article</a>.</p>

<p>One of the attributes is the <a href=""https://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.ownerattribute(v=vs.140).aspx"" rel=""nofollow noreferrer"">Owner trait</a> that specifies the person responsible for a test method. </p>

<p>I would like to know if it is recommended to use this trait or not. My primary intuition will be to <strong>ignore this feature because of the collective code ownership principle</strong>.</p>

<p>So my question is : what are the reasons we should use (or not) the <code>Owner</code> trait in Visual Studio unit testing framework ?</p>
",https://stackoverflow.com/questions/45712467/is-the-trait-owner-useful-in-unit-tests,"['c#', '.net', 'visual-studio', 'unit-testing']",817,TRUE,1,1
CDI Produces Method InjectionPoint is Null,"<p>I am leaning CDI Annotation have a question with respect to Produces Annotation:</p>

<p>I have a Bank </p>

<pre><code>public interface Bank {
    public void withdrawal();
    public void deposit();
}
</code></pre>

<p>Two Implementation flavors</p>

<pre><code>public class BankOfAmerica implements Bank {
    public void withdrawal() {
        System.out.println(""You are withdrawing from Bank Of America"");
    }

    public void deposit() {
        System.out.println(""You are depositing in Bank Of America"");
    }
}

public class Chase implements Bank {
    public void withdrawal() {
        System.out.println(""You are withdrawing from Chase"");
    }

    public void deposit() {
        System.out.println(""You are depositing in Chase"");
    }
}
</code></pre>

<p>A Qualifier</p>

<pre><code>@Qualifier
@Retention(RUNTIME)
@Target({TYPE, METHOD, PARAMETER, FIELD})
public @interface BankProducer {
}
</code></pre>

<p>An Enum</p>

<pre><code>public enum BankName {
    DCU(DCU.class), Chase(Chase.class), BankOfAmerica(BankOfAmerica.class);

    private Class&lt;? extends Bank&gt; bankType;

    private BankName(Class&lt;? extends Bank&gt; bankType) {
        this.bankType = bankType;
    }

    public Class&lt;? extends Bank&gt; getBankType() {
        return bankType;
    }
}
</code></pre>

<p>An Annotation to bind the BankName</p>

<pre><code>@Retention(RUNTIME)
@Target({TYPE, METHOD, PARAMETER, FIELD})
public @interface BankType {
    @Nonbinding
    BankName value();
}
</code></pre>

<p>A Factory</p>

<pre><code>public class BankFactory {
    @Produces
    @BankProducer
    public Bank createBank(@Any Instance&lt;Bank&gt; instance, InjectionPoint injectionPoint) {
        Annotated annotated = injectionPoint.getAnnotated();
        BankType bankTypeAnnotation = annotated.getAnnotation(BankType.class);
        Class&lt;? extends Bank&gt; bankType = bankTypeAnnotation.value().getBankType();
        return instance.select(bankType).get();
    }
}
</code></pre>

<p>And a JUnit</p>

<pre><code>@RunWith(Arquillian.class)
public class ProducesTest {
    @Inject
    @BankProducer
    @BankType(BankName.BankOfAmerica)
    private Bank bankOfAmerica;

    @Deployment
    public static JavaArchive createDeployment() {
        return ShrinkWrap.create(JavaArchive.class).addPackages(true, ""com.tutorial.produces"")
            .addAsManifestResource(EmptyAsset.INSTANCE, ""beans.xml"").merge(getDependecies());
    }

    private static JavaArchive getDependecies() {
        JavaArchive[] javaArchives = Maven.configureResolver().loadPomFromFile(""pom.xml"")
            .resolve(""org.projectlombok:lombok"").withTransitivity().as(JavaArchive.class);
        JavaArchive mergedLibraries = ShrinkWrap.create(JavaArchive.class);
        for (JavaArchive javaArchive : javaArchives) {
            mergedLibraries.merge(javaArchive);
        }
        return mergedLibraries;
    }

    @Test
    public void create() {
        assertEquals(banks.getBankOfAmerica().getClass(), BankOfAmerica.class);
    }
}
</code></pre>

<p>POM - using tomee</p>

<pre><code>&lt;dependency&gt;
    &lt;groupId&gt;org.apache.tomee&lt;/groupId&gt;
    &lt;artifactId&gt;javaee-api&lt;/artifactId&gt;
    &lt;version&gt;7.0-1&lt;/version&gt;
    &lt;scope&gt;provided&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.apache.tomee&lt;/groupId&gt;
    &lt;artifactId&gt;arquillian-tomee-embedded&lt;/artifactId&gt;
    &lt;version&gt;7.0.3&lt;/version&gt;
    &lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.jboss.shrinkwrap.resolver&lt;/groupId&gt;
    &lt;artifactId&gt;shrinkwrap-resolver-depchain&lt;/artifactId&gt;
    &lt;version&gt;2.2.2&lt;/version&gt;
    &lt;scope&gt;test&lt;/scope&gt;
    &lt;type&gt;pom&lt;/type&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;junit&lt;/groupId&gt;
    &lt;artifactId&gt;junit&lt;/artifactId&gt;
    &lt;version&gt;4.10&lt;/version&gt;
    &lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
</code></pre>

<p>I am getting a NullPointer exception in my factory createBank method. InjectionPoint is Null. What is the issue and how do I resolve it?</p>

<p>Alternate Solution: Tried Weld</p>

<pre><code>&lt;dependency&gt;
    &lt;groupId&gt;org.jboss.weld.se&lt;/groupId&gt;
    &lt;artifactId&gt;weld-se&lt;/artifactId&gt;
    &lt;version&gt;2.2.8.Final&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>

<p>JUnit</p>

<pre><code>@RunWith(WeldJUnit4Runner.class)
public class ProducesWeldTest {
    @Inject
    @BankProducer
    @BankType(BankName.BankOfAmerica)
    private Bank bankOfAmerica;

    @Test
    public void create() {
         assertEquals(bankOfAmerica.getClass(), BankOfAmerica.class);
    }
}
</code></pre>

<p>WeldContext and WeldJUnit4Runner are from here - 
<a href=""http://memorynotfound.com/java-se-unit-testing-cdi-junit-jboss-weld-se/"" rel=""nofollow noreferrer"">http://memorynotfound.com/java-se-unit-testing-cdi-junit-jboss-weld-se/</a></p>
",https://stackoverflow.com/questions/45575400/cdi-produces-method-injectionpoint-is-null,"['java', 'junit', 'cdi']",998,FALSE,1,1
Tool to identify a missing tag for an HTML element,"<p>As part of the WebPage automation, I'm looking to ensure development team is adding a ID tag with unique value for each of the web element, so that, the automation team can create a easily maintainable object repository.</p>

<p>In this context, was looking for the help on a tool or a process that I can share with the Development team, so that, they can execute it as part of the unit testing to identify missing ID tag for each HTML element.</p>

<p>Any help will be highly appreciated.</p>
",https://stackoverflow.com/questions/41743407/tool-to-identify-a-missing-tag-for-an-html-element,"['html', 'dom', 'process', 'automation']",65,FALSE,1,0
How to unit test an observable with jasmine,"<p>I've added some code to a constructor and now my unit tests are failing. The new code sets either true or false to <code>this.isFollowOnMode</code> from an observable:</p>

<pre><code>import { CustomerGroupService } from 'customerGroup.service';

class HeaderBarController {
    private isFollowOnMode: boolean;

    constructor(private customerGroupService: CustomerGroupService) {
        'ngInject';

        //new code that is causing test to fail:

        this.customerGroupService.isFollowOnMode$ // will be true or false
            .subscribe((isFollowOnMode) =&gt; {
                this.isFollowOnMode = isFollowOnMode;
            });
    }

    // other stuff
}

export default HeaderBarController;
</code></pre>

<p>I get the following error in my unit test:</p>

<blockquote>
  <p>PhantomJS 2.1.1 (Mac OS X 0.0.0) Controller: HeaderBarController should be defined FAILED
  TypeError: undefined is not a constructor (evaluating 'this.customerGroupService.isFollowOnMode$'</p>
</blockquote>

<p>And this is my unit test that is failing:</p>

<pre><code>describe('Controller: HeaderBarController', function () {
    beforeEach(angular.mock.module(module.name));

    beforeEach(angular.mock.module(function ($provide) {
        $provide.service('customerGroupService', () =&gt; { });

    }));

    beforeEach(inject(function ($rootScope, $componentController) {
        this.$scope = $rootScope.$new();
        this.ctrl = $componentController('headerBar',
            {
                // locals
                $scope: this.$scope,
                $element: [{}],
                $attrs: [],
            },
            {
                // scope bindings
            }
        );
    }));

    it('should be defined', function () {
        expect(this.ctrl).toBeDefined();
    });

});
</code></pre>

<p>So it seems I'm not setting <code>this.customerGroupService.isFollowOnMode$</code>. the default value for it should be false. in the unit test. I'm new to unit testing.</p>
",https://stackoverflow.com/questions/45658856/how-to-unit-test-an-observable-with-jasmine,"['angular', 'typescript', 'jasmine']",1243,TRUE,1,1
How to unit test promises in react/redux application,"<p>Looking at the advanced example on the <a href=""http://redux.js.org/docs/advanced/ExampleRedditAPI.html"" rel=""nofollow noreferrer"">react-redux</a> site, what is the best way to unit test the <code>fetchPosts</code> function using <code>mocha</code>, <code>chai</code> and <code>sinon</code>?  It uses a promise chain so in view of this, I have looked at <code>chai-as-promised</code>.</p>

<p>The promises chain together with the last one resolving to an empty value and dispatching an action to update the redux state.</p>

<p>App code:</p>

<pre><code>export function fetchPosts(subreddit) {   
    return dispatch =&gt; {
      dispatch(requestPosts(subreddit))
      return fetch(`https://www.reddit.com/r/${subreddit}.json`)
        .then(response =&gt; response.json())
        .then(json =&gt; dispatch(receivePosts(subreddit, json)))   
    } 
}

//other functions

export function requestPosts(subreddit){
    return {
        type:REQUEST_POSTS,
        subreddit
    }
}

export function receivePosts(subreddit,json){
    return {
        type:RECEIVE_POSTS,
        subreddit,
        posts:json.data.children.map(child =&gt; child.data),
        receivedAt:Date.now()
    } 
}
</code></pre>

<p>My attempt at unit testing:</p>

<pre><code>describe('fetchPosts action creator', () =&gt; {
    it('should have one parameter', () =&gt; {
        expect(fetchPosts.length).to.equal(1);
    });

    it('should return a function holding one parameter', () =&gt; {
        let subreddit = 'frontend';
        expect(fetchPosts(subreddit).length).to.equal(1);
    });

   it('should execute the dispatch funcion with requestPosts' ,() =&gt;{
       let spy = spy(dispatch);
       let subreddit = 'frontend';
       expect(spy.calledWith(fetchPosts(subreddit))).to.be.calledOnce;
       expect(spy.calledWith(receivePosts(subreddit,json))).to.be.calledOnce;
   })
})
</code></pre>

<p>My thoughts are</p>

<ul>
<li>Test <code>fetchPosts()</code> can hit the reddit api</li>
<li>Check the response is valid json</li>
<li>Check that <code>dispatch</code> is called twice with <code>requestPosts</code> and <code>receivePosts</code></li>
</ul>
",https://stackoverflow.com/questions/46791110/how-to-unit-test-promises-in-react-redux-application,"['javascript', 'unit-testing', 'promise', 'react-redux', 'chai']",335,FALSE,1,1
Invalid or unexpected token &quot;��&quot; when trying to test with mocha,"<p>I'm trying to get into unit testing, but when I try to test my code I'm getting this in the terminal:</p>

<pre><code> D:\VS Code\VS Code\tests\test\test.js:1
(function (exports, require, module, __filename, __dirname) { ��'
                                                              ^
SyntaxError: Invalid or unexpected token
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at C:\Users\SSD\AppData\Roaming\npm\node_modules\mocha\lib\mocha.js:230:27
    at Array.forEach (native)
    at Mocha.loadFiles (C:\Users\SSD\AppData\Roaming\npm\node_modules\mocha\lib\mocha.js:227:14)
    at Mocha.run (C:\Users\SSD\AppData\Roaming\npm\node_modules\mocha\lib\mocha.js:495:10)
    at Object.&lt;anonymous&gt; (C:\Users\SSD\AppData\Roaming\npm\node_modules\mocha\bin\_mocha:469:18)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:504:3
</code></pre>

<p>I followed the steps given in the mocha documentation here:
 <a href=""https://mochajs.org/#installation"" rel=""nofollow noreferrer"">https://mochajs.org/#installation</a></p>

<ol>
<li>npm install mocha</li>
<li>mkdir test</li>
<li>$null > test/test.js</li>
</ol>

<p>Then I literally copied and pasted the example</p>

<pre><code>    var assert = require('assert');
describe('Array', function() {
  describe('#indexOf()', function() {
    it('should return -1 when the value is not present', function() {
      assert.equal(-1, [1,2,3].indexOf(4));
    });
  });
});
</code></pre>

<p>Set up the test in package.json:</p>

<pre><code>""scripts"": {
""test"": ""mocha""
</code></pre>

<p>}</p>

<p>Then ran the command <code>npm test</code>
No matter what test example I take the error is the same. I've also tried to uninstall and install mocha again, I've tried chai also. Same error.  </p>
",https://stackoverflow.com/questions/45139778/invalid-or-unexpected-token-when-trying-to-test-with-mocha,"['javascript', 'node.js', 'unit-testing', 'mocha.js']",1852,TRUE,1,2
Mockito Unit test: Factory create newInstance,"<p>For unit testing I want to test good and bad scenario's</p>

<p>I'm getting a bit stuck on the Factory.createFoo() method.
How do I write proper unit tests for this (with Mockito)</p>

<pre><code>public class Bar extends Foo {
    public Bar() {}
    public Bar(Scenario scenario){
       ...DoStuff..
    }
}

public static &lt;T extends Foo&gt; T createFoo(Class&lt;T&gt; fooClass) throws RuntimeException {
    try {
        return fooClass.newInstance();
    } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
        throw new RuntimeException(""Could not create the Foo: "" + fooClass.getSimpleName(), e);
    }
}

public static &lt;T extends Foo&gt; T createFoo(Scenario scenario, Class&lt;T&gt; fooClass) throws RuntimeException {
    try {
        return fooClass.getDeclaredConstructor(Scenario.class).newInstance(scenario);
    } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
        throw new RuntimeException(""Could not create the needed Foo: "" + fooClass.getSimpleName(), e);
    }
}
</code></pre>

<p>I would like to be able to mock the following parts:</p>

<pre><code>fooClass.newInstance();

fooClass.getDeclaredConstructor(Scenario.class).newInstance(scenario);
</code></pre>

<p>I've found some factory examples, but all without the generic </p>

<pre><code>Class&lt;T&gt;
</code></pre>

<p>making those examples invalid for me.</p>

<p>How to proceed to test these kind of factory methods?
If there is a design flaw that is making this non testable, don't hesitate to point me those flaws ;-)</p>
",https://stackoverflow.com/questions/44001831/mockito-unit-test-factory-create-newinstance,"['unit-testing', 'mockito', 'factory']",951,TRUE,1,1
Making tests independent in Node JS Tape,"<p>I am trying to test functions in my script that I have written in Node JS. I am using tape for unit testing. But I am facing one problem of how to make each test case independent. Eg. there are some global variables in the script. The values of these variables are getting set inside these methods. Now, the problem is these variables are sharing the values among different unit test cases. Is there a way to clear all global variables before any test case ran?</p>
",https://stackoverflow.com/questions/47084485/making-tests-independent-in-node-js-tape,"['node.js', 'unit-testing', 'node.js-tape']",66,FALSE,1,0
Why does Jasmine not find my specs?,"<p>I set up the basic example (Chapter1) from Javascript Unit testing and it works, e.g.<a href=""https://i.stack.imgur.com/8eNE5.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/8eNE5.png"" alt=""enter image description here""></a></p>

<p>Why, when I set up a new directory for chapter 2 in what seems to be the same way but with my own spec do I get no specs being run:</p>

<p><a href=""https://i.stack.imgur.com/byIkh.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/byIkh.png"" alt=""enter image description here""></a></p>

<p>My runner file has:</p>

<pre><code>&lt;script type=""text/javascript"" src=""src/SimpleMath.js""&gt;&lt;/script&gt;
&lt;script type=""text/javascript"" src=""spec/SimpleMathSpec.js""&gt;&lt;/script&gt;
</code></pre>

<p>My Spec file is </p>

<pre><code>spec/SimpleMathSpec.js 
</code></pre>

<p>and my source file is </p>

<pre><code>src/SimpleMath.js
</code></pre>

<p>They both do exist:</p>

<pre><code>$ ls src/SimpleMath.js 
src/SimpleMath.js
10:56:21 durrantm U2017 /home/durrantm/Dropbox/_/jasmine_2017/Chapter2 
$ ls spec/SimpleMathSpec.js 
spec/SimpleMathSpec.js
</code></pre>

<p>Network Tab shows them being found ok - though not sure why Zero size ???
<a href=""https://i.stack.imgur.com/mZiKS.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/mZiKS.png"" alt=""enter image description here""></a></p>

<p>I can even see that the file was loaded:
<a href=""https://i.stack.imgur.com/PGVQI.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/PGVQI.png"" alt=""enter image description here""></a></p>

<p>Contents:</p>

<pre><code>spec/SimpleMathSpec.js:

describe(""SimpleMath"", function() {
  var simpleMath;

  beforeEach(function() {
    simpleMath = new SimpleMath();
  }); 

  it(""should calculate a factorial for a positive number"", function() {
    result=simpleMath.getFactorial(3);
    expect(result).toEqual(6);
  }); 

  it(""should calculate a factorial for 0 - which will be zero"", function() {
    result=simpleMath.getFactorial(0);
    expect(result).toEqual(0);
  }); 

  it(""should calculate a factorial for -3 - which will raise an error"", function() {
    result=simpleMath.getFactorial(-3);
    expect(result).toThrow Error;
  }); 

});

src/SimpleMath.js:

SimpleMath = function() {}; 
SimpleMath.prototype.getFactorial = function(number) {
  if (number &lt; 0) {
    throw new Error(""Can't be less than zero"");
  }
  else if (number == 1 || number == 0) {
    return 1;
  }
  else {
    return number * this.getFactorial(number-1);
  }
}
SimpleMath.prototype.signum = function(number) {
  if (number &gt; 0) {
    return 1;
  } else if (number == 0) {
  return 0;
  } else {
    return -1; 
  }
}
SimpleMath.prototype.average = function(number1, number2) {
  return (number1 + number2) / 2;
}
</code></pre>
",https://stackoverflow.com/questions/44051535/why-does-jasmine-not-find-my-specs,"['javascript', 'jasmine']",392,FALSE,0,1
Ecto changesets and GenServers using TDD,"<p>I'm testing a <code>GenServer</code> by <a href=""https://stackoverflow.com/a/33028216/1693831"">unit testing the <code>handle_{call,cast,info}</code> callbacks</a>. One of my <strong>doctest</strong>s is as follows:</p>



<pre><code>@doc """"""                                                                                             
  Call the GenServer to retrieve the initial workout                                                   

  ## Examples                                                                                          
  iex&gt; :rand.seed(:exsplus, {101, 102, 103})                                                           
  iex&gt; Pullapi.GenServerWorker.handle_call({:initial_workout, 5}, nil, %{})                         
  {:reply,                                                                                             
  {:ok,                                                                                                
  [%{""Action"" =&gt; ""Pullups"", ""SequenceNo"" =&gt; 0, ""Units"" =&gt; ""1""},                                        
  %{""Action"" =&gt; ""Rest"", ""SequenceNo"" =&gt; 1, ""Units"" =&gt; ""60""},                                           
  %{""Action"" =&gt; ""Pullups"", ""SequenceNo"" =&gt; 2, ""Units"" =&gt; ""3""},                                         
  %{""Action"" =&gt; ""Rest"", ""SequenceNo"" =&gt; 3, ""Units"" =&gt; ""60""},                                           
  %{""Action"" =&gt; ""Pullups"", ""SequenceNo"" =&gt; 4, ""Units"" =&gt; ""3""},                                         
  %{""Action"" =&gt; ""Rest"", ""SequenceNo"" =&gt; 5, ""Units"" =&gt; ""70""}]}, %{}}                                    
  """"""
</code></pre>

<p>I want to insert the reply to the DB under a specified schema which has been realised in a migration. However I have no solid idea as to how I would write a unit test for this - since the DB write is essentially a side effect, the above <strong>doctest</strong> would stay the same.</p>

<p>Is it enough to somehow <strong>doctest</strong> the <code>changeset</code> independently, then place the <code>Repo.insert</code> into the <code>GenServer</code> given a test pass?</p>
",https://stackoverflow.com/questions/46639901/ecto-changesets-and-genservers-using-tdd,"['tdd', 'elixir', 'ecto', 'changeset', 'gen-server']",203,TRUE,0,1
Dependency Injection in WindowsForm Application C#,"<p>i am currently creating the structure of a windows form application. I encountered the NULL REFERENCE Error when implementing dependency injection. I was using this kind of approach in my MVC applications for easy unit testing but cant figure it out how to implement it here in windows form application.</p>

<p>This is the partial class of the Main form:</p>

<pre><code>public partial class pws : Form
{
    private IInterfaceTasks _tasks { get; set; }
    public pws(IInterfaceTasks tasks)
    {
        InitializeComponent();
        _tasks = tasks;
    }

    private void cmdSave_Click(object sender, EventArgs e)
    {

        IEntities.AssignmentEntityRequest request = new IEntities.AssignmentEntityRequest();

        &lt;code mapping here&gt;

        _tasks.CreateAssignments(request); --&gt; _tasks here is null
    }
}
</code></pre>

<p>Here is the class that is inheriting the IServiceTasks interface</p>

<pre><code>public class CreateAssignmentsInterface : IInterfaceTasks
{
    private Service.IServiceTasks _task;

    public CreateAssignmentsInterface(Service.IServiceTasks task)
    {
        _task = task;
    }

    public bool CreateAssignments(IEntities.AssignmentEntityRequest request)
    {
        Helpers.Helpers mapper = new Helpers.Helpers();
        var assignmentRequest = new SEntities.AssignmentEntityRequest();
        assignmentRequest = mapper.MapInterfacetoServiceRequest(request);

        _task.CreateAssignment(); --&gt; _task here is null
        return true;
    }
}
</code></pre>

<p>Here is my IServiceTasks Interface</p>

<pre><code>public interface IServiceTasks
{
    bool CreateAssignment();
}
</code></pre>

<p>And for the IInterfaceTasks Interface</p>

<pre><code>public interface IInterfaceTasks
{
    bool CreateAssignments(IEntities.AssignmentEntityRequest request);
}
</code></pre>

<p>Can somebody help me how can I implement this right?</p>

<p>update:
pws is being called here</p>

<pre><code>[STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        IInterfaceTasks tasks = new pws();
        Application.Run(new pws(tasks));
    }
</code></pre>
",https://stackoverflow.com/questions/42256075/dependency-injection-in-windowsform-application-c,"['c#', 'winforms', 'dependency-injection', 'interface']",14640,TRUE,3,1
java spring boot test POST REST with object in content,"<p>I'm tryin to unit test a post rest service, this service takes an object (not a json) as content. The result is that I can't test it, the MockMvc object expects some json content.</p>

<p>Part of the controller, where Dsd is an internal class of the application :</p>

<pre><code>@PostMapping(path=""dsd"")
@ApiOperation(value = ""Sends Dsd  data"",response = Dsd.class)
public Dsd requestPostDsd (
        @ApiParam(""DSD data"")
        @Valid @RequestBody Dsd dsd,
        HttpServletResponse response
) throws IOException, ParseException {
    if (dsd.getId() != null) {
        // do something
    } else {
        response.sendError(HttpStatus.BAD_REQUEST.value(), ""the id doesn't exist"");
    }
    return dsd;
}
</code></pre>

<p>In the unit testing code, I create a MockMvc object but the perform().content method expects a string json content, I can't pass my Dsd object instead.</p>

<p>How can test this POST api ?</p>

<p>Edit : part of the test code :</p>

<pre><code> @Test
public void postDsdTest() throws Exception {

    Dsd dsd = new Dsd();

    this.mvc.perform(post(""/services/latest/validation/dsd"")
            .header(""Origin"", HTTP_HEADER_ORIGIN)
            .header(""Accept"", ""application/json"")
            .content(dsd)
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(header().string(""Access-Control-Allow-Origin"", HTTP_HEADER_ORIGIN))
            .andExpect(status().isOk())
            .andDo(MockMvcResultHandlers.print());

}
</code></pre>
",https://stackoverflow.com/questions/47508531/java-spring-boot-test-post-rest-with-object-in-content,"['java', 'spring-boot', 'junit']",4131,TRUE,0,1
Angular 2 - How to access a service dependency in a unit test,"<p>I have the following Angular service which depends on <code>AngularFire</code>:</p>

<pre class=""lang-ts prettyprint-override""><code>@Injectable()
export class FirebaseService {

  constructor(private af: AngularFire) { }

  // more code here
}
</code></pre>

<p>I'm unit testing this service with the following setup:</p>

<pre class=""lang-ts prettyprint-override""><code>TestBed.configureTestingModule({
  imports: [ AngularFireModule.initializeApp(MY_FIREBASE_CONFIG) ],
  providers: [ FirebaseService ]
});
const firebaseService = TestBed.get(FirebaseService);
</code></pre>

<p>I can then do assertions on the service's methods such as:</p>

<pre class=""lang-ts prettyprint-override""><code>// This works great
expect(firebaseService.callFoo()).toEqual('foo');
</code></pre>

<p>My question is how do I get a hold of the <code>AngularFire</code> instance that's injected in the constructor of <code>FirebaseService</code>? (<code>TestBed.get(AngularFire)</code> does not work; also, I don't have a component so I can't use the component's injector)</p>

<p>Site note: I know I should mock the backend for unit tests but it's not the point of the question here.</p>
",https://stackoverflow.com/questions/42718763/angular-2-how-to-access-a-service-dependency-in-a-unit-test,"['unit-testing', 'angular', 'angular2-services']",723,FALSE,0,0
"Unit test ASP.NET, Open a file in web api","<p>I have a Web api with a function like this:</p>

<pre><code>    [HttpPost]
    public IHttpActionResult PostData([FromBody] JObject new_data)
    {
        //Some code here
        var fullPath = System.Web.Hosting.HostingEnvironment.MapPath(@""~/App_Data/data.txt"");

        System.IO.File.WriteAllText(fullPath, new_data.ToString());

        return Ok();
    }
</code></pre>

<p>Then I am testing this api like this:</p>

<pre><code>    [TestMethod]
    public void TestPostData()
    {
        // Arrange
        JObject data = getSampleData();
        var controller = new MyController();
        //Act
        IHttpActionResult result = controller.PostData(data);

        //Assert
        Assert.IsInstanceOfType(result, typeof(OkNegotiatedContentResult&lt;JObject&gt;));      
    }
</code></pre>

<p>Here I get error at the line below:</p>

<pre><code>    System.IO.File.WriteAllText(fullPath, new_data.ToString());
</code></pre>

<p>And the error says: 
Message: Test method NetWorth.Tests.UnitTest1.TestPostData threw exception: 
System.ArgumentNullException: Value cannot be null.
Parameter name: path</p>

<p>Can someone help please? I'm very new to ASP and c# and unit testing! Any suggestions would help a lot.</p>

<p>I should say that the api works perfect when I run it and this problem is just at the time of testing.</p>
",https://stackoverflow.com/questions/47321953/unit-test-asp-net-open-a-file-in-web-api,"['c#', 'asp.net', 'unit-testing']",122,TRUE,0,1
How do I remove AfterMap from Automapper Profiles,"<p>I have a profile class where I am using AfterMap() method. My profile class has two constructor dependencies. Problem is that while I am unit testing I am mocking these dependencies but also I require the actual objects when I am doing integration testing. Since im using xUnit2, everything runs in parallel, so I have no control. So that is why I want to remove all the code from aftermap. Can someone tell me the approach for this ?
I am using structuremap as my IOC container.</p>
",https://stackoverflow.com/questions/46639737/how-do-i-remove-aftermap-from-automapper-profiles,"['.net', 'automapper', 'structuremap3', 'xunit2']",89,FALSE,0,0
Importing NuGet references through a local project reference,"<p>Let's say I have a ""main"" C# project that uses NuGet to manage its third-party dependencies. </p>

<p>Now let's say I create a unit-testing project alongside the main project that includes the main project as a reference.</p>

<p>Unfortunately, it seems that I need to re-add dependencies that are included via nuget in the main project in order to use them to write code for the unit tests in the unit test project. </p>

<p>My question is: Is there a way to automatically include the ""main"" nuget references in the testing project?</p>
",https://stackoverflow.com/questions/44706516/importing-nuget-references-through-a-local-project-reference,"['c#', 'visual-studio', 'nuget', 'projects-and-solutions']",2595,TRUE,3,1
.NET Core testing output format,"<p>In order to integrate unit testing into my <a href=""https://en.wikipedia.org/wiki/Continuous_integration"" rel=""nofollow noreferrer"">CI</a>/<a href=""https://en.wikipedia.org/wiki/Continuous_delivery"" rel=""nofollow noreferrer"">CD</a> build pipeline, I need to run tests via the command line and output them in a format that Jenkins can read.</p>

<p>Recently, there was a significant change to .NET Core where <code>project.json</code> and <code>.xproj</code> files have been converted into the <code>.csproj</code> format. This change broke my previous integration with NUnit&nbsp;3.</p>

<p>As of writing, NUnit does not support .NET Core v1.0.3.</p>

<p>Is there a <code>dotnet test</code> setting that will enable me to output the results in a Jenkins readable format (e.g. xUnit, NUnit, or JUnit)?</p>
",https://stackoverflow.com/questions/43661404/net-core-testing-output-format,"['.net', 'jenkins', 'continuous-integration', 'nunit', '.net-core']",4686,TRUE,3,2
Rejecting a $q.defer causing unhandled rejection error to be thrown,"<p>I have recently updated from 1.5 to 1.6.3 and have code where I am using deferred promise objects using the $q service which is now throwing the following errors in my unit test runs:</p>

<pre><code>Possibly unhandled rejection: undefined thrown
</code></pre>

<p>Here is the typical structure of a function I have in my code that uses a deferred promise:</p>

<pre><code>public someFunction = () =&gt; {
    const deferred = this.$q.defer();
    if (someConditionIsTrue) {
        this.myService.getThings().then((response) =&gt; {
            deferred.resolve(response);
        });
    } else {
        deferred.reject();
    }
    return deferred.promise;
};
</code></pre>

<p>When unit testing the else condition I get this error thrown (using karma\jasmine\phantomJS)</p>

<p>I already have the following configured also:</p>

<pre><code>config(['$qProvider', ($qProvider) =&gt; {
        $qProvider.errorOnUnhandledRejections(false);
      }])
</code></pre>

<p>Can someone point me in the right direction please?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/42760713/rejecting-a-q-defer-causing-unhandled-rejection-error-to-be-thrown,['angularjs'],1254,FALSE,0,1
how to write dependent test cases in protractor/jasmine?,"<p>I am using protractor and jasmine as a unit testing tool for my project. I want to write dependent test cases for eg. If test case 1 fails do not execute test case 2 instead jump on test case 3 directly. Is it possible in protractor ? If yes then how ? </p>

<pre><code> conf.js

    suites: {
            network: 'consumerIndex.js',
            platform: 'adminIndex.js'

    }
</code></pre>

<p>adminIndex.js</p>

<pre><code>    describe('Protractor Demo CTL App', function() {

            require('./adminPage.js');
            require('./addSeatPage.js');
            require('./groupusers.js');
            require('./invoiceSettings.js');

    }); 
</code></pre>

<p>addSeatPage.js</p>

<pre><code>    it('case 1 ', function() {
            browser.driver.sleep(10000);    
            addSeat.productLink;
            expect(browser.getLocationAbsUrl()).toMatch(""/seatSummarydsds"");    
    });
    it('case 2 ', function() {

            browser.driver.sleep(10000);    
            element(by.css('[ng-click=""goToBuyProducts()""]')).click();
            expect(browser.getLocationAbsUrl()).toMatch(""/addSeat"");

    });

    it('case 3', function() {
            browser.driver.sleep(10000);    
            addSeat.addToCart(browser.params.testData.datetimeTxt);
            expect(element(by.css('.errLabel')).isDisplayed()).toBe(true);
    });
</code></pre>

<p>I want to jump to case 3 if case 1 fails. Also is there any solution for jumping to next spec file i.e. groupusers.js directly if any of the case in addSeatPage.js fails ?</p>
",https://stackoverflow.com/questions/42340572/how-to-write-dependent-test-cases-in-protractor-jasmine,"['angularjs', 'jasmine', 'protractor']",1704,TRUE,0,1
Unit test result does not show on SonarQube Dashboard for nodejs,"<p><strong>SonarQube Version</strong> : 6.0.0
<strong>SonarJS</strong> : 2.17.0.3154</p>

<p><strong>Issue</strong></p>

<p>The main aim is to display coverage report and the unit test result in SonarQube dashboard. Though I am able to get the coverage report but not able to get the unit test result in SonarQube dashboard .
I have been using the mocha for unit testing and istanbul nyc for code coverage. The report generated by mocha is in xml format using the package mocha-sonar-reporter and the coverage report is in lcov format .</p>

<p><a href=""https://i.stack.imgur.com/tpnTq.png"" rel=""nofollow noreferrer"">sonarqube dashboard</a></p>

<p><strong>Sonar.Property File</strong></p>

<pre><code>sonar.projectKey=unittest
sonar.projectName=unittest 
sonar.projectVersion=1.0.0
sonar.sources=src/
sonar.tests=test/
sonar.language=js
sonar.sourceEncoding=UTF-8
sonar.javascript.jstestdriver.reportsPath=/home/jenkinsbot/workspace/devops_stuffs/reports
sonar.javascript.lcov.reportPath=/home/jenkinsbot/workspace/devops_stuffs/reports/lcov.info
</code></pre>

<p><strong>SonarQube log</strong> :</p>

<pre><code>_[Pipeline] wrap
Injecting SonarQube environment variables using the configuration: Sonar(dk.147)
[Pipeline] {
[Pipeline] sh
[e_feature_COS-239-unit-test-P23YKERWYLNSD6K3ISKUHA5NSJTRN6K7DRJGKI5QLG6LTD3HHOPA] Running shell script

/home/jenkinsbot/sonar-scanner-2.9.0.670/bin/sonar-scanner
INFO: Scanner configuration file: /home/jenkinsbot/sonar-scanner-2.9.0.670/conf/sonar-scanner.properties
INFO: Project root configuration file: /home/jenkinsbot/workspace//sonar-project.properties
INFO: SonarQube Scanner 2.9.0.670
INFO: Java 1.8.0_131 Oracle Corporation (64-bit)
INFO: Linux 4.4.0-92-generic amd64
INFO: User cache: /home/jenkinsbot/.sonar/cache
INFO: Load global repositories
INFO: Load global repositories (done) | time=94ms
INFO: User cache: /home/jenkinsbot/.sonar/cache
INFO: Load plugins index
INFO: Load plugins index (done) | time=4ms
INFO: SonarQube server 6.0
INFO: Default locale: ""en_US"", source code encoding: ""UTF-8""
INFO: Process project properties
INFO: Load project repositories
INFO: Load project repositories (done) | time=100ms
INFO: Load quality profiles
INFO: Load quality profiles (done) | time=17ms
INFO: Load active rules
INFO: Load active rules (done) | time=231ms
INFO: Publish mode
INFO: ------------- Scan cosmicunittest
INFO: Language is forced to js
INFO: Load server rules
INFO: Load server rules (done) | time=71ms
INFO: Base dir: /home/jenkinsbot/workspace/
INFO: Working dir: /home/jenkinsbot/workspace/eP23YKERWYLNSD6K3ISKUHA5NSJTRN6K7DRJGKI5QLG6LTD3HHOPA/.scannerwork
INFO: Source paths: src
INFO: Test paths: test
INFO: Source encoding: UTF-8, default locale: en_US
INFO: Index files
INFO: 152 files indexed
INFO: Quality profile for js: LogPoint Way
INFO: Sensor Lines Sensor
INFO: Sensor Lines Sensor (done) | time=33ms
INFO: Sensor SCM Sensor
INFO: Sensor SCM Sensor (done) | time=20ms
INFO: Sensor JavaScript Squid Sensor
INFO: 138 source files to be analyzed
INFO: Unit Test Coverage Sensor is started
INFO: 138/138 source files have been analyzed
INFO: Analysing [/home/jenkinsbot/workspace/reports/lcov.info]
INFO: Integration Test Coverage Sensor is started
INFO: Overall Coverage Sensor is started
INFO: Analysing [/home/jenkinsbot/workspace/reports/lcov.info]
INFO: Sensor JavaScript Squid Sensor (done) | time=4852ms
INFO: Sensor XmlFileSensor
INFO: Sensor XmlFileSensor (done) | time=1ms
INFO: Sensor Zero Coverage Sensor
INFO: Sensor Zero Coverage Sensor (done) | time=76ms
INFO: Sensor Code Colorizer Sensor
INFO: Sensor Code Colorizer Sensor (done) | time=3ms
INFO: Sensor CPD Block Indexer
INFO: DefaultCpdBlockIndexer is used for js
INFO: Sensor CPD Block Indexer (done) | time=1ms
INFO: Calculating CPD for 129 files
INFO: CPD calculation finished
INFO: Analysis report generated in 222ms, dir size=903 KB
INFO: Analysis reports compressed in 300ms, zip size=512 KB
INFO: Analysis report uploaded in 24ms
INFO: ANALYSIS SUCCESSFUL, you can browse http://test/dashboard/index/unittest
INFO: Note that you will be able to access the updated dashboard once the server has processed the submitted analysis report
INFO: More about the report processing at test
INFO: Task total time: 7.649 s
INFO: ------------------------------------------------------------------------
INFO: EXECUTION SUCCESS
INFO: ------------------------------------------------------------------------
INFO: Total time: 8.784s
INFO: Final Memory: 61M/551M
INFO: ------------------------------------------------------------------------
[Pipeline] }
[Pipeline] // wrap
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // node
[Pipeline] }
[Pipeline] // stage
[Pipeline] End of Pipeline
Finished: SUCCESS_
</code></pre>
",https://stackoverflow.com/questions/46314424/unit-test-result-does-not-show-on-sonarqube-dashboard-for-nodejs,"['node.js', 'sonarqube', 'sonar-runner', 'sonarjs']",3207,TRUE,0,1
How to run tests written using jasmine for typescript (angular 2)?,"<p>I have written unit tests using jasmine framework for angular 2 typescript application. I have not generated project using angular-cli. I installed jasmine and wrote the unit testing for angular component. How do I run this <strong>spec.ts</strong> ? I followed this <a href=""https://github.com/jasmine/jasmine-npm"" rel=""nofollow noreferrer"">https://github.com/jasmine/jasmine-npm</a> and try to configure my project to run the tests. But this works only for spec.js test files. I tried with karma and did not work. How to setup the test environment to run tests written for typescript using jasmine?</p>
",https://stackoverflow.com/questions/44503014/how-to-run-tests-written-using-jasmine-for-typescript-angular-2,"['angular', 'unit-testing', 'typescript', 'jasmine', 'angular2-testing']",1534,TRUE,0,1
Cannot use JUnitCore,"<p>I'm pretty new to java and unit testing and I'm experimenting with junit and so I watch tutorials and read blogs about it. From time to time there are things like PrimerClasses and TestSuites and everyone seems to have no problem using these kind of functionalities.</p>

<p>So when I try to use these too, my project cannot find JUnitCore or even the runner, where all that pretty stuff comes from and up to now I was not able to work out what the reason might be.</p>
",https://stackoverflow.com/questions/43472898/cannot-use-junitcore,"['java', 'junit']",546,TRUE,-1,1
Apply GetProperties to interface only,"<p>Please see the code below:</p>

<pre><code>public static class AssertEx
{
    public static void PropertyValuesAreEquals(object actual, object expected)
    {
        PropertyInfo[] properties = expected.GetType().GetProperties();
        foreach (PropertyInfo property in properties)
        {
            object expectedValue = property.GetValue(expected, null);
            object actualValue = property.GetValue(actual, null);

            if (actualValue is IList)
                AssertListsAreEquals(property, (IList)actualValue, (IList)expectedValue);
            else if (!Equals(expectedValue, actualValue))
                Assert.Fail(""Property {0}.{1} does not match. Expected: {2} but was: {3}"", property.DeclaringType.Name, property.Name, expectedValue, actualValue);
        }
    }

    private static void AssertListsAreEquals(PropertyInfo property, IList actualList, IList expectedList)
    {
        if (actualList.Count != expectedList.Count)
            Assert.Fail(""Property {0}.{1} does not match. Expected IList containing {2} elements but was IList containing {3} elements"", property.PropertyType.Name, property.Name, expectedList.Count, actualList.Count);

        for (int i = 0; i &lt; actualList.Count; i++)
            if (!Equals(actualList[i], expectedList[i]))
                Assert.Fail(""Property {0}.{1} does not match. Expected IList with element {1} equals to {2} but was IList with element {1} equals to {3}"", property.PropertyType.Name, property.Name, expectedList[i], actualList[i]);
    }
}
</code></pre>

<p>I took this from here: <a href=""https://stackoverflow.com/questions/318210/compare-equality-between-two-objects-in-nunit"">Compare equality between two objects in NUnit</a> (Juanmas' answer)</p>

<p>Say I have an interface like this:</p>

<pre><code>public interface IView
{
    decimal ID { get; set; }
    decimal Name { get; set; }
}
</code></pre>

<p>I then have two views like this:</p>

<pre><code>IView view = new FormMain();
IView view2 = new FormMain();
</code></pre>

<p>view and view2 are then given properties.</p>

<p>I then want to compare the interfaces so I do this:</p>

<pre><code>Assert.AreEqual(Helper.PropertyValuesAreEquals(view, view2), true);
</code></pre>

<p>However, this produces an exception: </p>

<blockquote>
  <p>""Property Get method was not found."".  </p>
</blockquote>

<p>How can I ensure this function only gets properties for the properties in my interface?</p>

<p>Should I even be unit testing a view like this?</p>
",https://stackoverflow.com/questions/44200160/apply-getproperties-to-interface-only,"['c#', 'unit-testing']",75,TRUE,0,3
Why use OWIN TestServer?,"<p>This article shows how to host an entire web API stack in memory for testing using OWIN:</p>

<p><a href=""http://www.davidwhitney.co.uk/Blog/2015/01/07/testing-an-asp-net-webapi-app-in-memory/"" rel=""nofollow noreferrer"">http://www.davidwhitney.co.uk/Blog/2015/01/07/testing-an-asp-net-webapi-app-in-memory/</a></p>

<p>Whereas this article shows using the OWIN TestServer to unit test controllers:</p>

<p><a href=""https://blog.jcorioland.io/archives/2014/04/01/using-owin-to-test-your-web-api-controllers.html"" rel=""nofollow noreferrer"">https://blog.jcorioland.io/archives/2014/04/01/using-owin-to-test-your-web-api-controllers.html</a></p>

<p>The difference I see is between the use of <code>TestServer.Create</code> and <code>WebApp.Start&lt;Startup&gt;</code></p>

<p>What is the key difference and why would you choose one over the other?</p>

<p>Is it simply the difference between unit testing controller methods as web api calls versus end-to-end integration testing in memory?</p>
",https://stackoverflow.com/questions/46088291/why-use-owin-testserver,"['testing', 'asp.net-web-api', 'owin-middleware']",4099,TRUE,8,1
Using minitest methods in capybara ruby implementation?,"<p>Im very new at ruby coding and I always use capybara native methods.
Now, I need to use some assert methods for unit testing only available in rspec matchers or minitest. Rspec was discarded because some gem trouble in system machine...so.....minitest is the choice.</p>

<p>My question is:</p>

<p>Can only access to minitest methods using class like this? (see in documentation)</p>

<pre><code>require ""minitest/autorun""

class myTest &lt; Minitest::Test
</code></pre>

<p>If I already have my class like this:   </p>

<pre><code>class myTest &lt; BasePageExample

def method1()
  ""needed assert_equal(.............)""
end
end
</code></pre>

<p>How can I import minitest for my existant class and use assert_equal method???</p>

<p>Thanks!!!</p>
",https://stackoverflow.com/questions/41998508/using-minitest-methods-in-capybara-ruby-implementation,"['ruby', 'testing', 'rspec', 'capybara']",93,FALSE,0,0
How to test a GraphQl API?,"<p>I need to write a functional test suite (that will test a GraphQl API). The test suite will be in a separate repo and container from the API. </p>

<p>One approach I thought of would be to use a BDD framework within the test suite. The suite would run all the BDD tests after receiving a HTTP request.   </p>

<p>I was considering using Cucumber.js as the BDD framework. I know there is <code>npm test</code>. I am not sure how I will execute the tests. It feels a bit awkward to use a unit testing framework in this way. Does this approach make sense?  </p>

<p>What tooling exists to do something like this? I am open to consider various languages and tools. </p>
",https://stackoverflow.com/questions/42841902/how-to-test-a-graphql-api,"['testing', 'functional-testing', 'graphql']",17065,TRUE,18,2
How to Unit Test a GlassController Action which Returns a View Taking a Model,"<p>I'm a sitecore developer and I want to create a sample sitecore helix unit testing project for testing out our ""HomeBottomContentController"" controller:</p>

<pre><code>    public class HomeBottomContentController : GlassController
    {
        private readonly ISitecoreContext _iSitecoreContext;
        public HomeBottomContentController(ISitecoreContext iSitecoreContext)
        {
            _iSitecoreContext = iSitecoreContext;
        }

        public override ActionResult Index()
        {
            var model = _iSitecoreContext.GetCurrentItem&lt;Home_Control&gt;();
            return View(""~/Views/HomeBottomContent/HomeBottomContent.cshtml"", model);
        }
    }
</code></pre>

<p>I have created a WTW.Feature.HomeBottomContent.Tests project, for the purpose of testing this entire component using helix unit testing.  In it I have a UnitTest1.cs file with following:</p>

<pre><code>namespace WTW.Feature.HomeBottomContent.Tests
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void Test_ISitecoreContextInsertion()
        {
            var iSitecoreContext = Mock.Of&lt;Glass.Mapper.Sc.ISitecoreContext&gt;();
            HomeBottomContentController controllerUnderTest = new HomeBottomContentController(iSitecoreContext);
            var result = controllerUnderTest.Index() as ViewResult;
            Assert.IsNotNull(result);
        }
    }
}
</code></pre>

<p>This test does pass, meaning ""result"" is NOT null; however, the problem is when I step into the Index() code, I see that the ""model"" variable is NULL when we do</p>

<pre><code>    var model = _iSitecoreContext.GetCurrentItem&lt;Home_Control&gt;();
</code></pre>

<p>My question is, how exactly do I change this code to make sure that the ""model"" in that line does not become null?  How do I ""mock"" an item in unit test code for the _iSitecoreContext so that it has a ""Home_Control"" template with legit values for its fields?  Would that even be the right approach?  Most online sources I've found do not have a similar scenario, I'm looking for the shortest code possible.</p>

<p>Another question I had is, how can I test the below Index() method in my [TestMethod], given that the SitecoreContext is declared <em>inside</em> the Index() method, rather than received in the HomeBottomContentController constructor like above?  Is there a way to do that from the [TestMethod], or we have to send in the SitecoreContext into the HomeBottomContentController constructor or into the Index() method as a parameter?</p>

<pre><code>public override ActionResult Index()
{
    var context = new SitecoreContext();
    var model = context.GetCurrentItem&lt;Home_Control&gt;();
    return View(""~/Views/HomeBottomContent/HomeBottomContent.cshtml"", model);
}
</code></pre>
",https://stackoverflow.com/questions/46186187/how-to-unit-test-a-glasscontroller-action-which-returns-a-view-taking-a-model,"['c#', 'moq', 'sitecore8', 'sitecore-mvc', 'glass-mapper']",455,TRUE,3,2
Angular 4 Unit test error - Failed to execute &#39;send&#39; on &#39;XMLHttpRequest&#39;: Failed to load &#39;ng:///DynamicTestModule/LoginComponent.ngfactory.js&#39;,"<p>I am writing some unit tests for my component and i am getting this cryptic error message. I found a similar question at <a href=""https://stackoverflow.com/questions/44254758/angular-2-unit-testing-getting-error-failed-to-load-ng-dynamictestmodule-m"">Angular 2 unit testing - getting error Failed to load &#39;ng:///DynamicTestModule/module.ngfactory.js&#39;</a> but the answers did not help me solve my issue. I am angular 4.3.2</p>

<p>Here's the component i am writing the test for:</p>

<pre><code>import {Component} from '@angular/core';
import {Router} from '@angular/router';

import {NotificationService} from '../common/notification/notification.service';
import {SessionService} from '../common/session/session.service';
import {Login} from './login.model';

@Component({
             selector: 'cc-login-form',
             templateUrl: './login.component.html',
             styleUrls: ['./login.component.scss'],
           })
export class LoginComponent {
  model: Login = new Login('', '');

  constructor(private sessionService: SessionService,
              private router: Router,
              private notificationService: NotificationService) {
  }

  onSubmit() {
    this.sessionService
        .login(this.model.email, this.model.password)
        .subscribe(
          sessionInfo =&gt; {
            this.notificationService.showSuccess('notification.successfully.logged.in');
            this.router.navigate([`/cc/list`]);
          },
          error =&gt; this.notificationService.showError('notification.invalid.login')
        );
  }
}
</code></pre>

<p>And here is the test file:</p>

<pre><code>import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {FormsModule} from '@angular/forms';
import {Router} from '@angular/router';
import {TranslateModule, TranslateService} from '@ngx-translate/core';
import {NotificationService} from '../common/notification/notification.service';
import {NotificationServiceStub} from '../common/notification/tests/NotificationServiceStub';
import {SessionService} from '../common/session/session.service';
import {SessionServiceStub} from '../common/session/tests/SessionServiceStub';
import {RouterStub} from '../common/tests/RouterStub';
import {TranslateServiceStub} from '../common/translate/tests/TranslateServiceStub';

import {LoginComponent} from './login.component';

describe('LoginComponent', () =&gt; {
  let component: LoginComponent;
  let fixture: ComponentFixture&lt;LoginComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
                                     imports: [
                                       FormsModule,
                                       TranslateModule
                                     ],
                                     declarations: [LoginComponent],
                                     providers: [
                                       {provide: SessionService, useClass: SessionServiceStub},
                                       {provide: Router, useClass: RouterStub},
                                       {provide: NotificationService, useClass: NotificationServiceStub},
                                       {provide: TranslateService, useClass: TranslateServiceStub},
                                     ]
                                   })
           .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be created', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p>When running the test i get the following on chrome console: </p>

<pre><code>zone.js:2642 XMLHttpRequest cannot load ng:///DynamicTestModule/LoginComponent.ngfactory.js. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
(anonymous) @ zone.js:2642
zone.js:195 Uncaught DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'ng:///DynamicTestModule/LoginComponent.ngfactory.js'.
    at http://localhost:9876/_karma_webpack_/webpack:/Users/pedrompg/Documents/quandoo/fe/chains-center/~/zone.js/dist/zone.js:2642:1
    at XMLHttpRequest.proto.(anonymous function) [as send] (
</code></pre>

<p>Any can help me with that?</p>

<p>EDIT - 1
Here's the services/stubs implementation</p>

<p><strong>SessionServiceStub</strong></p>

<pre><code>export class SessionServiceStub implements ISessionService {
  login(login: string, password: string): Observable&lt;any&gt; {
    return Observable.of({merchantId: 123});
  }

  logout(): Observable&lt;any&gt; {
    throw new Error('Method not implemented.');
  }

  validateSessionToken(): Observable&lt;any&gt; {
    throw new Error('Method not implemented.');
  }
}
</code></pre>

<p><strong>SessionService</strong></p>

<pre><code>@Injectable()
export class SessionService implements ISessionService {

  constructor(private http: CcHttpClient, private router: Router, private localSessionService: LocalSessionService) {
  }

  login(login: string, password: string): Observable&lt;any&gt; {
    return this.http.post(`api/sessions`, {login: login, password: password}).map((res: Object) =&gt; {
      this.localSessionService.createSession(res);
      return res;
    });
  }
}
</code></pre>

<p><strong>RouterStub</strong></p>

<pre><code>export class RouterStub {
  navigate(commands: any[], extras?: NavigationExtras): Promise&lt;boolean&gt; {
    return Promise.resolve(true);
  };
}
</code></pre>

<p><strong>TranslationServiceStub</strong></p>

<pre><code>export class TranslateServiceStub {
  instant(key: string | Array&lt;string&gt;, interpolateParams?: Object): string | any {
    return 'translation';
  };
}
</code></pre>

<p><strong>NotificationServiceStub</strong></p>

<pre><code>export class NotificationServiceStub implements INotificationService {
  showToast(type, text, title, defaultTitle): Promise&lt;Toast&gt; {
    return Promise.resolve(null);
  }

  showSuccess(msg, title?): Promise&lt;Toast&gt; {
    return Promise.resolve(null);
  }

  showError(msg, title?): Promise&lt;Toast&gt; {
    return Promise.resolve(null);
  }
}
</code></pre>

<p><strong>EDIT 2</strong>
Changing my TestBed config to the following removed the error but brought a new one:</p>

<pre><code>beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
                                     imports: [
                                       FormsModule,
                                       HttpClientModule,
                                       TranslateModule.forRoot({
                                                                 loader: {
                                                                   provide: TranslateLoader,
                                                                   useFactory: HttpTranslateLoaderFactory,
                                                                   deps: [HttpClient]
                                                                 }
                                                               })
                                     ],
                                     declarations: [LoginComponent],
                                     providers: [
                                       {provide: SessionService, useClass: SessionServiceStub},
                                       {provide: Router, useClass: RouterStub},
                                       {provide: NotificationService, useClass: NotificationServiceStub},
                                     ]
                                   })
           .compileComponents();
  }));
</code></pre>

<p>Now the error message is </p>

<pre><code>TypeError: Cannot read property 'assertPresent' of undefined
        at resetFakeAsyncZone home/pedrompg/Documents/quandoo/fe/chains-center/~/@angular/core/@angular/core/testing.es5.js:304:1)
        at Object.&lt;anonymous&gt; home/pedrompg/Documents/quandoo/fe/chains-center/~/@angular/core/@angular/core/testing.es5.js:1001:1)
        at ZoneQueueRunner.webpackJsonp.../../../../zone.js/dist/jasmine-patch.js.jasmine.QueueRunner.ZoneQueueRunner.execute home/pedrompg/Documents/quandoo/fe/chains-center/~/zone.js/dist/jasmine-patch.js:132:1)
</code></pre>

<p>Which happens at this function:</p>

<pre><code>function resetFakeAsyncZone() {
    _fakeAsyncTestZoneSpec = null;
    ProxyZoneSpec.assertPresent().resetDelegate(); //ProxyZoneSpec is undefined here for whatever reason
}
</code></pre>
",https://stackoverflow.com/questions/45551214/angular-4-unit-test-error-failed-to-execute-send-on-xmlhttprequest-failed,"['javascript', 'angular', 'unit-testing']",19512,TRUE,23,4
Should I test view&#39;s attributes in unit tests?,"<p>I am wondering what is a proper way to unit test a Django view, for example this one:</p>

<pre><code>class UserListView(LoginRequiredMixin, ListView):

    model = get_user_model()
    template_name = 'users/user_list.html'
    ordering = 'last_name'

    def get_queryset(self):
        self.queryset = self.model.objects.all().annotate(
            full_name=Concat('first_name', Value(' '), 'last_name')
        )
        return super().get_queryset()
</code></pre>

<p>I'm currently unit testing the <code>get_queryset</code> method. This gives me 100% coverage of this view, but should I also test, for example, default ordering in a <strong>unit test</strong>? Or should this be tested in an integration/system test only (e.g. using Selenium or Django's Client)?</p>

<p>On one side, the <code>ordering</code> attribute is part of the view and it influences it's behaviour, on the other side, it's used by a third party code only.</p>
",https://stackoverflow.com/questions/42636982/should-i-test-views-attributes-in-unit-tests,"['python', 'django', 'unit-testing', 'selenium']",260,TRUE,2,1
How to test a Floating Action Button in Ionic2,"<p>I have an Ionic2 project, with the Unit Testing setup based on the <a href=""https://github.com/lathonez/clicker"" rel=""nofollow noreferrer"">clicker</a> repository.
I try to use a Floating Action Button in a component but it throws an exception when running the unit tests. I added a FAB to the plain clickr app to demonstrate the error. It is added to page2.html and you can find it in the <a href=""https://github.com/euleule/clicker/tree/fab-error"" rel=""nofollow noreferrer"">fab-error branch</a>.</p>

<p>When running the tests, the log looks like this.</p>

<pre><code>&gt; Clicker@2.19.0 test /Users/rkause/test/clicker
&gt; ng test

 10% building modules 1/1 modules 0 active16 08 2017 12:15:52.892:WARN [karma]: No captured browser, open http://localhost:9876/
16 08 2017 12:15:52.902:INFO [karma]: Karma v1.7.0 server started at http://0.0.0.0:9876/
16 08 2017 12:15:52.902:INFO [launcher]: Launching browser ChromeNoSandbox with unlimited concurrency
16 08 2017 12:15:52.915:INFO [launcher]: Starting browser Chrome

WARNING in ./~/ionic-angular/util/ng-module-loader.js
54:11-36 Critical dependency: the request of a dependency is an expression

WARNING in ./~/ionic-angular/util/ng-module-loader.js
69:11-36 Critical dependency: the request of a dependency is an expression
16 08 2017 12:16:02.325:WARN [karma]: No captured browser, open http://localhost:9876/
16 08 2017 12:16:02.541:INFO [Chrome 60.0.3112 (Mac OS X 10.11.6)]: Connected on socket djJaMpA7zKcR5c3jAAAA with id 17408513
Chrome 60.0.3112 (Mac OS X 10.11.6) Pages: Page2 should create page2 FAILED
    TypeError: unRegEvent is not a function
        at http://localhost:9876/_karma_webpack_/vendor.bundle.js:41527:13
        at Array.forEach (&lt;anonymous&gt;)
        at UIEventManager.webpackJsonp.../../../../ionic-angular/gestures/ui-event-manager.js.UIEventManager.unlistenAll (http://localhost:9876/_karma_webpack_/vendor.bundle.js:41526:19)
        at UIEventManager.webpackJsonp.../../../../ionic-angular/gestures/ui-event-manager.js.UIEventManager.destroy (http://localhost:9876/_karma_webpack_/vendor.bundle.js:41535:14)
        at FabContainer.webpackJsonp.../../../../ionic-angular/components/fab/fab-container.js.FabContainer.ngOnDestroy (http://localhost:9876/_karma_webpack_/vendor.bundle.js:9287:22)
        at callProviderLifecycles (http://localhost:9876/_karma_webpack_/vendor.bundle.js:120688:18)
        at callElementProvidersLifecycles (http://localhost:9876/_karma_webpack_/vendor.bundle.js:120657:13)
        at callLifecycleHooksChildrenFirst (http://localhost:9876/_karma_webpack_/vendor.bundle.js:120641:17)
        at destroyView (http://localhost:9876/_karma_webpack_/vendor.bundle.js:121902:5)
        at callViewAction (http://localhost:9876/_karma_webpack_/vendor.bundle.js:122048:13)
Chrome 60.0.3112 (Mac OS X 10.11.6): Executed 14 of 30 (1 FAILED) (0 secs / 2.319 secs)
Chrome 60.0.3112 (Mac OS X 10.11.6) Pages: Page2 should create page2 FAILED
    TypeError: unRegEvent is not a function
        at http://localhost:9876/_karma_webpack_/vendor.bundle.js:41527:13
        at Array.forEach (&lt;anonymous&gt;)
        at UIEventManager.webpackJsonp.../../../../ionic-angular/gestures/ui-event-manager.js.UIEventManager.unlistenAll (http://localhost:9876/_karma_webpack_/vendor.bundle.js:41526:19)
        at UIEventManager.webpackJsonp.../../../../ionic-angular/gestures/ui-event-manager.js.UIEventManager.destroy (http://localhost:9876/_karma_webpack_/vendor.bundle.js:41535:14)
        at FabContainer.webpackJsonp.../../../../ionic-angular/components/fab/fab-container.js.FabContainer.ngOnDestroy (http://localhost:9876/_karma_webpack_/vendor.bundle.js:9287:22)
        at callProviderLifecycles (http://localhost:9876/_karma_webpack_/vendor.bundle.js:120688:18)
        at callElementProvidersLifecycles (http://localhost:9876/_karma_webpack_/vendor.bundle.js:120657:13)
        at callLifecycleHooksChildrenFirst (http://localhost:9876/_karma_webpack_/vendor.bundle.js:120641:17)
        at destroyView (http://localhost:9876/_karma_webpack_/vendor.bundle.js:121902:5)
ERROR: 'Error during cleanup of component', Page2{title: 'Page 2', OK: function () { ... }, alertController: Object{create: function () { ... }}}
</code></pre>

<p>I tried adding the components by hand, mocking various services but could not figure out what causes this behaviour.</p>
",https://stackoverflow.com/questions/45711222/how-to-test-a-floating-action-button-in-ionic2,"['angular', 'ionic2', 'angular2-testing']",251,TRUE,2,1
Trouble Setting Up Mocha/ChaiHttp Unit Tests With My Node.js REST API,"<p>I am trying to set up unit testing for my node.js REST API using mocha and chaihttp, but my sample test which should pass seems to be failing.</p>

<p>My code for the unit tests is here:</p>

<pre><code>var express = require('express');
var router = express.Router();

var chai = require(""chai"");
var chaiHttp = require('chai-http');
chai.use(chaiHttp);

describe(""Test"", function() {
    it('Simple test', function(done) {
        chai.request('http://localhost:3000/')
            .get('/')
            .end(function(err, res) {
                chai.expect(res).to.have.status(200);
                done();
            });
    });
});
</code></pre>

<p>And the error I get when running the tests:</p>

<pre><code>  1) Test Simple test:
     Uncaught AssertionError: expected { Object (domain, _events, ...) } to have status code 200 but got 404
      at tests.js:13:42
      at Test.Request.callback (/Users/laptop/Desktop/Toptal/node_modules/superagent/lib/node/index.js:631:3)
      at IncomingMessage.&lt;anonymous&gt; (/Users/laptop/Desktop/Toptal/node_modules/superagent/lib/node/index.js:795:18)
      at endReadableNT (_stream_readable.js:974:12)
      at _combinedTickCallback (internal/process/next_tick.js:74:11)
      at process._tickCallback (internal/process/next_tick.js:98:9)
</code></pre>

<p>From what it looks like, it's unable to connect to my local host or something because I'm getting a 404 error whereas if I manually go to localhost:3000 in my browser, I'm served a simple Hello world index page.</p>

<p>Here is my index.js route if it might be relevant:</p>

<pre><code>var express = require('express');

var router = express.Router();

router.get('/', function(req, res, next) {
    res.status(200).render('index.ejs');
});

module.exports = router;
</code></pre>
",https://stackoverflow.com/questions/42799423/trouble-setting-up-mocha-chaihttp-unit-tests-with-my-node-js-rest-api,"['javascript', 'node.js', 'mocha.js', 'chai']",5945,TRUE,2,1
How do I run redis on Travis CI?,"<p>I am practicing unit testing using django</p>

<p><strong>In items/tests.py</strong></p>

<pre><code>class NewBookSaleTest(SetUpLogInMixin):

def test_client_post_books(self):

    send_post_data_post = self.client.post(
            '/booksale/',
            data = {
                'title':'Book_A',
                }
            )

    new_post = ItemPost.objects.first()
    self.assertEqual(new_post.title, 'Book_A')
</code></pre>

<p><strong>In views/booksale.py</strong></p>

<pre><code>class BookSale(LoginRequiredMixin, View):

login_url = '/login/'

def get(self, request):
    [...]

def post(self, request):

    title = request.POST.get('title')

    saler = request.user

    created_bookpost = ItemPost.objects.create(
                user=saler,
                title=title,
                )

    # redis + celery task queue
    auto_indexing = UpdateIndexTask()
    auto_indexing.delay()

        return redirect(
               [...]
                ) 
</code></pre>

<p>when I run unit test, raise redis connection error</p>

<pre><code> redis.exceptions.ConnectionError
</code></pre>

<p>I know when I running redis-server and celery is error will solve</p>

<p>but when I run unit test in <code>Travis CI</code> I can't run redis-server and celery in Travis CI</p>

<p>So, I found this <a href=""https://docs.travis-ci.com/user/database-setup/#Redis"" rel=""nofollow noreferrer"">link</a></p>

<p>I try insert this code in .travis.yml</p>

<pre><code>language:
    python
python:
    - 3.5.1
addons:
    postgresql:""9.5.1""
install:
    - pip install -r requirement/development.txt

service:
    - redis-server

# # command to run tests
script:
    - pep8
    - python wef/manage.py makemigrations users items
    - python wef/manage.py migrate
    - python wef/manage.py collectstatic --settings=wef.settings.development --noinput
    - python wef/manage.py test users items --settings=wef.settings.development
</code></pre>

<p>but it shows same error</p>

<p>so I found next <a href=""https://stackoverflow.com/questions/27297703/running-redis-on-travis-ci"">link</a></p>

<pre><code>before_script:
    - sudo redis-server /etc/redis/redis.conf --port 6379 --requirepass 'secret'
</code></pre>

<p>but... it show same error...</p>

<p>how can I running redis-server in travis ci?</p>
",https://stackoverflow.com/questions/45995561/how-do-i-run-redis-on-travis-ci,"['django', 'unit-testing', 'redis', 'celery']",1480,TRUE,2,1
How to cope with tests coverage and impossible reached lines?,"<p>I'm starting to work with Java and JUnit, and I'm facing some problem with understanding the tips and tricks about code coverage. </p>

<p>If I'm right, the ultimate goal in unit testing classes is to get to a 100% test coverage. </p>

<p>So here is the code that I have right now:</p>

<pre><code>// field is of type Field (from reflection)

field.setAccessible(true);
try {
    field.get(instance);
} catch (IllegalAccessException e) {
    e.printStackTrace();
}
</code></pre>

<p>So here, you can see that I can't access the catch() block at any time because I make the field Accessible just on top of it... </p>

<p><strong>What is wrong with my code? How can I get a 100% code coverage result when this happens?</strong></p>
",https://stackoverflow.com/questions/46553865/how-to-cope-with-tests-coverage-and-impossible-reached-lines,"['java', 'junit']",179,TRUE,2,1
Mock function of React Native component with Enzyme,"<p>I'm trying to get going unit testing using Enzyme and Jest to mock functions of a class that extends <code>React.Component</code>, and I'm finding can mock the inherited <code>setState</code> function, but no other functions in the component.</p>

<p>For example, my App component has a <code>TextInput</code> that invokes <code>setState</code> on an <code>onChangeText</code> event, and a <code>TouchableOpacity</code> that invokes <code>submitFilter</code> on an <code>onPress</code> event.</p>

<pre><code>export default class App extends React.Component {
  constructor(props) {
    super(props)

    this.state = { filter: '' }
  }
  submitFilter = () =&gt; {
    if (this.state.filter.length &lt;= 0) {
      Alert.alert('Filter is blank');
    }
  }
  render() {
    return (
      &lt;View style={styles.container}&gt;
        &lt;View style={styles.filterContainer}&gt;
          &lt;TextInput
            style={styles.filterInput}
            placeholder='Filter...'
            value={this.state.filter}
            onChangeText={(text) =&gt; {this.setState({ filter: text })}}
          /&gt;
          &lt;TouchableOpacity
            style={styles.filterButton}
            onPress={this.submitFilter}&gt;
            &lt;Text style={styles.filterButtonLabel}&gt;Go&lt;/Text&gt;
          &lt;/TouchableOpacity&gt;
        &lt;/View&gt;
      &lt;/View&gt;
    );
  }
}
</code></pre>

<p>Using the same pattern for mocking <code>setState</code> and <code>submitFilter</code>, and the same pattern for invoking each function:</p>

<pre><code>import Adapter from 'enzyme-adapter-react-16';
import Enzyme from 'enzyme';

Enzyme.configure({ adapter: new Adapter() });

describe('interaction', () =&gt; {
  let wrapper
  let mockFn
  beforeEach(() =&gt; {
    wrapper = Enzyme.shallow(&lt;App /&gt;)
    mockFn  = jest.fn()
  })
  describe('editing the filter input', () =&gt; {
    beforeEach(() =&gt; {
      wrapper.instance().setState = mockFn
      wrapper.find('TextInput').first().props().onChangeText('waffles');
    })
    it('should update the filter state', () =&gt; {
      expect(mockFn).toHaveBeenCalledTimes(1)
    })
  })
  describe('clicking filter button', () =&gt; {
    beforeEach(() =&gt; {
      wrapper.instance().submitFilter = mockFn
      wrapper.find('TouchableOpacity').first().props().onPress()
    })
    it('should invoke the submitFilter callback', () =&gt; {
      expect(mockFn).toHaveBeenCalledTimes(1)
    })
  })
})
</code></pre>

<p>Only the first passes, and I'm not sure what approach to use for mocking the <code>submitFilter</code> function to verify it gets invoked?</p>

<pre><code>  interaction
    editing the filter input
      ✓ should update the filter state (3ms)
    clicking filter button
      ✕ should invoke the submitFilter callback (18ms)

  ● interaction › clicking filter button › should invoke the submitFilter callback

    expect(jest.fn()).toHaveBeenCalledTimes(1)

    Expected mock function to have been called one time, but it was called zero times.

      at Object.&lt;anonymous&gt; (App.test.js:47:16)
      at tryCallTwo (node_modules/promise/lib/core.js:45:5)
      at doResolve (node_modules/promise/lib/core.js:200:13)
      at new Promise (node_modules/promise/lib/core.js:66:3)
      at tryCallOne (node_modules/promise/lib/core.js:37:12)
      at node_modules/promise/lib/core.js:123:15
</code></pre>

<p>Any ideas?</p>
",https://stackoverflow.com/questions/47552645/mock-function-of-react-native-component-with-enzyme,"['react-native', 'jestjs', 'enzyme']",1648,FALSE,2,1
NSubstitute: Mock method is not returning expected result,"<p>I'm new to NSubstitute, mocking, and unit testing in general.</p>

<p>I'm trying to use <code>NSubstitute</code> to remove some dependencies I have in my class under test, but methods in the mock objects are not behaving as I expect based on how I configured them. Here is an example I created in Visual Studio:</p>

<ol>
<li><p>Interface and concrete class to be substituted. Notice, <code>MyConcreteClass.MyMethod()</code> returns <code>false</code>:</p>

<pre><code>public interface IMyInterface
{
    bool MyMethod(string arg);
}

public class MyConcreteClass : IMyInterface
{
    public bool MyMethod(string arg)
    {
        return false;
    }
}
</code></pre></li>
<li><p>My class under test:</p>

<pre><code>public class MyTestedClass
{
    private IMyInterface _concrete;

    public MyTestedClass()
    {
        _concrete = new MyConcreteClass();
    }

    public MyTestedClass(IMyInterface mock)
    {
        _concrete = mock;
    }

    public bool MyConcreteMethod(string arg)
    {
        return _concrete.MyMethod(arg);
    }
}
</code></pre></li>
<li><p>My unit test class for <code>MyTestedClass</code>:</p>

<pre><code>[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void Given_MyMethodIsUsingAMock_ShouldReturnTrue()
    {
        // Arrange
        var myMock = Substitute.For&lt;IMyInterface&gt;();
        myMock.MyMethod(""blah"").Returns(true);
        var myTestedObject = new MyTestedClass(myMock);

        // Act
        var result = myTestedObject.MyConcreteMethod(""blah blah"");

        // Assert
        Assert.AreEqual(result, true); // This assertion fails!
    }

    [TestMethod]
    public void Given_MyMethodIsNotMock_ShouldReturnFalse()
    {
        // Arrange
        var myTestedObject = new MyTestedClass();

        // Act
        var result = myTestedObject.MyConcreteMethod(""blah blah"");

        // Assert
        Assert.AreEqual(result, false); // This assertion passes.
    }
}
</code></pre></li>
<li><p>Test results show that <code>Given_MyMethodIsUsingAMock_ShouldReturnTrue()</code> fails:</p>

<pre><code>MyUnitTests (2 tests) [0:00.190] Failed: 1 test failed
 MyUnitTests (2 tests) [0:00.190] Failed: 1 test failed
  UnitTest1 (2 tests) [0:00.190] Failed: 1 test failed
   Given_MyMethodIsNotMock_ShouldReturnFalse [0:00.000] Success
   Given_MyMethodIsUsingAMock_ShouldReturnTrue [0:00.189] Failed
Assert.AreEqual failed. Expected:&lt;False&gt;. Actual:&lt;True&gt;. 
   at MyUnitTests.UnitTest1.Given_MyMethodIsUsingAMock_ShouldReturnTrue() in ""c:\MyWorkspace\projects\NSubstituteMocking\MyUnitTests\UnitTest1.cs"":line 23
</code></pre></li>
</ol>

<p>It looks like I'm missing a trivial configuration, but it is eluding me.</p>
",https://stackoverflow.com/questions/47647706/nsubstitute-mock-method-is-not-returning-expected-result,"['c#', '.net', 'unit-testing', 'mocking', 'nsubstitute']",3331,TRUE,2,1
Umbraco Unit Tests,"<p>Trying to utilise the PublishedContentRequest method in order to perform several unit tests. As this is separate project purely for unit testing there is no Umbraco context as such.</p>

<p>Just wondering if anyone else has had an issue with testing Umbraco this way.  Really need to understand what uri it is expecting as well. For example is is ""contact-us"", ""/contact-us"" or ""<a href=""http://localhost/contact-us"" rel=""nofollow noreferrer"">http://localhost/contact-us</a>"".  Also would like to know how to setup the routingcontext correctly.</p>

<p>Got something like this at the moment:</p>

<pre><code>private static void SetupControllerContext(UmbracoContext umbCtx, ControllerBase controller)
    {
        var contextBase = umbCtx.HttpContext;
        var pcr = new PublishedContentRequest(new Uri(""/contact-us""), umbCtx.RoutingContext);

        var routeData = new RouteData();
        var routeDefinition = new RouteDefinition
        {
            PublishedContentRequest = pcr
        };
        routeData.DataTokens.Add(""umbraco-route-def"", routeDefinition);
        controller.ControllerContext = new ControllerContext(contextBase, routeData, controller);
}
</code></pre>

<p>Any pointers would be great.</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/41761494/umbraco-unit-tests,"['c#', 'unit-testing', 'umbraco7']",514,TRUE,2,1
Read resource file from inside SonarQube Plugin,"<p>I am developing a plugin using <code>org.sonarsource.sonarqube:sonar-plugin-api:6.3</code>. I am trying to access a file in my <code>resource</code> folder. The reading works fine in unit testing, but when it is deployed as a jar into sonarqube, it couldn't locate the file.</p>

<p>For example, I have the file <code>Something.txt</code> in <code>src/main/resources</code>. Then, I have the following code</p>

<pre><code>private static final String FILENAME = ""Something.txt"";

String template = FileUtils.readFile(FILENAME);
</code></pre>

<p>where FileUtils.readFile would look like </p>

<pre><code>public String readFile(String filePath) {
    try {
        return readAsStream(filePath);
    } catch (IOException ioException) {
        LOGGER.error(""Error reading file {}, {}"", filePath, ioException.getMessage());
        return null;
    }
}

private String readAsStream(String filePath) throws IOException {
    try (InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath)) {
        if (inputStream == null) {
            throw new IOException(filePath + "" is not found"");
        } else {
            return IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        }
    }
}
</code></pre>

<p>This question is similar with <a href=""https://stackoverflow.com/questions/20389255/reading-a-resource-file-from-within-jar"">reading a resource file from within a jar</a>. I also have tried with <code>/Something.txt</code> and <code>Something.txt</code>, both does not work.If I put the file <code>Something.txt</code> in the <code>classes</code> folder in sonarqube installation folder, the code will work. </p>
",https://stackoverflow.com/questions/43198028/read-resource-file-from-inside-sonarqube-plugin,"['file-io', 'sonarqube']",439,TRUE,2,1
How to run mongodb service in gitlab runner with docker executer,"<p>I'm trying to establish <strong>pipeline</strong> in <strong>gitlab</strong> for testing my <strong>api</strong> written in <strong>laravel</strong> with <strong>mongodb</strong> as database. Following is my <strong>.gitlab-ci.yml</strong> file.</p>

<pre><code>image: registry.gitlab.com/sadhu/web:latest

services:
  - name: mongo:3.4.10

variables:
  MONGO_URI: 'mongodb://mongo/demo'

stages:
  - test

unit_test:
  stage: test
  script:
    - npm install
    - composer install
    - cp .env.testing .env
    - php artisan key:generate
    - php artisan config:cache
    - php vendor/bin/phpunit --coverage-text --colors=never
</code></pre>

<p>But unit test results in negative results. Following is the result of my unit testing:</p>

<pre><code>1) TestBedApiTest::testDuplicateId
Expected status code 409, got 500.
Failed asserting that 500 matches expected 409.
</code></pre>

<p><strong>500</strong> error mostly comes when laravel api is unable to connect to database. But I'm not sure whether it is the main reason or not and I'm not able to find out, how to ensure this.</p>

<p>Following is my <strong>.env.testing</strong> file.</p>

<pre><code>APP_ENV=development
APP_KEY=base64:fvuqjkl+g7MNIH2eC39Osp78feOfHhMDXPXSlKHlPD4=
APP_DEBUG=true
APP_LOG_LEVEL=debug

DB_CONNECTION=mongodb
DB_HOST=mongo
DB_PORT=27017
DB_DATABASE=demo
DB_USERNAME=
DB_PASSWORD=
</code></pre>

<p>Can someone tell me how to enable mongodb service in gitlab runner?</p>
",https://stackoverflow.com/questions/47857487/how-to-run-mongodb-service-in-gitlab-runner-with-docker-executer,"['php', 'mongodb', 'docker', 'gitlab', 'gitlab-ci-runner']",2547,FALSE,2,0
Was ManuallyPumpedSynchronizationContext required in Jon Skeet&#39;s &quot;TimeMachine&quot; async unit test framework?,"<p>I've just seen a video-class by Jon Skeet, where he talks about unit testing asynchronous methods. It was on a paid website, but I've found something similar to what he says, in his <a href=""http://apprize.info/c/depth/15.html"" rel=""nofollow noreferrer"">book</a> (just Ctrl+F ""15.6.3. Unit testing asynchronous code"").</p>

<p>The complete code can be found on <a href=""https://github.com/jskeet/DemoCode/tree/master/AsyncIntro/Code/Testing.NUnit"" rel=""nofollow noreferrer"">his github</a>, but I have simplified it for the sake of my question (my code is basically <code>StockBrokerTest.CalculateNetWorthAsync_AuthenticationFailure_ThrowsDelayed()</code> but with TimeMachine and Advancer operations inlined).</p>

<p>Let's suppose we have a class to test a failed login (no unit test framework to simplify the question):</p>

<pre class=""lang-csharp prettyprint-override""><code>public static class LoginTest
{
    private static TaskCompletionSource&lt;Guid?&gt; loginPromise = new TaskCompletionSource&lt;Guid?&gt;();

    public static void Main()
    {
        Console.WriteLine(""== START =="");

        // Set up
        var context = new ManuallyPumpedSynchronizationContext(); // Comment this
        SynchronizationContext.SetSynchronizationContext(context); // Comment this

        // Run method under test
        var result = MethodToBeTested();
        Debug.Assert(!result.IsCompleted, ""Result should not have been completed yet."");

        // Advancing time
        Console.WriteLine(""Before advance"");
        loginPromise.SetResult(null);
        context.PumpAll(); // Comment this
        Console.WriteLine(""After advance"");

        // Check result
        Debug.Assert(result.IsFaulted, ""Result should have been faulted."");
        Debug.Assert(result.Exception.InnerException.GetType() == typeof(ArgumentException), $""The exception should have been of type {nameof(ArgumentException)}."");

        Console.WriteLine(""== END =="");
        Console.ReadLine();
    }

    private static async Task&lt;int&gt; MethodToBeTested()
    {
        Console.WriteLine(""Before login"");
        var userId = await Login();
        Console.WriteLine(""After login"");
        if (userId == null)
        {
            throw new ArgumentException(""Bad username or password"");
        }

        return userId.GetHashCode();
    }

    private static Task&lt;Guid?&gt; Login()
    {
        return loginPromise.Task;
    }
}
</code></pre>

<p>Where the implementation of <code>ManuallyPumpedSynchronizationContext</code> is:</p>

<pre class=""lang-csharp prettyprint-override""><code>public sealed class ManuallyPumpedSynchronizationContext : SynchronizationContext
{
    private readonly BlockingCollection&lt;Tuple&lt;SendOrPostCallback, object&gt;&gt; callbacks;

    public ManuallyPumpedSynchronizationContext()
    {
        callbacks = new BlockingCollection&lt;Tuple&lt;SendOrPostCallback, object&gt;&gt;();
    }

    public override void Post(SendOrPostCallback callback, object state)
    {
        Console.WriteLine(""Post()"");
        callbacks.Add(Tuple.Create(callback, state));
    }

    public override void Send(SendOrPostCallback d, object state)
    {
        throw new NotSupportedException(""Synchronous operations not supported on ManuallyPumpedSynchronizationContext"");
    }

    public void PumpAll()
    {
        Tuple&lt;SendOrPostCallback, object&gt; callback;
        while(callbacks.TryTake(out callback))
        {
            Console.WriteLine(""PumpAll()"");
            callback.Item1(callback.Item2);
        }
    }
}
</code></pre>

<p>The output is:</p>

<pre class=""lang-none prettyprint-override""><code>== START ==
Before login
Before advance
After login
After advance
== END ==
</code></pre>

<p><strong>My question is:</strong> Why do we need the <code>ManuallyPumpedSynchronizationContext</code>?</p>

<p>Why isn't the default SynchronizationContext enough? The <code>Post()</code> method isn't even called (based on the output). I've tried commenting the lines marked with <code>// Comment this</code>, and the output is the same and the asserts pass.</p>

<p>If I understood correctly what Jon Skeet says in the video, the <code>SynchronizationContext.Post()</code> method should be called when we meet an <code>await</code> with a not-yet-completed task. But this is not the case. What am I missing?</p>

<p><strong>Aditional info</strong></p>

<p>Through my researches, I stumbled across <a href=""https://stackoverflow.com/a/16916466/2420998"">this answer</a>. To try it, I changed the implementation of the <code>Login()</code> method to:</p>

<pre class=""lang-csharp prettyprint-override""><code>private static Task&lt;Guid?&gt; Login()
{
    // return loginPromise.Task;
    return Task&lt;Guid?&gt;.Factory.StartNew(
        () =&gt;
        {
            Console.WriteLine(""Login()"");
            return null;
        },
        CancellationToken.None,
        TaskCreationOptions.None,
        TaskScheduler.FromCurrentSynchronizationContext());
}
</code></pre>

<p>With that modification, the <code>Post()</code> method was indeed called. Output:</p>

<pre class=""lang-none prettyprint-override""><code>== START ==
Before login
Post()
Before advance
PumpAll()
Login()
After login
After advance
== END ==
</code></pre>

<p>So with Jon Skeet's use of <code>TaskCompletionSource</code>, was his creation of <code>ManuallyPumpedSynchronizationContext</code> not required?</p>

<p><em>Note</em>: I think the video I saw was made just around C# 5 release date.</p>
",https://stackoverflow.com/questions/42898828/was-manuallypumpedsynchronizationcontext-required-in-jon-skeets-timemachine-a,"['c#', 'unit-testing', 'async-await']",266,TRUE,8,3
How to test waterline models in Trails.js,"<p>I wanted to test the models of my Trails.js project with mocha. I use the <a href=""https://github.com/trailsjs/trailpack-waterline"" rel=""noreferrer"">trailpack-waterline</a> to load my models into the Waterline ORM.</p>

<p>Following the Trails <a href=""https://trailsjs.io/doc/en/test/unit.html#model-test-suite"" rel=""noreferrer"">Docs</a> I created a <code>User.test.js</code>:</p>

<pre><code>'use strict'

const assert = require('assert')

describe('User Model', () =&gt; {
  let User

  before(() =&gt; {
    assert(global.app.models.User)
    User = global.app.models.User
  })

  it('should exist', () =&gt; {
    assert(User)
  })
})
</code></pre>

<p>This runs without any error.</p>

<p>But I cannot instantiate the model in any way. Following the example of the Docs <code>new User({...})</code> should create a new user object, but this code throws an error saying <code>User is not a constructor</code>. And neither the example of the Waterline <a href=""https://sailsjs.com/documentation/concepts/testing#?writing-tests"" rel=""noreferrer"">Docs</a> using <code>User.create({...})</code> seems to work.</p>

<p>Printing out the User model shows it consists of only two <code>methods: [ 'getModelName', 'getTableName' ]</code>.</p>

<p>How do I instantiate a waterline Model for unit testing?</p>
",https://stackoverflow.com/questions/47180468/how-to-test-waterline-models-in-trails-js,"['javascript', 'unit-testing', 'mocha.js', 'waterline', 'trailsjs']",110,TRUE,7,1
Jenkins: force all projects to use the same jenkinsfile,"<p>Is it possible to configure Jenkins to always run using a predefined Jenkinsfile for all projects, rather than pulling a Jenkinsfile from the project repo?  The goal here is to make sure that a certain set of stages are always being run.  If we allow projects to define their own Jenkinsfile, they could theoretically just skip some required stages in their project (like unit testing).</p>

<p>I want to make sure this never happens, but simply telling everyone ""don't remove these stages from your Jenkinsfile"" seems a bit brittle.</p>
",https://stackoverflow.com/questions/46369496/jenkins-force-all-projects-to-use-the-same-jenkinsfile,"['jenkins', 'jenkins-pipeline']",349,FALSE,2,1
How can I import &#39;createSpyObj&#39; from jasmine for tests written in Typescript?,"<p>How do I import the <code>createSpyObj</code> property from jasmine?</p>

<p>I have installed <code>@types/jasmine</code> and <code>jasmine-core</code> via npm.</p>

<p>I have tried importing jasmine as:</p>

<pre><code>import jasmine from 'jasmine;
import { createSpyObj } from 'jasmine'; //triggers import error in IDE
import * as jasmine from 'jasmine'; //triggers import error in IDE
</code></pre>

<p>None of these allow me to access the <code>createSpyObj</code> without an error thrown in my WebStorm IDE.</p>

<p><a href=""https://i.stack.imgur.com/ti1MT.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/ti1MT.png"" alt=""IDE error showing it cannot find &#39;createSpyObj&#39; method on jasmine""></a></p>

<p><strong>More information:</strong></p>

<p>I see a namespace declaration for <code>createSpyObj</code> in the typings file. It is nested in the <code>jasmine</code> namespace. This is unlike <code>expect</code>, <code>it</code>, which are global declarations, but shouldn't I be able to access it with <code>jasmine.createSpyObj</code>?</p>

<p><a href=""https://i.stack.imgur.com/uWleN.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/uWleN.png"" alt=""jasmine typings file""></a></p>

<p>Related, but not duplicate of</p>

<p><a href=""https://stackoverflow.com/questions/41143700/how-to-import-describe-expect-and-it-into-a-typescript-tests-for-ide-to-n"">How to import &#39;describe&#39;, &#39;expect&#39; and &#39;it&#39; into a typescript tests for IDE to not to highlight them</a> and </p>

<p><a href=""https://stackoverflow.com/questions/30863565/unit-testing-using-jasmine-and-typescript"">Unit testing using Jasmine and TypeScript</a></p>
",https://stackoverflow.com/questions/46492029/how-can-i-import-createspyobj-from-jasmine-for-tests-written-in-typescript,"['angularjs', 'typescript', 'jasmine', 'webstorm']",1927,TRUE,7,1
Mocking Sequelize functions to expect output,"<p>I am new to the concept of unit testing and I have to test write the test for my ""create"" function that stores a record to the database table(mySQL). Here's my code for the controller :</p>

<pre><code>'use strict'
var todo = require('../../../repository/todo-repo')
module.exports = {
 collect: (req,res,next)=&gt;{
      var fields = ['id','title','description'];
      var reqdata = new req.collect(req,fields);

      req.task_data = reqdata.collect(req,res)
      if(!req.task_data.length) return (new Error(""no values provided""))
      console.log(req.task_data);
      next();
  },
 create: (req,res,next) =&gt;{
      var options = {
      data:req.task_data
     }
    todo.create(options,success,error)
    function success(result){
     console.log(result);
     }
    function error(err){
      if(err) return (err)
     }
   }
}
</code></pre>

<p>And here's my test code :</p>

<pre><code>var chai = require('chai')
var expect = chai.expect;
var todo = require('../controllers/api/todo/todo')
var todomodal = require('../models/todo')
var create = todo.create;
var sinon = require('sinon');

  describe('create',()=&gt;{
   it('should add data to the todo table',(done)=&gt;{
    var req = {
     task_data:{
     title:""here"",
     description:""details to follow""
      }
   }
  var id = create(req,null,null)
  console.log(""=&gt;&gt;"",id);
  expect(id).to.be.a('string')
  done()
  })
})
</code></pre>

<p>How do I write the test to expect a certain result from my function. Let's say I would like to send the test data to the function and expect the created record's id to be an integer. Since sequelize returns success and error two callbacks, how do I handle that?</p>
",https://stackoverflow.com/questions/42344697/mocking-sequelize-functions-to-expect-output,"['node.js', 'mocha.js', 'sinon']",203,FALSE,1,0
Testing asyn calls throws Unhandled promise rejection in Node JS,"<p>I´m unit testing an Express function like this:</p>

<pre><code>function(request,response,someDependency){
  ...
  someDependency.doStuff(arg1,arg2)
  .then(function(someResponse){
      response.status(200).send({body: someResponse});
  })
  .catch(function(error){
      response.status(500).send({someResponse: 'error');
  });
}
</code></pre>

<p>In my unit tests (using Mocha), I have decided to mock my response, using assertions inside it, and also to mock my dependency:</p>

<p>An abstraction of my mockedResponse:</p>

<pre><code>...
exports.expectedStatus = function(status){
  this.expectedCode = status;
}
exports.status = function(realStatus){
  this.expectdCode = realStatus;
  return this;
}
exports.send = function(body){
  assert.strictEqual(this.realStatus,this.expectedCode);
}
</code></pre>

<p>and an abstraction of my dependency would be:</p>

<pre><code>exports.setPromiseError(error){
  this.error = error;
};
exports.doStuff(arg1,arg2){
   return new Promise(function (resolve, reject){
      if (!error)
         resolve({this: 'is', a: 'response'});
      else
         reject(error);
     }});
</code></pre>

<p>In my unit tests I have a test like this: </p>

<pre><code>mockedResponse = require('./fake/assertiveResponse.js');
mockedDependency       = require('./fake/dependency.js');

it('should throw error',function(){
   mockedDependency.setPromiseError(new Error('sorry, not today');
   myLibUnderTest.myFunctionUnderTest(someFakeRequest,
                                       mockedResponse.get()
                                        .expectedStatus(200), &lt;--I´m forcing a failing test here!
                                      mockedDependency);
});    
</code></pre>

<p>But...my assert appears to be <a href=""http://jamesknelson.com/are-es6-promises-swallowing-your-errors/"" rel=""nofollow noreferrer"">swalled</a> by the promise and <strong>I get a passing test</strong> with this console output:</p>

<pre><code>(node:1512) UnhandledPromiseRejectionWarning: Unhandled promise rejection
(rejection id: 2): AssertionError: 500 === 200
</code></pre>

<p>Right now I´m not even sure I´m using Promises the right way...any help is appreciated.</p>
",https://stackoverflow.com/questions/44877038/testing-asyn-calls-throws-unhandled-promise-rejection-in-node-js,"['javascript', 'node.js', 'unit-testing', 'promise', 'mocking']",446,FALSE,1,3
Elasticsearch :found jar hell in test classpath,"<p>I want to perform unit testing in Elasticsearch for that I am using <code>Java-test-framework</code><br>
I am using <code>Elasticsearch-1.6.0</code>
and referring to these link for help 
<a href=""https://www.elastic.co/guide/en/elasticsearch/reference/1.6/using-elasticsearch-test-classes.html"" rel=""noreferrer"">https://www.elastic.co/guide/en/elasticsearch/reference/1.6/using-elasticsearch-test-classes.html</a>
<a href=""https://github.com/elastic/elasticsearch/blob/master/core/src/test/java/org/elasticsearch/action/search/SearchRequestBuilderTests.java"" rel=""noreferrer"">https://github.com/elastic/elasticsearch/blob/master/core/src/test/java/org/elasticsearch/action/search/SearchRequestBuilderTests.java</a></p>

<p>here is the code </p>

<pre><code>class CampaignESTest extends ESTestCase {

  def getCLient():MockTransportClient={
     val settings = Settings.builder()
                .put(Environment.PATH_HOME_SETTING.getKey(), Files.createTempDir().toString())
                .build();
     val client = new MockTransportClient(settings);  
     client
  }
 }

class CampaignTestSearch extends PlaySpec{
  val client=new CampaignESTest

val response = client.prepareSearch(""dbtest"")
      .setTypes(CAMPAIGN_COLLECTION_NAME)
      .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
      .addFields(""uuid"",""campaignName"",""artworkID"",""activationDate"",""_source"")
      .setQuery(query)
      .execute()
      .actionGet()
  }
</code></pre>

<p>I am getting these exceptions </p>

<pre><code>    Exception encountered when attempting to run a suite with class name: org.scalatest.DeferredAbortedSuite *** ABORTED ***
[info]   java.lang.ExceptionInInitializerError:
[info]   at org.elasticsearch.test.ESTestCase.&lt;clinit&gt;(ESTestCase.java:138)
[info]   at testcontrollers.campaign.CampaignTestSearch.&lt;init&gt;(CampaignTestSearch.scala:40)
[info]   at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
[info]   at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
[info]   at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
[info]   at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
[info]   at java.lang.Class.newInstance(Class.java:442)
[info]   at org.scalatest.tools.Framework$ScalaTestTask.execute(Framework.scala:468)
[info]   at sbt.ForkMain$Run$2.call(ForkMain.java:296)
[info]   at sbt.ForkMain$Run$2.call(ForkMain.java:286)
[info]   ...
[info]   Cause: java.lang.RuntimeException: found jar hell in test classpath
[info]   at org.elasticsearch.bootstrap.BootstrapForTesting.&lt;clinit&gt;(BootstrapForTesting.java:90)
[info]   at org.elasticsearch.test.ESTestCase.&lt;clinit&gt;(ESTestCase.java:138)
[info]   at testcontrollers.campaign.CampaignTestSearch.&lt;init&gt;(CampaignTestSearch.scala:40)
[info]   at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
[info]   at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
[info]   at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
[info]   at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
[info]   at java.lang.Class.newInstance(Class.java:442)
[info]   at org.scalatest.tools.Framework$ScalaTestTask.execute(Framework.scala:468)
[info]   at sbt.ForkMain$Run$2.call(ForkMain.java:296)
[info]   ...
[info]   Cause: java.nio.file.NoSuchFileException: /home/testproject/target/web/classes/test
[info]   at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86)
[info]   at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
[info]   at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
[info]   at sun.nio.fs.UnixFileAttributeViews$Basic.readAttributes(UnixFileAttributeViews.java:55)
[info]   at sun.nio.fs.UnixFileSystemProvider.readAttributes(UnixFileSystemProvider.java:144)
[info]   at sun.nio.fs.LinuxFileSystemProvider.readAttributes(LinuxFileSystemProvider.java:99)
[info]   at java.nio.file.Files.readAttributes(Files.java:1737)
[info]   at java.nio.file.FileTreeWalker.getAttributes(FileTreeWalker.java:219)
[info]   at java.nio.file.FileTreeWalker.visit(FileTreeWalker.java:276)
[info]   at java.nio.file.FileTreeWalker.walk(FileTreeWalker.java:322)
</code></pre>

<p>getting an exception on this line </p>

<pre><code>val client=new CampaignESTest
</code></pre>

<p>in class <code>CampaignTestSearch</code></p>

<p>here are the dependencies in <code>build.sbt</code> file </p>

<pre><code>libraryDependencies ++= Seq(filters, 
                ""org.scalatest"" %% ""scalatest"" % ""2.2.6"" % ""test""withSources() withJavadoc(),
                ""org.scalatestplus"" %% ""play"" % ""1.4.0-M3"" % ""test"",
                ""com.esotericsoftware.kryo"" % ""kryo"" % ""2.10"",
                ""org.mongodb"" %% ""casbah"" % ""2.8.0"",
                ""org.slf4j"" % ""slf4j-api"" % ""1.6.4"",
                ""org.elasticsearch"" % ""elasticsearch"" % ""1.6.0"",
                ""org.elasticsearch.test"" % ""framework"" % ""5.0.0"" % ""test"",
                ""org.apache.lucene"" % ""lucene-test-framework"" % ""4.10.4"" % ""test"",
                ""com.carrotsearch.randomizedtesting"" % ""randomizedtesting-runner"" % ""1.6.0"" % ""test"",
                ""org.apache.lucene"" % ""lucene-codecs"" % ""4.10.4"" % ""test"",
                ""org.apache.logging.log4j"" % ""log4j-core"" % ""2.8.2"",
                ""org.apache.logging.log4j"" % ""log4j-slf4j-impl"" % ""2.8.2"" ,
                ""org.apache.logging.log4j"" % ""log4j-api"" % ""2.8.2"",
                ""com.typesafe.akka"" %% ""akka-actor"" % ""2.3.6"",
                ""com.typesafe.akka"" % ""akka-testkit_2.11"" % ""2.3.6"",
                ""ch.qos.logback"" % ""logback-core"" % ""1.0.9"",
                ""com.github.nscala-time"" %% ""nscala-time"" % ""2.0.0"",
                ""com.hazelcast"" % ""hazelcast"" % ""3.5"",
                ""com.hazelcast"" % ""hazelcast-client"" % ""3.5"",
                ""com.twitter"" % ""chill-bijection_2.11"" % ""0.7.0"",
                ""com.github.slugify"" % ""slugify"" % ""2.1.3"" ,
                ""org.mindrot"" % ""jbcrypt"" % ""0.3m"",
                ""org.codehaus.groovy"" % ""groovy-all"" % ""2.4.0"",
                ""org.apache.lucene"" % ""lucene-expressions"" % ""4.10.4"",
                ""com.restfb"" % ""restfb"" % ""1.19.0"",
                ""org.twitter4j"" % ""twitter4j-core"" % ""4.0.0"",
                ""org.scribe"" % ""scribe"" % ""1.3.5"",
                ""com.google.code.gson"" % ""gson"" % ""2.6.2"",
                ""com.google.oauth-client"" % ""google-oauth-client"" % ""1.20.0"",
                ""com.google.api.client"" % ""google-api-client-auth-oauth2"" % ""1.2.0-alpha"",
                ""com.google.api-client"" % ""google-api-client"" % ""1.20.0"",
                ""com.google.http-client"" % ""google-http-client-jackson"" % ""1.20.0"",
                ""com.google.apis"" % ""google-api-services-oauth2"" % ""v2-rev120-1.20.0"",
                ""com.google.oauth-client"" % ""google-oauth-client-appengine"" % ""1.20.0"",
                ""com.google.oauth-client"" % ""google-oauth-client-java6"" % ""1.20.0"",
                ""com.google.oauth-client"" % ""google-oauth-client-jetty"" % ""1.20.0"",
                ""com.google.oauth-client"" % ""google-oauth-client-servlet"" % ""1.20.0"",
                ""com.google.apis"" % ""google-api-services-calendar"" % ""v3-rev120-1.19.1"",
                ""com.google.inject"" % ""guice"" % ""3.0"",
                ""org.mockito"" % ""mockito-all"" % ""1.10.19"")
</code></pre>

<p>How can these exception will be resolved ? also I have tried the solution given here 
<a href=""https://stackoverflow.com/questions/38712251/java-jar-hell-runtime-exception"">Java Jar hell Runtime Exception</a>
Bit when i try to create a class <code>JarHell</code> in <code>org/elasticsearch/bootstarp</code> package it won't let me create it saying type already exists I also tried searching the Class but did not found ,please guide </p>
",https://stackoverflow.com/questions/45770719/elasticsearch-found-jar-hell-in-test-classpath,"['java', 'scala', 'elasticsearch', 'elasticsearch-1.6.0']",1548,TRUE,22,1
HIbernate Maven project: No Persistence provider for EntityManager named,"<p>I am working on a JPA tutorial and running into issues when trying to unit test. I am working with Apache Derby and Hibernate.
Here is my sample code files;</p>

<p><strong>persistence.xml</strong></p>

<pre><code>&lt;persistence-unit name=""test"" transaction-type=""RESOURCE_LOCAL""&gt;
    &lt;provider&gt;org.hibernate.ejb.HibernatePersistence&lt;/provider&gt;
    &lt;class&gt;org.agonical.book.pojo.Book&lt;/class&gt;
    &lt;properties&gt;
        &lt;property name=""javax.persistence.schema-generation-action"" value=""drop-and-create""/&gt;
        &lt;property name=""javax.persistence.schema-generation-target"" value=""database-and-scripts""/&gt;
        &lt;property name=""javax.persistence.jdbc.driver"" value=""com.apache.derby.jdbc.EmbeddedDriver""/&gt;
        &lt;property name=""javax.persistence.jdbc.url"" value=""jdbc:derby://localhost:1527/chapter4DB;create=true""/&gt;
        &lt;property name=""javax.persistence.sql-load-script-source"" value=""insert.sql""/&gt;
        &lt;property name=""show_sql"" value=""true""/&gt;
        &lt;property name=""dialect"" value=""org.hibernate.dialect.DerbyDialect""/&gt;
    &lt;/properties&gt;
&lt;/persistence-unit&gt;
</code></pre>

<p></p>

<p><strong>Test.class</strong></p>

<pre><code>private static EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(""test"");
private EntityManager entityManager;
private EntityTransaction transaction;

@Before
public void initEntityManager() throws Exception {
    entityManager = entityManagerFactory.createEntityManager();
    transaction = entityManager.getTransaction();
}

@After
public void closeEntityManager() throws Exception {
    if(entityManager != null){
        entityManager.close();
    }
}

@Test
public void shouldFindJavaEE7Book() throws Exception {
    Book book = entityManager.find(Book.class, 1001L);
    assertEquals(""Beginning Java EE 7"", book.getTitle());
}
</code></pre>

<p><strong>pom.xml</strong></p>

<pre><code>&lt;dependencies&gt;
&lt;dependency&gt;
  &lt;groupId&gt;org.jboss.weld.se&lt;/groupId&gt;
  &lt;artifactId&gt;weld-se&lt;/artifactId&gt;
  &lt;version&gt;2.4.1.Final&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
  &lt;artifactId&gt;hibernate-validator&lt;/artifactId&gt;
  &lt;version&gt;5.0.0.Final&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;org.apache.derby&lt;/groupId&gt;
  &lt;artifactId&gt;derbyclient&lt;/artifactId&gt;
  &lt;version&gt;10.11.1.1&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;org.hibernate.javax.persistence&lt;/groupId&gt;
  &lt;artifactId&gt;hibernate-jpa-2.1-api&lt;/artifactId&gt;
  &lt;version&gt;1.0.0.Final&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;junit&lt;/groupId&gt;
  &lt;artifactId&gt;junit&lt;/artifactId&gt;
  &lt;version&gt;4.12&lt;/version&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;
</code></pre>

<p><strong>Error when unit testing</strong></p>

<pre><code>java.lang.ExceptionInInitializerError
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.junit.runners.BlockJUnit4ClassRunner.createTest(BlockJUnit4ClassRunner.java:217)
at org.junit.runners.BlockJUnit4ClassRunner$1.runReflectiveCall(BlockJUnit4ClassRunner.java:266)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: javax.persistence.PersistenceException: No Persistence provider for EntityManager named test
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:61)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
at org.agonical.book.BookIT.&lt;clinit&gt;(BookIT.java:19)
... 21 more
</code></pre>

<p>The <code>persistence.xml</code> is located in the <code>src/test/resources/META-INF</code> dir. I did have the test <code>persistence-unit</code> in the one <code>persistence.xml</code> file in <code>src/main/resources/META-INF</code> dir.
Each ends with the same result. I have been doing numerous research online and from what I can see I am doing everything correctly and don't understand why this is not working.</p>

<p>Any help would be greatly appreciated.</p>
",https://stackoverflow.com/questions/46942234/hibernate-maven-project-no-persistence-provider-for-entitymanager-named,"['java', 'hibernate', 'maven', 'jpa', 'derby']",1924,TRUE,1,1
How to unit test that an event of a class is subscribed when mocking is not possible,"<p>Is it possible to check via unit testing, if the event is subscribed  or not when mocking is not possible.</p>

<p>I have following class ""InteractiveEventManager"" which takes a class called DrawingArea. The class implements IEventManager which has two methods - Subscribe() and UnSubscribe();</p>

<p>Subscribe method subscribes custom events from DrawingArea class. </p>

<p>Now I am not sure how to check if the Subscribe method has subscribed those events?</p>

<pre><code>internal interface IEventManager
{
    void Subscribe();
    void UnSubscribe();
}

public class InteractiveEventManager: IEventManager
{
    private readonly DrawingArea _drawingArea;   
        public InteractiveEventManager(DrawingArea drawingArea)
    {
        _drawingArea = drawingArea;
    }

    public void Subscribe()
    {
        _drawingArea.MouseMove += DrawingAreaMouseMove;
        _drawingArea.PreviewMouseDown += DrawingAreaPreviewMouseDown;
    }

    private void DrawingAreaPreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        _drawingArea.Chart.InteractiveCurvesArea.ProcessMouseDown(
            e.GetPosition(_drawingArea));
    }

    private void DrawingAreaMouseMove(object sender, MouseEventArgs e)
    {
        _drawingArea.Chart.InteractiveCurvesArea.ProcessMouseMove(
            e.GetPosition(_drawingArea));
    }
}
</code></pre>

<p>I have written following test but it does not work. Since, DrawingArea is a class(not an interface), I think we cannot call AssertWasCalled. Can you please help.</p>

<pre><code>[Test]
public void When_register_then_drawing_area_mouse_move_is_registered()
{
    DrawingArea drawingArea = new DrawingArea();
    InteractiveEventManager interactiveEventManager = 
        new InteractiveEventManager(drawingArea);
    interactiveEventManager.Subscribe();

    drawingArea.AssertWasCalled(x =&gt; x.MouseMove += 
        Arg&lt;MouseEventHandler&gt;.Is.Anything);
}
</code></pre>

<p>Thanks.</p>
",https://stackoverflow.com/questions/46285416/how-to-unit-test-that-an-event-of-a-class-is-subscribed-when-mocking-is-not-poss,['c#'],118,FALSE,1,0
JUnit exception handling not working,"<p>I'm new to unit testing and I'm trying to learn JUnit. Handling exceptions in tests is not working in my project. Here is my class:</p>

<pre><code>public class Things {

  private int amount;
  private int[] weights;
  private int[] values;

  public Things(int amount, int[] weights, int[] values){
    this.amount = amount;
    if (amount!=weights.length || amount != values.length){
        throw new IllegalArgumentException(""Amount of things different than weights or values length"");
    }
    this.weights=weights;
    this.values=values;
  }
}
</code></pre>

<p>and Test class: </p>

<pre><code>public class ThingsTest {

@Test
public void testThingsConstructorIllegalArgumentsException(){
    boolean exceptionThrown = false;
    try{
        Things thingsBadParams = new Things(5, new int[]{4,3,2}, new int[]{7,8});
    }
    catch (IllegalArgumentException e){
        exceptionThrown = true;
    }
    Assert.assertTrue(exceptionThrown);
}
}
</code></pre>

<p>I know that maybe this isn't the best way to handle exception, but that's not the point. I've tried probably every solution (with @Rule, @Test(expected=IllegalArgumentException.class) and still every time the test is failing, there is a red bar and description below it:</p>

<pre><code>java.lang.IllegalArgumentException: Amount of things different than weights or values length

at pl.dsdev.Things.&lt;init&gt;(Things.java:14)
at ThingsTest.&lt;init&gt;(ThingsTest.java:11) 
</code></pre>

<p>I'm using IntelliJ Idea 2017, Maven and JUnit 4.12. What should I do to make test successful? </p>
",https://stackoverflow.com/questions/47485371/junit-exception-handling-not-working,"['java', 'maven', 'junit', 'exception']",471,TRUE,1,2
Test if a component is passing an @Input to another,"<p>I'm fairly new to unit testing. I wonder how I could test if a smart component is passing some as an <code>@Input()</code> to a dumb one (using Angular 4+).</p>

<p>At first, I thought about checking if the property exists:</p>

<pre><code>it('should have some data', async(() =&gt; {
  expect(component.data).toBeTruthy();
}));
</code></pre>

<p>However, I faced two issues: 1) that tells me if <code>data</code> is true but doesn't necessarily means it's being passed as an input to my dumb component; 2) if the <code>data</code> property doesn't exist, then the test suite won't be executed.</p>

<p>Any tips? Is there a better way to approach this? Thanks.</p>
",https://stackoverflow.com/questions/46352618/test-if-a-component-is-passing-an-input-to-another,"['javascript', 'angular', 'unit-testing', 'typescript']",819,TRUE,1,1
Python - Access to a protected member _ of a class,"<p>Given a class with some protected members and a public interface to modify them, when is it generally accepted to access the protected members directly? I have some specific examples in mind:</p>

<ol>
<li>Unit testing</li>
<li>Internal private methods such as __add__ or __cmp__ accessing other's protected attributes</li>
<li>Recursive data structures (e.g. accessing next._data in a linked list)</li>
</ol>

<p>I don't want to make these attributes public as I don't want them touched publicly. My syntax IDE syntax highlighting keeps saying that I'm wrong with accessing protected members - who is right here?</p>

<p><strong>EDIT</strong> - adding a simple example below:</p>

<pre><code>class Complex:
    def __init__(self, imaginary, base):
        self._imaginary = imaginary
        self._base = base

    def __str__(self):
        return ""%fi + %f"" % self._base, self._imaginary

    def __add__(self, other):
        return Complex(self._imaginary + other._imaginary, self._base + other._base)
</code></pre>

<p>Pycharm highlights <em>other._imaginary</em> and <em>other._base</em> with the following:</p>

<blockquote>
  <p>Access to a protected member _imaginary of a class</p>
</blockquote>
",https://stackoverflow.com/questions/42736044/python-access-to-a-protected-member-of-a-class,"['python', 'oop', 'attributes', 'protected']",30228,TRUE,17,1
Travis CI testing AngularJS directive with Karma/Jasmine/PhantomJS results in &quot;undefined is not a function&quot;,"<p>I'm unit testing an AngularJS directive using Karma/Jasmine/PhantomJS stack and have all successes locally, but when I run it on Travis CI it results in errors:</p>

<pre><code>PhantomJS 2.1.1 (Linux 0.0.0) test description... FAILED
    TypeError: undefined is not a function (evaluating 'angular.element(directiveInput).val('').trigger('input')') in test/tests.spec.js (line 63)
</code></pre>

<p>Here is my .travis.yml file:</p>

<pre><code>language: node_js
node_js:
  - ""node""
before_script:
  - npm install -g gulp-cli
  - npm install -g bower
  - bower install
script:
  - gulp test
os: linux
</code></pre>

<p>And the Gulp task:</p>

<pre><code>var gulp = require('gulp');
var Server = require('karma').Server;
gulp.task('test', function(done) {
    new Server({
        configFile: __dirname + '/karma.conf.js',
        singleRun: true
    }, done).start();
});
</code></pre>

<p>I tried commenting out the code that throws the error, just to see if that'd give some insight into what's going on. It resulted in a different error:</p>

<pre><code>PhantomJS 2.1.1 (Linux 0.0.0) test description... FAILED
    ReferenceError: Can't find variable: $ in test/tests.spec.js (line 34)
</code></pre>

<p>With that in mind I think it may have something to do with jQuery, but I don't really know how Travis CI works. Any help would be appreciated.</p>
",https://stackoverflow.com/questions/44853611/travis-ci-testing-angularjs-directive-with-karma-jasmine-phantomjs-results-in-u,"['angularjs', 'jasmine', 'phantomjs', 'karma-runner', 'travis-ci']",93,FALSE,1,0
Jest/enzyme: How to test for .then and .catch of an nested asynchronous function,"<p>I'm trying to do some enzyme/jest unit testing for a asynchronous function in my reactJS component, which gets injected as prop.</p>

<p>My Problem is to test for a value in the <code>then()</code> part of the function and to test for <code>catch()</code> if an error occures.</p>

<p>This is how the function of my component (<code>&lt;CreateAccount /&gt;</code>) looks like:</p>

<pre><code>_onSubmit = (event) =&gt; {
  event.preventDefault()
  const { username, password } = this.state

  this.props.createUserMutation({
    variables: { username, password }
  }).then(response =&gt; {
    const token = response.data.createUser.token
    if (token) {
      Cookies.set('auth-token', token, { expires: 1 })
    }
  }).catch(error =&gt; {
    console.warn(error)
  })
}
</code></pre>

<p>The first test should check for <code>.catch(error =&gt; {})</code> as data is undefined:</p>

<pre><code>it('_onSubmit() should throw error if data is missing', () =&gt; {
  const createUserMutation = () =&gt; {
    return Promise.resolve({})
  }
  const wrapper = shallow(&lt;CreateAccount createUserMutation={createUserMutation} /&gt;)
  wrapper.update().find(Form).simulate('submit', {
    preventDefault: () =&gt; {}
  })
  const state = wrapper.instance().state
  expect(wrapper).toThrow() // &lt;-- How to do it correctly?
})
</code></pre>

<p>And the second test should check if cookie is set correctly. Here I don't know how to do that? I think I have to mock <code>Cookie</code></p>

<pre><code>it('_onSubmit() should get token', () =&gt; {
  const createUserMutation = () =&gt; {
    return Promise.resolve({
      data: {
        createUser: { token: 'token' }
      }
    })
  }
  const wrapper = shallow(&lt;CreateAccount createUserMutation={createUserMutation} /&gt;)
  wrapper.find(Form).simulate('submit', {
    preventDefault: () =&gt; {}
  })
  // How to check for token value and Cookies?
})
</code></pre>
",https://stackoverflow.com/questions/47214302/jest-enzyme-how-to-test-for-then-and-catch-of-an-nested-asynchronous-function,"['javascript', 'reactjs', 'unit-testing', 'asynchronous', 'enzyme']",6100,TRUE,1,2
How do you dynamically populate a PrincipalSearchResult&lt;Principal&gt; collection?,"<p>I'm doing some unit testing and I need to create a test collection of the type <code>PrincipalSearchResult&lt;Principal&gt;</code>.  This collection is normally returned when you use the method call <code>UserPrincipal.GetAuthorizationGroups()</code>.  </p>

<p>This type is part of the <code>System.DirectoryServices.AccountManagement</code> namepsace which houses code for querying Microsoft's Active Directory.</p>

<p>If I try to simply create a new collection like such, I get an error:</p>

<pre><code>PrincipalSearchResult&lt;Principal&gt; restResult = new PrincipalSearchResult&lt;Principal&gt;();
</code></pre>

<blockquote>
  <p><em>Error message: <code>PrincipalSearchResult&lt;Principal&gt;</code> does not contain a constructor that takes 0 arguments.</em></p>
</blockquote>

<p>But I'm not getting any Intellisense when newing-up the collection that indicates what parameters to pass the constructor.</p>

<p>How can I create and populate this type?</p>
",https://stackoverflow.com/questions/46029160/how-do-you-dynamically-populate-a-principalsearchresultprincipal-collection,"['c#', '.net', 'active-directory']",439,TRUE,1,1
Neo4j in memory db,"<p>I saw Neo4j can run as Impermanent DB for unit testing porpouses, I'm not sure if this fits my needs. I have my data stored in neo4j the usual way (persistent) but, starts from my data, I want to let each user start an ""experimental session"": the users add/delete nodes and relationships, but NOT in permanent way, just experimenting with the data (after that session the edits should be lost). The edits shouldn't be saved and obiouvsly they shouldn't be visibile to the others. What's the best way to accomplish that?</p>
",https://stackoverflow.com/questions/44866745/neo4j-in-memory-db,"['spring-boot', 'neo4j', 'spring-data-neo4j', 'network-analysis']",629,TRUE,1,2
xamarin android uitest theme style conflicts,"<p>Recently I asked a question over trying to get my theme recognized within the android test project: <a href=""https://stackoverflow.com/questions/45000812/unit-testing-a-xamarin-forms-android-specific-code-project"">Unit testing a Xamarin Forms Android specific code project</a></p>

<p>I'm not running into a conflict that shows up within <code>xunit</code> / <code>nunit</code> as the testing strategy. I feel like it's because the <code>FormsAppCompatActivity</code> with an older activity type, but I'm new to Xamarin and am unsure on how to approach this.</p>

<p>I get a lot of these type of errors:</p>

<p><code>Attribute ""layout_anchorGravity"" already defined with incompatible format.</code></p>

<p>The full list of the similar Attribute errors is:</p>

<pre><code> fabSize
 tabMode
 expandedTitleGravity
 layout_scollFlags
 layout_collapseMode
 collapsedTitleGravity
 tabGravity
 showDividers
 displayOptions
 showAsActions
 actionBarSize
</code></pre>

<p>finally I have the addition error:
<code>Found tag styles where item is expected</code></p>

<pre><code>//Within the Android Forms project, I have this inheritance:
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity {
    // typical code
}

//within the Android UITest project
public class MainActivity : Xunit.Runners.UI.RunnerActivity {
    // tests can be inside the main assembly
    AddTestAssembly(Assembly.GetExecutingAssembly());

    AddExecutionAssembly(typeof(ExtensibilityPointFactory).Assembly);
    // or in any reference assemblies           

    //AddTestAssembly(typeof(PortableTests).Assembly);
    // or in any assembly that you load (since JIT is available)

#if false
    // you can use the default or set your own custom writer (e.g. save to web site and tweet it ;-)
    Writer = new TcpTextWriter (""10.0.1.2"", 16384);
    // start running the test suites as soon as the application is loaded
    AutoStart = true;
    // crash the application (to ensure it's ended) and return to springboard
    TerminateAfterExecution = true;
#endif
    // you cannot add more assemblies once calling base
    base.OnCreate(bundle);
 }
</code></pre>
",https://stackoverflow.com/questions/45070750/xamarin-android-uitest-theme-style-conflicts,"['xamarin', 'xamarin.android', 'xamarin.forms', 'xunit']",89,FALSE,1,0
visual studio: How to ignore pdb not loaded warnings during debug?,"<p>While debugging, I do not want visual studio to be looking for *.pdb files from 3rd party *.dlls. For example I use Jetbrains Resharper TaskRunner for unit testing. To use it requires a reference to Jetbrains.Resharper.TaskRunnerFramework.dll. When I debug my application via the TaskRunner, I end up with something similar to this picture below:</p>

<p><a href=""https://i.stack.imgur.com/731u8.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/731u8.png"" alt=""enter image description here""></a></p>

<p>Well, I'm not debugging the task runner. That isn't my code anyhow. I want Visual Studio to be ""smart"" enough (or have a setting) to automatically know to NOT concern itself with *.pdb files for anything that isn't my code. Is this possible?</p>
",https://stackoverflow.com/questions/47336792/visual-studio-how-to-ignore-pdb-not-loaded-warnings-during-debug,"['c#', 'visual-studio']",3810,TRUE,6,2
How to configure docker daemon for test enviroment,"<p>I try to setup unit testing agains database with docker. I use library, that runs database image during tests. <a href=""https://github.com/testcontainers/testcontainers-java/blob/master/docs/usage.md"" rel=""nofollow noreferrer"">Docs</a> says:</p>

<blockquote>
  <p>Testcontainers will try to connect to a Docker daemon using the
  following strategies in order:</p>
  
  <p>Environment variables:  </p>

<pre><code>DOCKER_HOST (this should be set to an
HTTP/HTTPS connection rather than a unix socket at present)

DOCKER_TLS_VERIFY
DOCKER_CERT_PATH
</code></pre>
  
  <p>Defaults:</p>

<pre><code>DOCKER_HOST=https://localhost:2376
DOCKER_TLS_VERIFY=1
DOCKER_CERT_PATH=~/.docker
</code></pre>
  
  <p>If Docker Machine is installed, the docker machine environment for the
  first machine found. Docker Machine needs to be on the PATH for this
  to succeed.</p>
</blockquote>

<p>I have docker installed in Ubuntu 16.04, but dont understund how to configure docker daemon to use with this testing library. Any helps?</p>
",https://stackoverflow.com/questions/47070469/how-to-configure-docker-daemon-for-test-enviroment,"['docker', 'testcontainers']",732,FALSE,1,1
Should I (statically) type-check Third-party codes (e.g. using Flow)?,"<p>I had this question particularly while I was writing my first unit test. It doesn't seem right to statically type check these third-party codes, for instance the return values type of Enzyme/React test utils functions and test framework's callback function type.</p>

<p>I just thought that third-party APIs are like (this)[<a href=""https://github.com/airbnb/enzyme/blob/master/docs/api/shallow.md#shallowwrapper-api]"" rel=""nofollow noreferrer"">https://github.com/airbnb/enzyme/blob/master/docs/api/shallow.md#shallowwrapper-api]</a> are too long and very likely to be tested.</p>

<p>EDIT: clarified that when I said type-check, I mean by static type-checking like Flow, and not thru unit-testing.</p>
",https://stackoverflow.com/questions/43905972/should-i-statically-type-check-third-party-codes-e-g-using-flow,"['javascript', 'unit-testing', 'types', 'tdd', 'typechecking']",54,FALSE,0,2
Angular Unit Test Factory .catch(),"<p>I'm unit testing a factory for a 400 response and I don't understand why the .catch() response in the test case is undefined. The test is failing when the promise is chained with .catch() because the response is undefined but succeeds if .then() is used. Why is this $q.reject() response not passed to the .catch() function? I see that the .catch() block in the factory is receiving the $.reject() but when the response is returned in the unit test .catch is undefined.</p>

<p><strong><em>factory</em></strong></p>

<pre><code>function resetTempPassword(data) {
  return $http.post('/reset_temp_password', data)
  .then(function(response) {
    console.log('inside then');
    console.log(response);
    return response;
  })
  .catch(function(response) {
    console.log('inside catch');
    console.log(response);
    return response;
  });
}
</code></pre>

<p><strong><em>test</em></strong></p>

<p>describe('resetTempPassword()', function() {
    var result;</p>

<pre><code>beforeEach(function() {
  // init local result
  result = {};
  ...

it('should return 400 when called with invalid temp password', function() {
  $httpBackend.expectPOST('/reset_temp_password', RESET_TEMP_INVALID).respond(400, RESET_TEMP_ERROR);
  $httpBackend.whenPOST(API, RESET_TEMP_INVALID).respond(400, $q.reject(RESET_TEMP_ERROR));

  expect(idmAdminFactory.resetTempPassword).not.toHaveBeenCalled();
  expect(result).toEqual({});

  idmAdminFactory.resetTempPassword(RESET_TEMP_INVALID)
  .catch(function(response) {
    result = response;
  });
  // flush pending HTTP requests
  $httpBackend.flush();

  expect(idmAdminFactory.resetTempPassword).toHaveBeenCalledWith(RESET_TEMP_INVALID);
  expect(result.data.code).toEqual(40008); // result.data is undefined
</code></pre>
",https://stackoverflow.com/questions/45174391/angular-unit-test-factory-catch,"['angularjs', 'unit-testing']",42,FALSE,0,1
"Performance, load and stress testing in Django","<p>I am studying the different types of testing for a Django application. I know how to do functional and unit testing in Django and how to apply different methodologies, but now I am facing a new challenge, I need to know how to do:</p>

<ul>
<li>Performance testing</li>
<li>Load testing</li>
<li>Stress testing</li>
</ul>

<p>I <strong>know the difference between them</strong> but I dont know which is the best methodology to follow,which are the best packages for do it or simply where I can get some <strong>documentation</strong> about it. </p>

<p>So my question is, how can I start to do these types of tests in a Django app or where can I get some good documentation about it?</p>

<p>Thanks </p>
",https://stackoverflow.com/questions/46893226/performance-load-and-stress-testing-in-django,"['python', 'django', 'testing', 'performance-testing']",12373,TRUE,16,1
Accessing angular service constructor in Jest testing framework,"<p>I'm struggling to find an answer to the following (and I'll bet it's more than likely that the answer is relatively straightforward)...</p>

<p>I'm unit testing an Ionic 3.4 application using the Jest testing framework and can't figure out how to call an angular service for testing where the constructor initialises the Http object and an InAppBrowser Ionic Native plugin object.</p>

<p>My <strong>package.json</strong> file contains the following configuration:</p>

<pre><code>...
""jest"": {
    ""transform"": {
        "".(ts|tsx)"": ""&lt;rootDir&gt;/node_modules/ts-jest/preprocessor.js""
    },
    ""testRegex"": ""(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$"",
    ""moduleFileExtensions"": [
        ""ts"",
        ""tsx"",
        ""js"",
        ""json""
    ]
},
""devDependencies"": {
    ""@types/jest"": ""^20.0.2"",
    ""@types/node"": ""^7.0.31"",
    ""jest"": ""^20.0.4"",
    ""ts-jest"": ""^20.0.6"",
    ""ts-node"": ""^3.0.6"",
    ""tslint"": ""^5.4.3"",
    ""tslint-eslint-rules"": ""^4.1.1"",
    ""typescript"": ""2.3.3""
},
...
</code></pre>

<p>My <strong>tsconfig.json</strong> file, located in the src/unit-tests directory (so as to only target that directory and its contents and not interfere with the root tsconfig.json file for the Ionic project), is as follows:</p>

<pre><code>{
    ""compilerOptions"" : {
        ""module""                        : ""commonjs"",
        ""allowSyntheticDefaultImports""  : true,
        ""experimentalDecorators""        : true,
        ""noImplicitAny""                 : false,
        ""removeComments""                : false,
        ""locale""                        : ""en-GB"",
        ""alwaysStrict""                  : true,
        ""skipLibCheck""                  : true,
        ""pretty""                        : true
    }
}
</code></pre>

<p>The requested service - <strong>providers/settings/settings.ts</strong> - is as follows:</p>

<pre><code>import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { InAppBrowser } from '@ionic-native/in-app-browser';
import 'rxjs/add/operator/map';


@Injectable()
export class SettingsProvider {

constructor(public http     : Http,
            private _INAPP  : InAppBrowser) 
{  }

// Methods follow here
}
</code></pre>

<p>This is then used within the <strong>settings.test.ts</strong> file like so:</p>

<pre><code>import 'reflect-metadata';
import { SettingsProvider } from '../providers/settings/settings';


let settings = null;

beforeEach(() =&gt; {
  // The following works IF the SettingsProvider class 
  // contains NO parameters in the constructor
  settings = new SettingsProvider();
});



describe('Settings service', () =&gt; 
{
    // Tests are defined within here
    // using methods supplied by the 
    // SettingsProvider class
});
</code></pre>

<p>IF I take the parameters out of the SettingsProvider class constructor Jest can run the tests exactly as intended (pass or fail).</p>

<p>With the parameters in place inside the SettingsProvider class constructor Jest chokes when trying to run the test script with the following error:</p>

<pre><code> Test suite failed to run

/ionic-unit/node_modules/@ionic-native/in-app-browser/index.js:20
import { Injectable } from '@angular/core';
^^^^^^
SyntaxError: Unexpected token import

  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/ScriptTransformer.js:289:17)
  at Object.&lt;anonymous&gt; (src/providers/settings/settings:12:21)
  at Object.&lt;anonymous&gt; (src/unit-tests/settings.test.ts:2:18)
</code></pre>

<p>How do I configure my test script so that Jest recognises the modules that are initialised in the SettingsProvider constructor?</p>

<p>I'm relatively new to unit testing and have been trying to figure out how to accomplish this (but, as you can tell, without much joy so far!)</p>

<p>I appreciate any guidance/advice any developers out there might have on the matter.</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/44833608/accessing-angular-service-constructor-in-jest-testing-framework,"['unit-testing', 'typescript', 'ionic2', 'ionic3', 'jestjs']",1705,FALSE,1,1
Reliability of algorithm performance testing based on unit framework,"<p>For my PhD I am writing a DEM (Discrete Element Method) simulation in c++ describing particle flow which is computational intensive. I have a lot of different algorithms in place for the calculation of different parameters. The run time per algorithm can vary significantly based on the configuration of points (where the number of points stay the same). For testing, a good amount of unit tests are in place with different configurations and number of points.</p>

<p>For optimization and performance testing it seems easiest to run the specific unit tests multiple times, under the assumption that the time required by the unit testing framework is constant I can compare different algorithm performances against each other. So in pseudo code I want to do this, where algorithm1 and algorithm2 are different implementations of a single algorithm and the different unitTests are different input configurations:</p>

<pre><code>//Preformance test algorithm1
timer = 0;
startTimer();
for(n = 1000) {
     unitTest1(algorithm1);
     unitTest2(algorithm1);
     .....
 }
 print(timer);

//Performance test algorithm2
timer = 0;
startTimer();
for(n = 1000) {
     unitTest1(algorithm2);
     unitTest2(algorithm2);
     .....
 }
 print(timer);
</code></pre>

<p><strong>Question:</strong> Is this a valid way to do performance testing that will yield reliable and comparable results or can the unit testing framework invalidate my results in some way? Also can this method be extended to test performance when the code is written for parallel processing.</p>

<p>Additional information: The unit framework I am using is the Boost Test Library and due to long run times I cannot efficiently performance test the code as a whole with different configurations.</p>
",https://stackoverflow.com/questions/44676535/reliability-of-algorithm-performance-testing-based-on-unit-framework,"['c++', 'algorithm', 'performance', 'unit-testing', 'time']",172,TRUE,1,1
Accessing the view which has the dependecy,"<p>I have two js files, in which one view in a separate file. I am testing it using Jasmine unit testing. I have the js files included in the jasmine.html page. I am able to access everything other than the following view. The problem I am facing is when I tried to access the view from the console it says that app.TodoView is not a constructor where I am doing wrong?
Also I have a dependency in another file </p>

<pre><code>var app = app || {};
app.TodoView = Backbone.View.extend({
tagName: ""li"",
template: _.template($(""#item-template"").html()),

initialize: function() {

    this.render();
},

render: function() {

    console.log(""rendering"");
    console.log(this.collection);
    var template = _.template($(""#item-template"").html())
    template = this.template({
        persons: this.collection.toJSON()
    });
    $('#todo-list').html(template);
    this.$el.html(template);

    return this;
},

});
app.TodoView = new app.TodoView()
</code></pre>

<p>Dependency(in another js file under another view) ----
    app.TodoView = new app.TodoView({
       collection : data
    });</p>
",https://stackoverflow.com/questions/45869663/accessing-the-view-which-has-the-dependecy,"['javascript', 'backbone.js', 'jasmine2.0']",32,FALSE,0,0
IllegalArgumentException in Enhancer.setCallbacksHelper() while using .createMock with EasyMock,"<p>I encounter a problem during unit testing with EasyMock. When trying to create a mock object, the following Exception is thrown:</p>

<pre><code>java.lang.IllegalArgumentException: class  ...UnitOfWork$$EnhancerByCGLIB$$3561f3ca is not an enhanced class
    at net.sf.cglib.proxy.Enhancer.setCallbacksHelper(Enhancer.java:621)
    at net.sf.cglib.proxy.Enhancer.setThreadCallbacks(Enhancer.java:612)
    at net.sf.cglib.proxy.Enhancer.registerCallbacks(Enhancer.java:581)
    at org.easymock.internal.ClassProxyFactory.createProxy(ClassProxyFactory.java:194)
    at org.easymock.internal.MocksControl.createMock(MocksControl.java:60)
    at org.easymock.EasyMock.createMock(EasyMock.java:104)
    at testplugin.Test.testMethod(Test.java:65)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.internal.runners.s
</code></pre>

<p>What makes a class enhanced? And what is the Enhancer doing anyways (I don't know what <code>net.sf.cglib.proxy</code>package is about) And why is it not working for this class, but for another mock object directly created before this object?</p>

<pre><code>Mock1 mock1 = EasyMock.createMock(Mock1.class);
UnitOfWork mockUow = EasyMock.createMock(UnitOfWork.class); // Exception Happening here
</code></pre>

<p>Used versions are <code>easymock-3.0.jar</code> and <code>cglib-nodep-2.2.jar</code>. 
<code>UnitOfWork</code> is not a final class. The only thing that might be different are transient fields. Sadly I can't provide the code or recreate the Exception with another class.</p>
",https://stackoverflow.com/questions/45280803/illegalargumentexception-in-enhancer-setcallbackshelper-while-using-createmoc,"['java', 'junit', 'mocking', 'easymock', 'cglib']",346,FALSE,0,1
PHPUnit - Mark test as failed when two related functions fail,"<p>I started using PHPUnit for unit testing recently and I structured my tests to check correct behavior when a function succeeds and fails.</p>

<p>For example I could test function <code>connectToDevice()</code> expecting that when connection succeeds it returns <code>true</code>, otherwise it returns <code>false</code>. Then I would have:</p>

<pre><code>public function testConnectToDeviceSuccess()
{
    $this-&gt;assertTrue($this-&gt;myObject-&gt;connectToDevice());
}

public function testConnectToDeviceFailure()
{
    $this-&gt;assertFalse($this-&gt;myObject-&gt;connectToDevice());
}
</code></pre>

<p>At the moment one of those function will necessarily fail, then PHPUnit will report me 1 fail. Instead I would set it to mark test failed only when both functions fail. Therefore when 1 succeeds the other will be skipped.</p>

<p>Is this possible in PHPUnit maintaining those tests in two different functions?</p>
",https://stackoverflow.com/questions/44821446/phpunit-mark-test-as-failed-when-two-related-functions-fail,"['php', 'unit-testing', 'phpunit']",445,TRUE,0,2
lambda with more than one effect,"<p>I have three different classes of some common interface <code>Bag</code>. Those are simple containers with some properties. I can add a bunch of stuff in them, e.g <code>int</code>s. For purposes of unit testing, I wanted to add a number of values to each and every one of those <code>Bag</code>s. So I used the following <code>IntConsumer</code>:</p>

<pre><code>IntStream.rangeClosed(1, 300).forEach(new IntConsumer() {
    @Override
    public void accept(int value) {
        staticBag.add(value);
        shuffledBag.add(value);
        randomAccessBag.add(value);
        }
    });
</code></pre>

<p>My question is how that might be changeable to a lambda expression. <code>Intellij</code> is usually doing a pretty good job at changing those things automatically, but at this point it hasn't been showing me any tips.</p>
",https://stackoverflow.com/questions/43107941/lambda-with-more-than-one-effect,"['lambda', 'java-8']",65,TRUE,0,3
Spring boot: inject mock into Runner class,"<p>I have a spring boot application and some other components which application should interact with. However, in my unit testing I am using just application functionality and I would like to mock outer API calls. I am stuck as I can't find the way to mock case like this:</p>

<p>My start class with main method:</p>

<pre><code>@ComponentScan(""com.sample.application"")
@SpringBootApplication
public class MyApp implements CommandLineRunner {

    @Autowired
    private OuterAPI outerAPI;

    public static void main(String[] args) {
       SpringApplication.run(AdRedirectorMain.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        outerAPI.createInstances();
    }

    ...
}
</code></pre>

<p>And here is my test class example:</p>

<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MyApp.class)
public class MyAppTest {
    // any tests
}
</code></pre>

<p>I am working with Spring Boot, JUnit, Mockito.</p>

<p>So, I am facing the problem - how could I avoid this method call createInstances() with Mockito, via reflection or in any other way.</p>
",https://stackoverflow.com/questions/42236931/spring-boot-inject-mock-into-runner-class,"['java', 'spring', 'spring-boot', 'mockito']",3171,TRUE,0,2
Is it possible to get JavaScript code coverage from protractor and make it into Istanbul report,"<p>Background:
I am working on a AngularJS Project that has 3 kinds of automated testing.
unit testing using jest,
end to end testing using protractor
end to end testing using robot framework</p>

<p>What we want now is to combine code coverage result from jest,protractor and robot framework. and merge it into a single Istanbul report</p>

<p>I would like to ask if 
1. Is it possible to get code coverage results from protractor?
2. Is it appropriate to the things I mention above? Are we supposed to put end to end test into code coverage? </p>
",https://stackoverflow.com/questions/46582376/is-it-possible-to-get-javascript-code-coverage-from-protractor-and-make-it-into,"['angularjs', 'protractor', 'code-coverage', 'e2e-testing', 'istanbul']",332,TRUE,0,1
Change Propel Connection,"<p>I'm trying to configure Propel for unit testing. I have created a second connection for testing purposes, but I haven't been able to figure out how to make propel use it. The connection looks like this:</p>

<pre><code>connectionForTests:
    adapter: mysql
    dsn: mysql:host=localhost;port=3306;dbname=code_test
    user: root
    password: root
    settings:
        charset: utf8
</code></pre>

<p>And I have looked at the propel docs, there's not very much information about how to get propel to actually use a different connection. Do I set an environment variable, run a function on a <code>ConnectionFactory</code>, or something like that?</p>

<p>I'm using Propel2 at <code>dev-master</code>, and I am not using it as a part of Symfony.</p>
",https://stackoverflow.com/questions/42679411/change-propel-connection,['propel'],760,TRUE,0,1
With dependency injection is my DB connection getting disposed?,"<p>I am wondering about how my context is being disposed, or if it is getting disposed at all!
I know I expext the garbage collecter to tidy everything up, but there is something just nagging the back of my mind. </p>

<p>I need to have the conext injected for unit testing</p>

<p>The Questsion, Is my code leaving DB connection open.</p>

<p>My service looks like this, with the context getting passed into the constructor, The dependancy injecting is handled by autofac. </p>

<pre class=""lang-cs prettyprint-override""><code>public class FooService : IFooService 
{
    private readonly Context context;

    public CountryService(Context context)
    {
           this.context = context;
    }

    public IEnumerable&lt;Foo&gt; GetAll()
    {
        return context.Foo.ToList();
    }
}
</code></pre>

<p>My Autofac set up looks like this </p>

<pre><code>public class ServiceModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        // ""ThisAssembly"" means ""any types in the same assembly as the module""
        builder
          .RegisterAssemblyTypes(ThisAssembly)
          .Where(t =&gt; t.Name.EndsWith(""Service""))
          .WithParameter(""context"", new MyContext())
          .AsImplementedInterfaces();
    }
}
</code></pre>

<p>I Have seen on solution to add IDisposable</p>

<pre><code>public class FooService : IFooService , IDisposable
{
    private readonly Context context;

    public CountryService(Context context)
    {
        this.context = context;
    }

    public IEnumerable&lt;Foo&gt; GetAll()
    {
        return context.Foo.ToList();
    }

    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                context.Dispose();
            }
        }
        this.disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}
</code></pre>
",https://stackoverflow.com/questions/42762917/with-dependency-injection-is-my-db-connection-getting-disposed,"['c#', 'entity-framework', 'dependency-injection', 'autofac']",1442,FALSE,0,2
Why (and how ?) does sqlalchemy bypass FK constrainsts with sqlite?,"<p>While I was doing unit testing, I wrote some code that I knew wouldn't pass because of foreign constrainst... Except it did.</p>

<p>This is an example : </p>

<pre><code>import os
import sqlalchemy as sa
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base, declared_attr
import logging
logging.basicConfig()
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)

try:
  os.unlink('test.db')
except:
  pass
engine = create_engine('sqlite:///test.db')

Base = declarative_base()

class Test1(Base):
  __tablename__ = 'Test1'
  id = sa.Column(sa.Integer(), primary_key = True)

class Test2(Base):
  __tablename__ = 'Test2'
  id = sa.Column(sa.Integer(), primary_key = True)
  link = sa.Column(sa.Integer(), sa.ForeignKey(Test1.id), index = True)

Base.metadata.create_all(engine)

Session = sessionmaker()

session = Session(bind=engine)

session.add(Test2(id=1, link=2)) # &lt;-- should raise an error because 2 not in Test1
session.commit()
session.add(Test1(id=1))
session.commit()
session.add(Test2(id=2, link=1)) #ok
session.commit()
session.add(Test2(id=3, link=42)) # &lt;-- should raise an error because 42 not in Test1
session.commit()
</code></pre>

<p>I declare a simple database, a table <code>Test1</code> with a PK <code>id</code>, and a second table <code>Test2</code> with a PK id and a FK constrainst on <code>Test2.link</code> to reference <code>Test1.id</code>. Then, I insert some values that would break the FK.</p>

<p>The FK seems to work because if I open a sqlite db browser, I can't put these same values...</p>

<p>Why and how sqlalchemy bypasses the FK ?</p>

<p>Note : I haven't tried on another db</p>
",https://stackoverflow.com/questions/47916856/why-and-how-does-sqlalchemy-bypass-fk-constrainsts-with-sqlite,"['python', 'sqlite', 'sqlalchemy']",69,TRUE,0,1
python unit test - how to test function local JSON object has correct key value pairs?,"<p>I'm new to Python and unit testing as I just started looking into it this morning. I have a object that has a number of key/pair values as well as one of those key/pairs being another object.</p>

<p>ie.</p>

<pre><code>my_program.py

    def my_function(self):
        my_obj = {
            ""someKey"": 1234-5678,
            ""locationId"": self.location_id,
            ""environment"": self.environment_name,
            ""metaData"" : {
                ""log_id"": self.last_log_id,
                ""satisfied"": False 
            }
        }


tests_my_program.py

import unittest2
import mock

    def test_should_check__my_function__payload_obj_is_set(self):
        #code here to test the variable has all of those key/pair values
</code></pre>

<p>How do I write a unit test to ensure that this object always has these key/pair values (someKey, locationId, etc.) ? <strong>My tests are in a separate python file (test_my_program.py) so would i need to mock my_obj to the test function?</strong></p>

<p>This variable is local to a function so it's not global.</p>
",https://stackoverflow.com/questions/45428164/python-unit-test-how-to-test-function-local-json-object-has-correct-key-value,"['python', 'json', 'unit-testing', 'unittest2']",2734,TRUE,0,1
Unit test in Unity - Getting an InvalidCastException - Why? And how to fix?,"<p>I try to be as specific and helpful as possible in my questions here on S.O. but for this one, well, that means almost nothing, as I have absolutely no hint of the faintest clue about why this is happening.</p>

<p>It happens on any/every test (even ""blank"" ones). And I already tried (uninstalling and) updating unity. - Didn't work.</p>

<p>Anyways, here is the stacktrace of the exception:</p>

<pre><code>2017.11.16 14:54:24.308   ERROR System.Reflection.TargetInvocationException: Uma exceção foi acionada pelo destino de uma chamada.
System.Reflection.TargetInvocationException: Uma exceção foi acionada pelo destino de uma chamada. ---&gt; System.InvalidCastException: Não é possível converter um objeto do tipo 'NUnit.Engine.CallbackHandler' no tipo 'System.Web.UI.ICallbackEventHandler'.
   em NUnit.Framework.Api.FrameworkController.LoadTestsAction..ctor(FrameworkController controller, Object handler)
   --- Fim do rastreamento de pilha de exceções internas ---
   em System.RuntimeMethodHandle._InvokeConstructor(Object[] args, SignatureStruct&amp; signature, IntPtr declaringType)
   em System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   em System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
   em System.Activator.CreateInstance(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo, StackCrawlMark&amp; stackMark)
   em System.Activator.CreateInstance(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo)
   em System.AppDomain.CreateInstance(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityAttributes)
   em System.AppDomain.CreateInstanceAndUnwrap(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityAttributes)
   em NUnit.Engine.Drivers.NUnit3FrameworkDriver.Load(String testAssemblyPath, IDictionary`2 settings)
   em NUnit.Engine.Runners.DirectTestRunner.LoadPackage()
   em NUnit.Engine.Runners.AbstractTestRunner.Load()
   em NUnit.Engine.Runners.MasterTestRunner.LoadPackage()
   em NUnit.Engine.Runners.AbstractTestRunner.EnsurePackageIsLoaded()
   em NUnit.Engine.Runners.MasterTestRunner.NUnit.Engine.ITestRunner.Explore(TestFilter filter)
   em JetBrains.ReSharper.UnitTestRunner.nUnit30.BuiltInNUnitRunner.&lt;&gt;c__DisplayClass1.&lt;RunTests&gt;b__0()
   em JetBrains.ReSharper.UnitTestRunner.nUnit30.BuiltInNUnitRunner.WithExtensiveErrorHandling(IRemoteTaskServer server, Action action)
</code></pre>

<hr>

<p>This is making me pretty much code without (unit-)testing for the last couple of days, so if anyone has any idea about the cause and/or solutions, that would be greatly appreciated.</p>
",https://stackoverflow.com/questions/47335493/unit-test-in-unity-getting-an-invalidcastexception-why-and-how-to-fix,"['unit-testing', 'exception', 'unity-game-engine', 'nunit']",596,TRUE,5,1
Adding a shim to a static method,"<p>I've got some legacy code to add unit testing to. I can add shims where necessary to classes that need instanciating, but some of the code uses static classes. I can't add a shim properly.</p>

<p>for example (simplified for clarity):</p>

<pre><code>public static class DBHelper
    {
        public static ObservableCollection&lt;Run&gt; GetRuns()
        {
            ObservableCollection&lt;Run&gt; retval = new ObservableCollection&lt;Run&gt;();

            using (AriaEntities DBC = new AriaEntities())
            {
                var res = DBC.Runs.OrderByDescending(x =&gt; x.Run_Number).Take(100).ToList();

                retval = new ObservableCollection&lt;Run&gt;(res);
            }

            return retval;
        }
    }
</code></pre>

<p>I want to shim this method. if it was non static, I'd use:</p>

<pre><code> using (ShimsContext.Create())
 {
      ShimDBHelper.AllInstances.GetRuns = (i) =&gt; { return FakeRunList(); };

      ...
 }
</code></pre>

<p>But with a static I get ""'DBHelper': static types cannot be used as parameters"". If I remove the parameter, I get told that the delegate doesn't take 0 arguments.</p>

<p>Whats the syntax for a static class, if there is one? </p>
",https://stackoverflow.com/questions/44705224/adding-a-shim-to-a-static-method,"['c#', 'unit-testing', 'shim']",1537,FALSE,0,0
Creating a reusable component reactjs,"<p>I read an article that creating small reusable components decreases the file size, makes unit testing faster and easier and a lot more. So I'm now trying to create one, however I am very new to reactjs and I'm maintaining this project for a friend, so I haven't written all the code.</p>

<p>Heres a code snippet:</p>

<pre><code>class ObjectKeyDisplay extends Component {
  constructor(props) {
    super(props)
    this.state = { open: false } // Sets open to false (closed)
  }

  renderInner() {
    const { schema, parentDocumentId, collectionName, value } = this.props
    const { open } = this.state // equals const open = this.state.open

    let expandButton
    if (schema.type === 'belongs_to') {
      expandButton = (
        &lt;button onClick={e =&gt; this.setState({ open: !open })}&gt; // Sets it to true (opened)
          {open ? 'Minimera' : 'Expandera'}
        &lt;/button&gt;
      )
    }
</code></pre>

<p>So I basically want to make the whole open/close process to a component, so I easily reuse the logic for other buttons. I would really appreciate if someone could help me out here!</p>
",https://stackoverflow.com/questions/44951037/creating-a-reusable-component-reactjs,"['reactjs', 'components']",366,TRUE,0,1
why am i getting this Error:connect ECONNREFUSED 127.0.0.1:3000 while writing mocha js test,"<p>I have taken a sample random nodejs code named f.js and writing unit test for that.
the node js code is below,</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>//storing the information in temporary memory
var http = require(""http"");
var url = require(""url"");
var parsedUrl = url.parse('/itemsAvailable?model=nokia', true)
//	href: '/itemsAvailable?model=nokia',
//search: '?model=nokia',
//query: {model: 'nokia'},
//pathname: '/itemsAvailable'


//information of the user 
function reset() {
  var d = new Date();
  var date = d.getDate();
  var hour = d.getHours();
  var min = d.getMinutes();
  //var time = hour + ':'+min;
  //console.log(date,itemsAvailable[2].count,itemsAvailable[2].userId);

  if (hour == 16 &amp;&amp; min == 52) {
    itemsAvailable[2].count = 0;
  }
}
exports.reset = reset;

var itemsAvailable = [{
    model: 'nokia',

    available: 10
  },
  {
    model: 'samsung',
    available: 20
  },
  {
    userId: 1234,
    count: 0, //initially assigning count to 0 
    model: """",

  }
]; //create an object to store the itemsAvailable
exports.itemsAvailable = itemsAvailable;

var server = http.createServer(function(req, res) {
  reset(); //calling the reset after every request
  res.write(""hello\n"");
  if (itemsAvailable[2].count == 0) {
    if (parsedUrl.query.model === 'nokia' &amp;&amp; itemsAvailable[0].available != 0) { //parsedUrl.query gives an object and .model gives nokia
      res.write(""item chosen is nokia\n"")
      res.write(""item can be bought"");
      itemsAvailable[2].count++; // increasing the num of mobiles bought 
      console.log(itemsAvailable[2].count);
      itemsAvailable[0].available--;
      console.log(itemsAvailable[0].available)

    }
  } else {
    res.write(""u cannot buy the item today come back tomorrow"");
  }

  res.end()
}).listen(3000);

exports.server = server;</code></pre>
</div>
</div>
</p>

<p>The test code i have written is below</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>var assert = require(""chai"").assert;

var http = require(""http"");

var Code = require(""../f"");


describe(""itemsAvailable"", function() {
  it(""information count"", function() {
    assert.equal(Code.itemsAvailable[2].count, 0);
  })

});


describe(""information count"", function() {
  it(""reset"", function() {
    if (Code.reset.hour == 16 &amp;&amp; Code.reset.min == 52) {
      assert.equal(Code.reset.itemsAvailable[2].count, 0);
    }
  });
})



describe('/', function() {

  before(function(done) {
    Code.server.listen(3000, done);
  });

  after(function(done) {
    Code.server.close();
  });

  describe(""http request"", function() {

    it('buy the item', function(done) {

      http.get(""http://localhost:3000"", function(res) {

        //assert.equal(Code.server.res,'hello');
        try {
          if (Code.itemsAvailable[2].count == 0) {
            if (Code.parsedUrl.query.model == 'nokia' &amp;&amp; Code.itemsAvailable[0].available != 0) {

              it(""item can be bought"", function(done) {
                assert.equal(Code.server.res, 'item chosen is nokia');
                assert.equal(Code.server.res, 'item can be bought');
                done();
              })
            }
          };
        } catch (error) {
          it(""item can not be bought"", function(done) {
            assert.equal(Code.server.res, 'u cannot buy the item today come back tomorrow');
            done();
          })
        }
      })
      done();
    })

  });
})</code></pre>
</div>
</div>
</p>

<p>Iam getting the error</p>

<blockquote>
  <p>3 passing and 1 failing 
  1) after all hook uncaught error : error econnrefused 127.0.0.1:3000</p>
</blockquote>

<p>iam listening to the port 3000 .The nodejs code alone works fine . I just started learning mocha unit testing , can someone explain me why that error occurs and what changes can be done in the above unit test code to possibly get rid of the error. </p>
",https://stackoverflow.com/questions/45139681/why-am-i-getting-this-errorconnect-econnrefused-127-0-0-13000-while-writing-mo,"['unit-testing', 'mocha.js']",1875,TRUE,0,1
Spring MockMvc doesn&#39;t contain cookies,"<p>I have a controller protected with HTTP Basic authentication.</p>

<p>I setup the app to use session cookies and it works.</p>

<p>However when I test the controller using MockMvc, a successful authentication does not give me any cookie.</p>

<p>Web configuration:</p>

<pre class=""lang-java prettyprint-override""><code>package world.pyb.spring.cookiesdemo;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;

@Configuration
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser(""admin"").password(""argentina"").roles(""USER"");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //@formatter:off
        http.httpBasic()
                .and().authorizeRequests().antMatchers(HttpMethod.GET, ""/hello"").authenticated()
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.ALWAYS);
        //@formatter:on
    }
}
</code></pre>

<p>Simple controller:
</p>

<pre><code>package world.pyb.spring.cookiesdemo;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @RequestMapping(""/hello"")
    public String index() {
        return ""Greetings from Spring Boot!"";
    }

}
</code></pre>

<p>Simple controller test that doesn't give me the session cookie:
</p>

<pre><code>package world.pyb.spring.cookiesdemo;

import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.cookie;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {

    @Autowired
    private MockMvc mvc;

    @Test
    public void getHello() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get(""/hello"")
            .with(SecurityMockMvcRequestPostProcessors.httpBasic(""admin"", ""argentina""))
    )
        // prints ""Cookies = []""
        .andDo(MockMvcResultHandlers.print())
        .andExpect(cookie().exists(""JSESSIONID""))
        .andExpect(status().is2xxSuccessful())
        .andExpect(content().string(equalTo(""Greetings from Spring Boot!"")));
    }

}
</code></pre>

<p>Related questions:</p>

<ul>
<li><a href=""https://stackoverflow.com/questions/26142631/why-does-spring-mockmvc-result-not-contain-a-cookie"">Why does Spring MockMvc result not contain a cookie?</a></li>
<li><a href=""https://stackoverflow.com/questions/28231336/unit-testing-login-in-spring-mvc-using-mockmvc"">Unit Testing /login in Spring MVC using MockMvc</a></li>
<li><a href=""https://stackoverflow.com/questions/36600817/spring-mvc-testing-security-integration-test-jsessionid-is-not-present"">Spring MVC testing (security Integration test), JSESSIONID is not present</a></li>
</ul>

<p>Some answers suggest not to use MockMvc but I'd like to keep using it if possible.</p>
",https://stackoverflow.com/questions/46793814/spring-mockmvc-doesnt-contain-cookies,"['spring-mvc', 'testing', 'cookies', 'spring-security']",7084,TRUE,5,1
Questions on NodeJS application,"<p>I have very basic questions on NodeJS apps;</p>

<ol>
<li><p>When someone says a NodeJS app, does it refer to a pure server-side written NodeJS app ? I mean nowadays, when projects (say Angular, Ember, etc) use Node to install dependencies, can those client-side apps (which run in browser) be also called NodeJS app ? Or are these just NPM using apps ?</p></li>
<li><p>The unit-testing frameworks like Mocha, Jasmine, etc be used for both the types of apps I described above ? Or is it meant only for server-side NodeJS app ?</p></li>
</ol>
",https://stackoverflow.com/questions/44481441/questions-on-nodejs-application,"['javascript', 'angularjs', 'node.js']",77,TRUE,0,3
Test Cases states Failed but value returned is true,"<p>I have written up a simple sample code to understand GMOCK used for unit testing:</p>

<pre><code>#include &lt;iostream&gt;
#include ""gmock/gmock.h""
#include ""gtest/gtest.h""
using ::testing::AtLeast;
class A {
public:
    void ShowPub1()
    {
        std::cout &lt;&lt; ""A::PUBLIC::SHOW..1"" &lt;&lt; std::endl;
    }
    int ShowPub2(int x)
    {
        std::cout &lt;&lt; ""A::PUBLIC::SHOW..2"" &lt;&lt; std::endl;
        return true;
    }
};

class MockA : public A{
public:
    MOCK_METHOD0(ShowPub1, void());
    MOCK_METHOD1(ShowPub2, int(int x));
};
</code></pre>

<p>Below is my test code - I just wish to call ShowPub2 method of class A. I was expecting the statement <strong>A::PUBLIC::SHOW..2</strong> to get printed at console - but it just did not happen and the test case also failed though the method is hardcoded to return true:</p>

<pre><code>TEST(FirstA, TestCall) {
    MockA a; 
    EXPECT_CALL(a, ShowPub2(2)) 
        .Times(AtLeast(1));
    a.ShowPub2(2);
    EXPECT_TRUE(a.ShowPub2(2));
}
</code></pre>

<p>GMOCK test code execution output - I am not sure why the output <strong>A::PUBLIC::SHOW..2</strong> did not rendered in console and test case failed:</p>

<pre><code>[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from FirstA
[ RUN      ] FirstA.TestCall
c:\users\user1\documents\c and c++\gmock\gmock1\gmock1\gmock1.cpp(78): error:
Value of: a.ShowPub2(2)
  Actual: false
Expected: true
[  FAILED  ] FirstA.TestCall (0 ms)
[----------] 1 test from FirstA (0 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (0 ms total)
[  PASSED  ] 0 tests.
[  FAILED  ] 1 test, listed below:
[  FAILED  ] FirstA.TestCall

 1 FAILED TEST
Press any key to continue . . .



int main(int argc, char** argv)
{
    ::testing::InitGoogleTest(&amp;argc, argv);
    return RUN_ALL_TESTS();
    return 0;
}
</code></pre>
",https://stackoverflow.com/questions/45408271/test-cases-states-failed-but-value-returned-is-true,"['c++', 'googlemock']",52,TRUE,0,1
Angular Unit Test of a PRIME ng confirmation service,"<p>First of all i am newbie at angular unit testing. I want to unit test the following method that removes a record from my data. The method is:</p>

<pre><code>//Confirm Button for deletion


 confirm(name: string, id: any) {
      this.confirmationService.confirm({
          message: 'Are you sure you want to remove ' + name + ' from your list of Supporting Staff?',
          accept: () =&gt; {
             const index: number = this.data.indexOf(id);
              if (index !== -1) {
                this.data.splice(index,1);
                this.totalResults = this.data.length;
                this.updateVisibility();                
                this.alertMessage = { severity: 'success', summary: 'SUCCESSFUL REMOVAL', detail: 'You have successfully removed '+name+' from your Supporting Staff List.' };
                this.alertMessagesSrv.pushAlert(this.alertMessage);
               }   
          },
      reject: () =&gt; {       
      }
      });

  }
</code></pre>

<p>As you can see i am calling the confirmation service from PRIME ng and i open a dialog to ask the user if he wants to remove the selected record. (Data are my records).</p>

<p>This is my unit test:</p>

<pre><code> it('should remove a supporting staff from list', () =&gt; {
let fixture = TestBed.createComponent(SupportingStaffComponent);
let app = fixture.debugElement.componentInstance;
let dataService = fixture.debugElement.injector.get(ProvidersService);
let spy = spyOn(dataService,'getSupportingStaffList').and.callThrough(); 
fixture.detectChanges();
let confirmFunction = fixture.componentInstance.confirm(app.data[0].name,1);
let confirmService = fixture.debugElement.injector.get(ConfirmationService);
//fixture.nativeElement.querySelector('#btnYes').click();
let spyRemove = spyOn(confirmService,'accept').and.callThrough();

fixture.detectChanges();

console.log(app.data);
expect(app.data).toBeDefined();
});
</code></pre>

<p>So i am calling the service to load my data (dataService) and then calling my method to remove the first record. but nothing is happening. The unit test finishes succesfull but no data are removed.</p>

<p>Any thoughts?</p>
",https://stackoverflow.com/questions/47132412/angular-unit-test-of-a-prime-ng-confirmation-service,"['angular', 'unit-testing', 'service', 'primeng']",5463,TRUE,10,3
Create file during mstest - System.UnauthorizedAccessException,"<p>I have a UWP C# app, with a unit testing project. In these unit test, I want to be able to write to a text file in order to make something like <a href=""http://facebook.github.io/jest/docs/en/snapshot-testing.html"" rel=""noreferrer"">snapshots in Jest</a>.</p>

<p><code>Directory.GetCurrentDirectory()</code> returns <code>C:\path\to\project\bin\x64\Debug\AppX</code>, so I made a folder in the project directory and am navigating to it, then attempting to create a file there.</p>

<pre class=""lang-cs prettyprint-override""><code>[TestMethod]
public void Test()
{
    var folder = Path.Combine(Directory.GetCurrentDirectory(), ""../../../../Snapshots"");
    string data = ""example data"";
    string filename = Path.Combine(folder, ""Test.snap"");
    File.WriteAllText(filename, json);
}
</code></pre>

<p>However, this test produces a <code>System.UnauthorizedAccessException</code>. I went into the folder in windows and gave Everyone read/write permissions, but that didn't make any difference.</p>

<p>I don't want to have to run Visual Studio as an administrator. Is this possible?</p>
",https://stackoverflow.com/questions/46940213/create-file-during-mstest-system-unauthorizedaccessexception,"['c#', '.net', 'visual-studio', 'uwp', 'mstest']",1363,TRUE,5,3
Polymer 2.x unit test pass optional content to fixture in order to bind to a target property,"<p>I am trying to insert data into the test fixture but couldn't achieve so far. Returns this error:
    <code>""was given a model to stamp, but the template is not of a bindable type""</code></p>

<p>My test code is like below:</p>



<pre class=""lang-html prettyprint-override""><code>&lt;test-fixture id=""myFixture""&gt;
  &lt;template is=""dom-template""&gt;
    &lt;my-element given-input=""[[selectedInput]]""&gt;&lt;/myElement&gt;
  &lt;/template&gt;
&lt;/test-fixture&gt;

&lt;script&gt;
  suite('&lt;my-element&gt;', function() {

    var myEl;

    setup(function() {
      myEl = fixture('myFixture', {selectedInput: 'test input'});
    });

    test('initiates my-element', function() {

      // fails as givenInput returns ""[[selectedInput]]""
      assert.equal(myEl.givenInput, 'test input');
    });
  });
&lt;/script&gt;
</code></pre>



<p>Similar question was asked here <a href=""https://stackoverflow.com/questions/32360098/polymer-1-0-unit-tests-how-to-bind-properties-to-a-child-element"">polymer 1.0 unit tests - how to bind properties to a child element?</a> but the answer is not what I look for since it is directly defining target property in the child element</p>

<p>Also in <a href=""https://stackoverflow.com/questions/38689997/data-binding-in-polmyers-test-fixture"">Data binding in Polmyer&#39;s &lt;test-fixture&gt;</a> it is very same issue but didn't work for me either.</p>

<p>My question is about, how can we pass a property down to the element through test fixture in Polymer 2.x unit testing?</p>
",https://stackoverflow.com/questions/45241833/polymer-2-x-unit-test-pass-optional-content-to-fixture-in-order-to-bind-to-a-tar,"['html', 'unit-testing', 'polymer-2.x']",397,TRUE,5,1
Error trying to test an Angular2 component with an external template,"<p>I've been trying to familiarize myself with unit testing in an Angular2 app and have been following the Angular documentation on testing but have run into an error I haven't been able to figure out.</p>

<p>I have a simple demo app that I have put together to play with the testing. I have it setup and configured exactly like my full project. It is an Angular2 app built on top of ASP.NET Core MVC using the templates and setup provided here (<a href=""https://marketplace.visualstudio.com/items?itemName=MadsKristensen.ASPNETCoreTemplatePack"" rel=""nofollow noreferrer"">https://marketplace.visualstudio.com/items?itemName=MadsKristensen.ASPNETCoreTemplatePack</a>). I'm using Webpack and Typescript with Karma and Jasmine for the Unit Testing.</p>

<p>The problem that I am having is that when I try to implement the tests for a component with an external template (<a href=""https://angular.io/docs/ts/latest/guide/testing.html#!#async-in-before-each"" rel=""nofollow noreferrer"">https://angular.io/docs/ts/latest/guide/testing.html#!#async-in-before-each</a>) I am getting an error on the async beforeEach function. While all of my tests pass successfully, I am getting an error in my editor and when I run the full application. The error that I am receiving is: <code>error TS2345: Argument of type '(done: any) =&gt; any' is not assignable to parameter of type '() =&gt; void'.</code></p>

<p>While my prefered solution would be to fix the error, since my tests are passing, I'd settle for getting things configured so that my .spec.ts files are not included in the bundles Webpack creates for the prod site (note my spec.ts files live side-by-side with the .ts files that implement the components)</p>

<p>banner.component.spec.ts</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

import { BannerComponent } from '../banner.component';

describe('BannerComponent (templateUrl)', () =&gt; {

    let comp: BannerComponent;
    let fixture: ComponentFixture&lt;BannerComponent&gt;;
    let de: DebugElement;
    let el: HTMLElement;

    // async beforeEach
    //This is the function that is producing the error
    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            declarations: [BannerComponent], // declare the test component
        })
        .compileComponents();  // compile template and css
    }));

    // synchronous beforeEach
    beforeEach(() =&gt; {
        fixture = TestBed.createComponent(BannerComponent);

        comp = fixture.componentInstance; // BannerComponent test instance

        // query for the title &lt;h1&gt; by CSS element selector
        de = fixture.debugElement.query(By.css('h1'));
        el = de.nativeElement;
    });

    it('no title in the DOM until manually call `detectChanges`', () =&gt; {
        expect(el.textContent).toEqual('');
    });

    it('should display original title', () =&gt; {
        fixture.detectChanges();
        expect(el.textContent).toContain(comp.title);
    });

    it('should display a different test title', () =&gt; {
        comp.title = 'Test Title';
        fixture.detectChanges();
        expect(el.textContent).toContain('Test Title');
    });

});
</code></pre>

<p>karma.conf.js:</p>

<pre><code>'use strict';

module.exports = (config) =&gt; {
    config.set({
        autoWatch: true,
        browsers: ['Chrome', 'PhantomJS'],
        files: [
            './node_modules/es6-shim/es6-shim.min.js',
            './karma.entry.js'
        ],
        frameworks: ['jasmine'],
        logLevel: config.LOG_INFO,
        phantomJsLauncher: {
            exitOnResourceError: true
        },
        preprocessors: {
            'karma.entry.js': ['webpack', 'sourcemap']
        },
        reporters: ['progress', 'growl'],
        singleRun: false,
        webpack: require('./webpack.config.test'),
        webpackMiddleware: {
            noInfo: true
        }
    });
};
</code></pre>

<p>karma.entry.js  </p>

<pre><code>require('es6-shim');
require('reflect-metadata');
require('zone.js/dist/zone');
require('zone.js/dist/long-stack-trace-zone');
require('zone.js/dist/async-test');
require('zone.js/dist/fake-async-test');
require('zone.js/dist/sync-test');
require('zone.js/dist/proxy'); // since zone.js 0.6.14
require('zone.js/dist/jasmine-patch');

const browserTesting = require('@angular/platform-browser-dynamic/testing');
const coreTesting = require('@angular/core/testing');

coreTesting.TestBed.resetTestEnvironment();
coreTesting.TestBed.initTestEnvironment(
    browserTesting.BrowserDynamicTestingModule,
    browserTesting.platformBrowserDynamicTesting()
);

const context = require.context('./ClientApp/app/', true, /\.spec\.ts$/);

context.keys().forEach(context);

Error.stackTraceLimit = Infinity;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 2000;
</code></pre>

<p>webpack.config.test.js</p>

<pre><code>'use strict';

const path = require('path');
const webpack = require('webpack');

module.exports = {
    devtool: 'inline-source-map',
    module: {
        loaders: [
            { loader: 'raw', test: /\.(css|html)$/ },
            { test: /\.ts$/, exclude: /node_modules/, include: /ClientApp/, loader: 'ts', query: { silent: true } },
            { test: /\.(png|jpg|jpeg|gif|woff|woff2|eot|ttf|svg)(\?|$)/, loader: 'url-loader?limit=100000' },
        ]
    },
    resolve: {
        extensions: ['', '.js', '.ts'],
        modulesDirectories: ['node_modules'],
        root: path.resolve('.', 'ClientApp/app')
    }
};
</code></pre>

<p>webpack.config.js</p>

<pre><code>/// &lt;binding ProjectOpened='Watch - Development' /&gt;
var isDevBuild = process.argv.indexOf('--env.prod') &lt; 0;
var path = require('path');
var webpack = require('webpack');
var nodeExternals = require('webpack-node-externals');
var merge = require('webpack-merge');
var allFilenamesExceptJavaScript = /\.(?!js(\?|$))([^.]+(\?|$))/;

// Configuration in common to both client-side and server-side bundles
var sharedConfig = {
    resolve: { extensions: [ '', '.js', '.ts' ] },
    output: {
        filename: '[name].js',
        publicPath: '/dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
    },
    module: {
        loaders: [
            { test: /\.ts$/, include: /ClientApp/, loader: 'ts', query: { silent: true } },
            { test: /\.html$/, loader: 'raw' },
            { test: /\.css$/, loader: 'to-string!css' },
            { test: /\.(png|jpg|jpeg|gif|svg)$/, loader: 'url', query: { limit: 25000 } }
        ]
    }
};

// Configuration for client-side bundle suitable for running in browsers
var clientBundleConfig = merge(sharedConfig, {
    entry: { 'main-client': './ClientApp/boot-client.ts' },
    output: { path: path.join(__dirname, './wwwroot/dist') },
    devtool: isDevBuild ? 'inline-source-map' : null,
    plugins: [
        new webpack.DllReferencePlugin({
            context: __dirname,
            manifest: require('./wwwroot/dist/vendor-manifest.json')
        })
    ].concat(isDevBuild ? [] : [
        // Plugins that apply in production builds only
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin()
    ])
});

// Configuration for server-side (prerendering) bundle suitable for running in Node
var serverBundleConfig = merge(sharedConfig, {
    entry: { 'main-server': './ClientApp/boot-server.ts' },
    output: {
        libraryTarget: 'commonjs',
        path: path.join(__dirname, './ClientApp/dist')
    },
    target: 'node',
    devtool: 'inline-source-map',
    externals: [nodeExternals({ whitelist: [allFilenamesExceptJavaScript] })] // Don't bundle .js files from node_modules
});

module.exports = [clientBundleConfig, serverBundleConfig];
</code></pre>
",https://stackoverflow.com/questions/41879078/error-trying-to-test-an-angular2-component-with-an-external-template,"['angular', 'typescript', 'webpack', 'jasmine', 'karma-runner']",1092,TRUE,0,1
jenkins pipeline using different nodes for different stages,"<p>I am trying to run different stages on different nodes in my jenkins pipeline like stage 1 is checkout, stage 2 is build, stage 3 unit testing. 
For example :</p>

<pre><code>node ('linux1')
{
stage ('checkout')
..........
}

node ('linux2')
{
stage ('build')
........
}


node ('linux3')
{
stage ('unit testing')
...........
}
</code></pre>

<p>If I try to do this, my question is if I checkout code in Linux1 node, how come the other stages can run in different node while the checked out code is in node1. </p>

<p>How the code will be distributed and if my understanding is not correct, how can I achieve parallelism and ensure each stage can parallel and reduce time.</p>

<p>If possible, Please suggest any groovy pipeline documentation for writing Jenkins pipelines.</p>
",https://stackoverflow.com/questions/44481122/jenkins-pipeline-using-different-nodes-for-different-stages,"['jenkins', 'groovy', 'jenkins-pipeline']",15262,TRUE,4,1
AutoMock - How to unit test with Keyed Registrations?,"<p>I'm having trouble writing tests around a factory that uses Autofac keyed registrations.  </p>

<p>In an Autofac module, I register things like this:</p>

<pre><code>builder.RegisterType&lt;TypeAMessageHandler&gt;().As&lt;IMessageHandler&gt;()
    .Keyed&lt;IMessageHandler&gt;(MessageTypeEnum.A);

builder.RegisterType&lt;TypeBMessageHandler&gt;().As&lt;IMessageHandler&gt;()
    .Keyed&lt;IMessageHandler&gt;(MessageTypeEnum.B);

builder.RegisterType&lt;MessageHandlerFactory().As&lt;IMessageHandlerFactory&gt;();
</code></pre>

<p>Then the constructor for the factory gets a nice Index injected into its constructor by Autofac:</p>

<pre><code>public MessageHandlerFactory(
    IIndex&lt;MessageTypeEnum, IMessageHandler&gt; messageTypeToHandlerMap)
</code></pre>

<p>However, I can't figure out how to inject an <code>IIndex&lt;,&gt;</code> for unit testing with Automock, when I use <code>automock.Create&lt;MessageHandlerFactory&gt;()</code>. Telling the AutoMock to Provide message handler implementations doesn't get them into the keyed index.  Creating an explicit implementation of IIndex and asking Automock to Provide that also doesn't work - in both cases, my factory gets an empty <code>IIndex&lt;,&gt;</code> injected.</p>

<p>What is the right way to test keyed registrations?</p>
",https://stackoverflow.com/questions/47798273/automock-how-to-unit-test-with-keyed-registrations,"['c#', 'unit-testing', 'autofac']",1260,TRUE,3,2
How to specify what code is covered by a unit-test?,"<p>In PHPunit there is <a href=""https://phpunit.de/manual/current/en/code-coverage-analysis.html#code-coverage-analysis.specifying-covered-methods"" rel=""nofollow noreferrer""><code>@covers</code></a> annotation to specify which classes/methods/functions are covered by a specific unit test. This helps avoiding false-coverage.</p>

<p>Is there a way to do something similar in the Python unit-test world?</p>

<p>I am using Python 3.6 with <a href=""https://docs.pytest.org/en/latest/"" rel=""nofollow noreferrer"">pytest</a> for unit-testing and am free to choose any coverage tool that will allow me to annotate or mark my tests with what code (unit) they do cover and do not cover.</p>

<p>I am hoping for something like annotations or pragma comments to be used in the unit-tests. Preferably supported by the PyCharm if possible.</p>
",https://stackoverflow.com/questions/47532102/how-to-specify-what-code-is-covered-by-a-unit-test,"['python', 'unit-testing', 'pytest']",81,FALSE,3,0
How to create a Form&lt;T&gt; for a play (java) unit test now that Form.form() is deprecated?,"<p>In application code when dealing with forms it is recommended to use a FormFactory to create a Form wrapper around the form of type T. But when it comes to testing, what is the way to create a Form? (Do you have to inject FormFactory in the test?)</p>

<p>My app does something similar to that:</p>

<pre><code>class MyAmazingClass {
    private final FormFactory formFactory;

    @Inject
    MyAmazingClass(FormFactory formFactory) {
        this.formFactory = formFactory;
    }

    public CompletionStage&lt;Result&gt; myAmazingMethodHandlingForms() {
        Form&lt;String&gt; form = formFactory.form(String.class).bindFromRequest();
        // ... Actually doing something
        return null;
    }
}
</code></pre>

<p>What shall my test class (for unit testing) looks like?</p>

<p>I am trying something like this but I think I should not try to inject the FormFactory (also it does not seems to work):</p>

<pre><code>public class MyAmazingClassTest extends WithApplication {

    @Mock
    FormFactory mockedFormFactory;

    @Inject
    FormFactory realFormFactory;

    MyAmazingClass myAmazingClass;

    @Override
    protected Application provideApplication() {
        return new GuiceApplicationBuilder().build();
    }

    @Before
    public void setUp() throws Exception {
        myAmazingClass = new MyAmazingClass(mockedFormFactory);
    }

    @Test
    public void testMyAmazingMethodHandlingForms() throws Exception {
        String myString = ""ciao"";
        Form&lt;String&gt; stringForm = realFormFactory.form(String.class).fill(myString);
        when(mockedFormFactory.form(eq(String.class)).bindFromRequest()).thenReturn(stringForm);
        myAmazingClass.myAmazingMethodHandlingForms();
        // Some assertions...
    }
}
</code></pre>

<p>I am using JUnit 4, Java 8 and Play framework 2.5.</p>
",https://stackoverflow.com/questions/46282735/how-to-create-a-formt-for-a-play-java-unit-test-now-that-form-form-is-depr,"['java', 'unit-testing', 'playframework', 'junit4', 'playframework-2.5']",770,TRUE,2,1
Is there a way to get a 32bit C++ compiler to follow 16bit integer promotion rules?,"<p>With the following code:</p>

<pre><code>#include &lt;stdint.h&gt;

uint16_t test() {
    uint16_t a = 1000;
    uint16_t b = 1000;
    uint16_t c = 100;
    return (a * b) / c;
}
</code></pre>

<p>A compiler targeting a 32bit machine will return 10000, but one targeting a 16 bit machine will return 169. The behavior is explained by C's integer promotion rules.</p>

<p>This is a problem when unit testing firmware for a 8 or 16 bit machine on a desktop PC.</p>

<p>Right now, either casting every multiplication or putting it inside a function returning the same type are the only options I can think of. Ideally some compiler switch would exist, but I haven't seen one. </p>

<p>Happy with a solution for either GCC, Clang or MSVC.</p>
",https://stackoverflow.com/questions/44351991/is-there-a-way-to-get-a-32bit-c-compiler-to-follow-16bit-integer-promotion-rul,['c++'],111,TRUE,2,2
Mocking Scala Objects and Functions,"<p>I have a Scala object and it contains a few utility functions. These functions are called by other functions present in the same object or from other classes/objects. Is it possible to mock this object or the functions so that I can unit test the classes where they are being called.</p>

<p>Example:</p>

<pre><code>object Util {

  def methodA() = { 
    //other code
    methodB() 
    //other code
  }

  def methodB() = { 
    //other code
    methodC() 
    //other code
  }

  def methodC() = { ... }

}
</code></pre>

<p>And here I'm calling the object function from another class</p>

<pre><code>class Data {

  //other code

  def call() = {
    //other code
    Util.methodA()
    //other code
  }
}
</code></pre>

<p>How can I go about unit testing the function call() of class Data ? In Java I can create a mocked object for Util and set expectations for a call to methodA(), but this is not possible in Scala since no mocking library supports mocking of a Scala object.</p>
",https://stackoverflow.com/questions/43475907/mocking-scala-objects-and-functions,"['scala', 'unit-testing', 'mocking']",11990,TRUE,7,2
@Autowired objects are null only when testing,"<p>My question has to do with the application set-up, not mocking or using autowiring. See the answer for more details. </p>

<p>I'm trying to set up a Spring Boot application and I'm having issues creating unit tests. My issue is that all objects I have <code>@Autowired</code> are null only during unit testing. When I run the application normally I'm able to use CURL for and it works. However when I test with JUnit I get a null pointer when I try to use the <code>@Autowired</code> objects. I am not using a xml file to configure my beans, maybe that is my problem?</p>

<p>Application.java</p>

<pre><code>package com.blakeparmeter.metricsapi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 *
 * @author Blake
 */
@SpringBootApplication
@EnableAutoConfiguration
public class Application {

    public static void main(String[] args){
        SpringApplication.run(Application.class, args);
    }
}
</code></pre>

<p>MetricApi.java</p>

<pre><code>package com.blakeparmeter.metricsapi.api;

import com.blakeparmeter.metricsapi.beans.Metric;
import com.blakeparmeter.metricsapi.controllers.MetricController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Handles all the REST responses logic of the Metrics services. 
 * Complex logic should be moved outside of this class.
 * @author Blake
 */
@RestController
@EnableAutoConfiguration
public class MetricAPI {

    @Autowired 
    private MetricController metricController;

    @RequestMapping(""/addMetric"")
    public ResponseEntity&lt;?&gt; addMetric(@RequestBody Metric record){
        metricController.addMetric(record);
        return ResponseEntity.ok().build();
    }
}
</code></pre>

<p>MetricController.java</p>

<pre><code>package com.blakeparmeter.metricsapi.controllers;

import com.blakeparmeter.metricsapi.beans.Metric;
import org.springframework.stereotype.Controller;

/**
 *
 * @author Blake
 */
@Controller
public class MetricController {

    public Metric addMetric(Metric metric){
        System.out.println(""Adding a metric!"");
        return metric;
    }
}
</code></pre>

<p>MetricsTest.java</p>

<pre><code>package metrics;

import com.blakeparmeter.metricsapi.Application;
import com.blakeparmeter.metricsapi.api.MetricAPI;
import com.blakeparmeter.metricsapi.beans.Metric;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;

/**
 * @author Blake 
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class MetricsTest {

    private MockMvc mockMvc;

    @Autowired
    ObjectMapper objectMapper;

    @Before
    public void setup() throws Exception {
        mockMvc = standaloneSetup(new MetricAPI()).build();
    }

    /**
     * Adds a valid metric
     * @throws Exception 
     */
    @Test
    public void addMetricTest() throws Exception{
        mockMvc.perform(post(""/addMetric"")
            .contentType(MediaType.APPLICATION_JSON)
            .content(objectMapper.writeValueAsString(new Metric())))
                .andExpect(status().isOk());
    }
}
</code></pre>

<p>pom.xml</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;project xmlns=""http://maven.apache.org/POM/4.0.0"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xsi:schemaLocation=""http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd""&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
    &lt;groupId&gt;com.blakeparmeter&lt;/groupId&gt;
    &lt;artifactId&gt;MetricsAPI&lt;/artifactId&gt;
    &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
    &lt;packaging&gt;jar&lt;/packaging&gt;

    &lt;properties&gt;
        &lt;java.version&gt;1.8&lt;/java.version&gt;
        &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;
        &lt;maven.compiler.source&gt;1.7&lt;/maven.compiler.source&gt;
        &lt;maven.compiler.target&gt;1.7&lt;/maven.compiler.target&gt;
    &lt;/properties&gt;

    &lt;parent&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
        &lt;version&gt;1.5.1.RELEASE&lt;/version&gt;
    &lt;/parent&gt;

    &lt;dependencies&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.h2database&lt;/groupId&gt;
            &lt;artifactId&gt;h2&lt;/artifactId&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;
&lt;/project&gt;
</code></pre>

<p>Stack trace:</p>

<pre><code>Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 13.569 sec &lt;&lt;&lt; FAILURE! - in metrics.MetricsTest
addMetricTest(metrics.MetricsTest)  Time elapsed: 0.174 sec  &lt;&lt;&lt; ERROR!
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
    at com.blakeparmeter.metricsapi.api.MetricAPI.addMetric(MetricAPI.java:30)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
    at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
    at metrics.MetricsTest.addMetricTest(MetricsTest.java:47)
</code></pre>
",https://stackoverflow.com/questions/43128842/autowired-objects-are-null-only-when-testing,"['java', 'spring-boot', 'junit', 'autowired']",25971,TRUE,7,1
Mockito never() not working with andThen rxjava2,"<p>I am testing a fairly simple piece of code written in Kotlin:</p>

<pre><code>o1.updateUser(params)
     .andThen(o2.reload())
</code></pre>

<p>When updateUser fails I expect that reload will not be executed. But when testing with Mockito 2 and jUnit 5 there is an invocation of said mock.</p>

<p>the mocking is done like that:</p>

<pre><code>given(o1.updateUser(user)).willReturn(Completable.error(IllegalArgumentException())
given(o2.reload()).willReturn(Completable.complete())
</code></pre>

<p>Now the problem is that the code behaves as expected, meaning that in this case o2 is never actually called, but while unit testing Mockito claims that there was an invocation of o1. </p>

<p>Test assertion looks as follows:</p>

<pre><code>verify(o2, never()).reload()
</code></pre>

<p>Did I do something wrong here? Is there a way around this? Am I understanding the operator somehow incorrectly? </p>
",https://stackoverflow.com/questions/47241146/mockito-never-not-working-with-andthen-rxjava2,"['unit-testing', 'junit', 'kotlin', 'mockito', 'rx-java2']",483,TRUE,2,1
Django test: TransactionManagementError: You can&#39;t execute queries until the end of the &#39;atomic&#39; block,"<p>Django newbie here. I'm trying to implement unit tests for a simple API I developed. Below you can find my test implementation which works fine:</p>

<pre><code>from django.test import TestCase
from my_app.models import MyModel


class TestMyViewSet(TestCase):
    """"""
    Unit tests for endpoints in MyViewSet.
    """"""
    fixtures = ['my_app/fixtures/data.yaml']

    def setUp(self):
        # Making setup for the test case here.


    def test_post_my_resource(self):

        # Checking that fixture is loaded correctly.
        self.assertEqual(MyModel.objects.all().count(),1)

        request_body = {
            'my_resource': ""input_for_my_resource""
        }

        response = self.client.post('/my_resources/', data=request_body)
        self.assertEqual(response.status_code, 201)
        # self.assertEqual(MyModel.objects.all().count(),2)
</code></pre>

<p>But when I removed the last line <code>self.assertEqual(MyModel.objects.all().count(),2)</code> from the comment to test that <code>my_resource</code> is created successfully on the corresponding model by checking the number of instances, I got an error stating the following:</p>

<blockquote>
  <p>TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.</p>
</blockquote>

<p>What am I missing here? </p>

<p>Thanks in advance!</p>

<p>PS: I come across the following question: <a href=""https://stackoverflow.com/questions/21458387/transactionmanagementerror-you-cant-execute-queries-until-the-end-of-the-atom"">TransactionManagementError “You can't execute queries until the end of the 'atomic' block” while using signals, but only during Unit Testing</a> but I'm not sure what's happening in my case is the same.</p>
",https://stackoverflow.com/questions/43978468/django-test-transactionmanagementerror-you-cant-execute-queries-until-the-end,"['python', 'django', 'unit-testing']",11407,TRUE,17,1
Do you unit test __init__ method if it sets up public attributes of a class?,"<p>I am trying to apply Sandi Metz’s rules of unit testing only the messages that really have influence on the public side of the object and testing all the private stuff indirectly by testing the public stuff.</p>

<p>Thus we avoid testing the implementation and can change it at any time.</p>

<p>My question is this: if my <code>__init__</code> method sets up publicly available instance attributes should I unit test it as well. </p>

<p>I am basically not sure if the init should be treated as private method (and believe that if it sets public stuff it should be unit tested).</p>

<p>Example:</p>

<pre><code>MyClass(object):

    def __init__(self, public_parameter_1, public_param_2)

        self.public_parameter_1 = public_parameter_1
        self.public_parameter_2 = public_parameter_2
</code></pre>

<p>The test using pytest:</p>

<pre><code>def test_instance():

    instance = MyClass(1, 2)

    assert instance.public_parameter_1 == 1
    assert instance.public_parameter_2 == 2
</code></pre>
",https://stackoverflow.com/questions/46786341/do-you-unit-test-init-method-if-it-sets-up-public-attributes-of-a-class,"['python', 'unit-testing', 'initialization']",2132,TRUE,2,1
example for mocks and stubs in cxxtest,"<p>I am using cxx test for unit testing. I have the proper setup for everything and I have written test cases for some simple functions but with a lot of dependencies in the code, I am finding it difficult to write more test suites. I have searched thoroughly on Google about mocks and stubs but still, i don't have a complete feel of mocks and stubs.I would like to have some proper examples of projects which are using mocks and stubs. any proper GitHub link will also work. Or any proper explanation will also be very much useful.</p>
",https://stackoverflow.com/questions/44500587/example-for-mocks-and-stubs-in-cxxtest,"['stubs', 'cxxtest']",302,FALSE,2,0
How to deal with random order of Set in test case?,"<p>In my test cases, I use assertEquals() to make a unit test. The problem is that the value of this assertion comes from a HashSet, where the order is random. So each time when I run the test case, my assertions may fail due to the different string representation value of HashSet.</p>

<p>In order to deal with this, I am thinking to use a LinkedHashSet in my code, but that doesn't seem like a valid solution, since the choice of LinkedHashSet is simply to accommodate some test cases.</p>

<p>Is this a common situation in unit testing?</p>
",https://stackoverflow.com/questions/44787988/how-to-deal-with-random-order-of-set-in-test-case,"['java', 'unit-testing']",702,TRUE,1,3
Camel unit test case issue,"<p>I have a route for File transferring. In between, I have to insert to the audit table and log some minimal information. The route is working fine, but I am not able do the camel unit testing.</p>

<pre><code>public class EobRequestTest extends CamelBlueprintTestSupport {
  @Test
  public void testRoute() throws Exception {
     MockEndpoint mock = getMockEndpoint(""file:{{outBound.ftp.url}}"");
     mock.expectedMessageCount(1);
     template.sendBody(""file:{{intBound.ftp.url}}"", getInputFile());        
     mock.assertIsSatisfied();
  }

  @Override
  public String isMockEndpoints(){
    return ""*"";
  }

  private File getInputFile() throws Exception {
    return FileUtils.getFile(""src"", ""test"", ""resources"",""test.xml"");
  }
}
</code></pre>

<p>Now when I run the above test case, I am getting the file mentioned, ""test.xml"", transferred to original output folder. Also all the db operations are executed.
I tried to use <strong>isMockEndpointsAndSkip</strong> instead of <strong>isMockEndpoints</strong> as follows.</p>

<pre><code>@Override
 public String isMockEndpointsAndSkip(){
    return ""*"";
 }
</code></pre>

<p>But now it is throwing test failure</p>

<p>java.lang.AssertionError: mock://file:D:/output Received message count. Expected: &lt;1> but was: &lt;0></p>

<p>Am I missing something here? Please help.</p>
",https://stackoverflow.com/questions/45932235/camel-unit-test-case-issue,['apache-camel'],501,FALSE,1,1
eclipse gcov integration doesn&#39;t find static libraries,"<p>I have an eclipse workspace with two projects. The first is a static library written in C++ and the second is a collection of unit tests written in C++ using catch.hpp.</p>

<p>I am trying to use the eclipse plugin to evaluate the code coverage that the second project offers the first, however, whenever I run the unit testing project, it refuses to report on code coverage for the static library.</p>

<p>I do get code coverage on the test project which is not very useful.</p>

<p>Is there a configuration option to eclipse that will cause the code coverage to work?</p>
",https://stackoverflow.com/questions/42702915/eclipse-gcov-integration-doesnt-find-static-libraries,"['c++', 'eclipse', 'gcov']",80,FALSE,1,0
"passed parameter not working on xpath, although working in unit test","<pre><code>class ad_xml_model extends \ITico_core\common_class {

    public function get_info_from_ad($input_id) {
        $xml_file = parent::get_set('xml');
        $ad_info = $xml_file-&gt;xpath(""//ad[@id='"" . $input_id . ""']"");
        parent::get_set('ad_info', $ad_info);
        return $ad_info;
    }

}
</code></pre>

<p>The above code works when unit testing it, i've tried passing both a string and a int into the function and it works both times.</p>

<pre><code>&lt;h2&gt;get_info_from_ad&lt;/h2&gt;
test data: 1&lt;br&gt;
info from ad:- &lt;br&gt;
&lt;?php
$ad_xml_model-&gt;get_info_from_ad(1);
$ad_info = $ad_xml_model-&gt;get_set('ad_info');
print_r($ad_info);
</code></pre>

<p>but in the code below when being called from the controller its not working</p>

<pre><code>class main_controller(){
    $ad_top_limit = count($ads_from_category);
    $key = rand(0, $ad_top_limit - 1);
    $chosen_ad = $ads_from_category[$key];
    parent::get_set('chosen_ad', $chosen_ad);
    $ad_info = $ad_xml_model-&gt;get_info_from_ad($chosen_ad);
    parent::get_set('ad_info', $ad_info);
    if ($ad_info != null) {
        switch ($ad_type) {
            case NUll:
                break;
            case 'long':
                $long_view = new long_view($ad_info);
                $long_view-&gt;show_ad();
        }
    }
}
</code></pre>

<p>and the debug page testing</p>

<pre><code>&lt;?php
echo $main_controller-&gt;get_set('chosen_ad') . ""&lt;br&gt;"";
?&gt;
ad information:-: &lt;br&gt;
&lt;?php
print_r($main_controller-&gt;get_set('ad_info'));
</code></pre>

<p><a href=""https://i.stack.imgur.com/QZpfv.png"" rel=""nofollow noreferrer"">screenshot of the debug page</a></p>

<p>I've went every step of the way echoing all the variables to check that they aren't null but for some reason the xpath just doesnt work when being called from the main controller but it works fine from the unit test even though the exact same parameters are being passed.</p>
",https://stackoverflow.com/questions/41756019/passed-parameter-not-working-on-xpath-although-working-in-unit-test,"['php', 'oop', 'xpath', 'simplexml']",36,FALSE,1,1
Mock DataAccess methods that uses Enterprise Library to return IDataReader,"<p>I was given a task to rewrite an Api and corresponding unit tests. I am still quite new to unit testing and so I am struggling to write the test code for a data access class that uses Enterprise Library. Here is the code:</p>

<pre><code>namespace TOS_Landside_BL.Classes {
  using System.Collections.Generic;
  using System.Data;
  using System.Data.Common;
  using Microsoft.Practices.EnterpriseLibrary.Data;
  using Interfaces;

  public class DataAccess : IDataAccess {
    private readonly Database yasDB;

    public DataAccess () {
      DatabaseProviderFactory factory = new DatabaseProviderFactory ();
      DatabaseFactory.SetDatabaseProviderFactory (factory, false);
      yasDB = factory.Create (""AutomationDB"");
    }

    // caller is responsible for closing the reader.
    public IDataReader ExecuteReaderForStoredProcedure (string cmdName, List&lt;DbParameter&gt; parameters = null) {
      DbCommand cmd = yasDB.GetStoredProcCommand (cmdName);
      if (parameters != null)
        cmd.Parameters.AddRange (parameters.ToArray ());

      return yasDB.ExecuteReader (cmd);
    }

    public IDataReader ExecuteReaderForSqlStringCommand (string cmdScript, List &lt;DbParameter&gt; parameters = null) {
      DbCommand cmd = yasDB.GetSqlStringCommand (cmdScript);
      if (parameters != null) {
        cmd.Parameters.AddRange(parameters.ToArray());
      }

      return yasDB.ExecuteReader (cmd);
    }
  }
}
</code></pre>

<p>Here is the interface IDataAccess:</p>

<pre><code>namespace TOS_Landside_BL.Interfaces {
  using System.Collections.Generic;
  using System.Data;
  using System.Data.Common;

  public interface IDataAccess {
    IDataReader ExecuteReaderForStoredProcedure (string cmdName, List&lt;DbParameter&gt; parameters = null);
    IDataReader ExecuteReaderForSqlStringCommand (string cmdScript, List &lt;DbParameter&gt; parameters = null);
  }
}
</code></pre>

<p>And here is a sample on how I would call it:</p>

<pre><code>namespace TOS_Landside_BL.Data {
  using System;
  using System.Collections.Generic;
  using System.Data;
  using System.Data.Common;
  using System.Data.SqlClient;
  using System.Linq;
  using Classes;
  using Enums;
  using Factories;
  using Interfaces;

  public class LandsideTransactionDataProvider {
    private readonly IDataAccess _dataAccess;

    public LandsideTransactionDataProvider (IDataAccess dataAccess = null)  
    {
      _dataAccess = dataAccess ?? new DataAccess ();
    }

    public LandsideTransaction GetLandsideTransaction (string keyword, bool isKioskID = false)
    {
      var strCmd = isKioskID ? ""proc_get_landside_transaction_by_kiosk_id"" : ""[LandSide].[GetLandsideTransactionDetail]"";
      var parameters = new List &lt;DbParameter&gt; () {
        new SqlParameter (""@keyword"", SqlDbType.NVarChar, 11) {Value = keyword}
      };

      using (var reader = _dataAccess.ExecuteReaderForStoredProcedure (strCmd, parameters)) {
        return reader.Read () ? reader.CreateLandSideTransaction () : null;
      }
    }
  }
</code></pre>

<p>In the SetUp method of my test class, I tried this:</p>

<pre><code>var dataAccess = new Mock&lt;IDataAccess&gt;();
dataAccess.SetUp(d =&gt; d.ExecuteReaderFromStoredProcedure(null, null)).Returns(IDataReader);
</code></pre>

<p>but it won't accept IDataReader or any concrete data reader classes.</p>

<p>Please advise as to what I'm doing wrong, and any suggestion would really be appreciated.  Thank you.</p>
",https://stackoverflow.com/questions/47274407/mock-dataaccess-methods-that-uses-enterprise-library-to-return-idatareader,"['c#', 'unit-testing', 'moq']",386,FALSE,1,1
Unit testing CakePHP 3 plugin requires a config/routes.php folder to test with Router::url(),"<p>I am writing some tests for a CakePHP 3 plugin, and some of my actions use <code>Router::url</code> calls. When I run phpunit I get the following error: <code>include([project dir]\\config\routes.php): failed to open stream: No such file or directory</code>.</p>

<p>What I'd like to know is if this file is really required just for unit testing to work. If I create the file on that folder the testing works right. I have tried adding </p>

<p><code>DispatcherFactory::add('Asset');
 DispatcherFactory::add('Routing');
 DispatcherFactory::add('ControllerFactory');
</code></p>

<p>to my <code>tests/bootstrap.php</code> file, however it did no change at all.</p>

<p>Since this is a standalone plugin I'd find it a little odd to have a <code>config</code> folder with a <code>routes.php</code> file in it for the sole purpose of testing. Is there any workaround to this?</p>
",https://stackoverflow.com/questions/46260301/unit-testing-cakephp-3-plugin-requires-a-config-routes-php-folder-to-test-with-r,"['php', 'unit-testing', 'cakephp', 'routes']",413,TRUE,1,1
BadMethodCallException: Method Mockery_0_Illuminate_Contracts_Events_Dispatcher::listen() does not exist on this mock object,"<p>I'm doing some unit testing and want to test so basic stuff. In my test I'mg using <code>Illuminate\Foundation\Testing\WithoutEvents</code>.</p>

<p>When an user registers he or she get's an activation mail. First I used an Observer for that, but came to the conclusion that Laravel doesn't disable the observers when using <code>WithoutEvents</code> as writen <a href=""http://hellofrancesco.com/2015/12/08/a-quickie-dealing-with-observers-and-testing-in-laravel-5-1/"" rel=""nofollow noreferrer"">here</a> and <a href=""https://laracasts.com/discuss/channels/testing/prevent-event-listeners-when-using-model-factories"" rel=""nofollow noreferrer"">here</a>. Then I changed my code to the 'traditional' event and listeners.</p>

<p>EventServiceProvider is still default, except for the <code>$listen</code> property:</p>

<pre><code>/**
 * The event listener mappings for the application.
 *
 * @var array
 */
protected $listen = [
    'App\Events\UserCreated' =&gt; [
        'App\Listeners\CreateActivation'
    ],
];
</code></pre>

<p>When I dispatch the event:</p>

<p><code>event(new UserCreated($user));</code></p>

<p>And an example test (which fails):</p>

<pre><code>class ExampleTest extends TestCase
{
    use DatabaseMigrations, WithoutEvents;

    public function testExample()
    {
        $user = factory(User::class)-&gt;create();
    }
}
</code></pre>

<p>The error:</p>

<p><a href=""https://i.stack.imgur.com/ZoSWO.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ZoSWO.png"" alt=""error""></a></p>

<p>I've no clue why it's is crashing. Because I'm not sure where the problem is caused.</p>
",https://stackoverflow.com/questions/45323355/badmethodcallexception-method-mockery-0-illuminate-contracts-events-dispatcher,"['php', 'laravel', 'unit-testing', 'laravel-5']",376,FALSE,1,1
How to supply configuration file to JobDSL test?,"<p>I've been tearing my hair out trying to get this to work after the Job DSL plugin deprecated and dropped support for some older ConfigFile classes.  I have Jenkins jobs that use the Config File Provider plugin to get Maven settings.  Unfortunately, my unit test fails with </p>

<pre><code>MavenSettings config file with name 'my-maven-settings' not found.
</code></pre>

<p>The part of my test that is trying create that file is here:</p>

<pre><code>    given:
    JobManagement jm = new JenkinsJobManagement(System.out, [:], new File('.'))

    ConfigProvider cfgProvider = jenkinsRule.getInstance().getExtensionList(MavenSettingsConfig.MavenSettingsConfigProvider.class).get(MavenSettingsConfig.MavenSettingsConfigProvider.class)
    Config siteCfg = cfgProvider.newConfig(""${Projects.siteAbbr}-mvn-settings"",""${Projects.mavenSettingsName}"",null,null)

    GlobalConfigFiles.get().save(siteCfg)


    when:
    new DslScriptLoader(jm).runScript(file.text)

    then:
    noExceptionThrown()

    where:
    file &lt;&lt; jobFiles
</code></pre>

<p>That code doesn't seem to cause any issues for the Groovy compiler but it doesn't seem to be providing what my job is expecting to see either.  Any idea how to create config files when unit testing a Job DSL script?</p>
",https://stackoverflow.com/questions/47823365/how-to-supply-configuration-file-to-jobdsl-test,"['maven', 'jenkins', 'groovy', 'jenkins-job-dsl']",363,FALSE,1,1
Module name &quot;stardog&quot; has not been loaded yet for context: _. Use require([]),"<p>I'm trying to use Javascript for querying my local Stardog database. To do this, I'm using the code from here: <a href=""https://gist.github.com/ronmichael/4281566"" rel=""nofollow noreferrer"">https://gist.github.com/ronmichael/4281566</a>. I've installed npm, stardog, require without problems. However, when I try to run the following code:</p>
<pre><code>&lt;html&gt;
&lt;head&gt;
    &lt;link rel=&quot;stylesheet&quot; href=&quot;css/bootstrap.css&quot;&gt;
    &lt;link rel=&quot;stylesheet&quot; href=&quot;css/main.css&quot;&gt;
    &lt;script src=&quot;js/require.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js&quot;&gt;&lt;/script&gt;

&lt;/head&gt;



&lt;script&gt;
    const { Connection, query } = require('stardog');

    const conn = new Connection({
      username: 'admin',
      password: 'admin',
      endpoint: 'http://localhost:5820',
    });

    query.execute(conn, 'select distinct ?s where { ?s ?p ?o }', {
      limit: 10,
      offset: 0
    }).then(({ result }) =&gt; {
      console.log(result.results.bindings);
    });
&lt;/script&gt;


&lt;script src=&quot;js/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;js/jquery.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;js/bootstrap.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;js/bootstrap.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;js/main.js&quot;&gt;&lt;/script&gt;
</code></pre>

<p>I get the following error in my console:</p>
<pre><code>Uncaught Error: Module name &quot;stardog&quot; has not been loaded yet for context: _. Use require([])
http://requirejs.org/docs/errors.html#notloaded
    at F (require.js:7)
    at Object.m [as require] (require.js:26)
    at requirejs (require.js:32)
    at (index):22.
</code></pre>
<p>As far as I'm aware, I'm using require in the right way and since I've installed stardog properly, it should run. Could anyone point me in the right direction what I'm doing wrong here?</p>
<p>Edit: answer can be found here: <a href=""https://stackoverflow.com/questions/35788857/karma-unit-testing-module-name-react-has-not-been-loaded-yet-for-context"">Karma unit testing: Module name &quot;react&quot; has not been loaded yet for context: _. Use require([])</a></p>
",https://stackoverflow.com/questions/46789016/module-name-stardog-has-not-been-loaded-yet-for-context-use-require,"['javascript', 'node.js', 'requirejs', 'stardog']",511,FALSE,1,0
How can I test Angular4 Observables service method through MockBackend and FakeAsync,"<p>I have Angular4 service method which returns Observables. I have to use FakeAsync and tick() for unit testing. Can I use Mockbackend to mock webapi data, if I want to test fakeAsync and tick() for Observables? Is there any restriction of using MockBackend with FakeAsync for Observables?</p>

<p>is there any complete writeup on this subject? is there any sample code for the same? Sample code must cover 1.MockBackend 2. observables 3. fakeAsync 4.tick()</p>

<p>My idea is, I shouldn't use XHRBackend with FakeAsync. is my idea correct? It will be extremely helpful if you clarify this</p>
",https://stackoverflow.com/questions/46993582/how-can-i-test-angular4-observables-service-method-through-mockbackend-and-fakea,"['angular', 'unit-testing', 'mocking', 'karma-jasmine', 'observable']",55,FALSE,1,1
Unable to find bean when unit testing Spring MVC,"<p>I am new to unit testing in Spring MVC in Spring Boot. I want to be able to perform a simple test in which I call a html page and assert that it's the right page. The html page is bootstrapped and contains a a form.</p>

<p>Test:</p>

<pre><code>@Autowired
private LoginController loginController;
@Autowired
private findExistingUser findExistingUser;
@Autowired
MockMvc mockMvc;
@Test
public void testingLoginPage() throws Exception {
    RequestBuilder requestBuilder = MockMvcRequestBuilders.get(""/login"");
    MvcResult responseFromPage = mockMvc.perform(requestBuilder).andReturn();
    System.out.println(responseFromPage.toString());
}
</code></pre>

<p>Controller:</p>

<pre><code>@Autowired
findExistingUser findExistingUser;

@Autowired
private CustomerMongoRepository customerRepository;

@Autowired
private RequestRepository requestRepository;

@RequestMapping(value = HOME, method = RequestMethod.GET)
public String homepage(Customer customer) {
    .....
}
</code></pre>

<p>In the controller, the above controller utiliises both beans defined. When I run the test, I get the following stacktrace:</p>

<pre><code>`java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124) ~[spring-test-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83) ~[spring-test-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:47) ~[spring-boot-test-autoconfigure-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230) ~[spring-test-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228) [spring-test-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287) [spring-test-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289) [spring-test-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247) [spring-test-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) [spring-test-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) [spring-test-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137) [junit-4.12.jar:4.12]
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) [junit-rt.jar:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) [idea_rt.jar:na]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'loginController': Unsatisfied dependency expressed through field 'findExistingUser'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'matchingService.repository.findExistingUser' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) ~[spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) ~[spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) ~[spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120) ~[spring-boot-test-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98) ~[spring-test-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116) ~[spring-test-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    ... 28 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'matchingService.repository.findExistingUser' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    ... 46 common frames omitted


java.lang.IllegalStateException: Failed to load ApplicationContext

    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
    at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:47)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'loginController': Unsatisfied dependency expressed through field 'findExistingUser'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'matchingService.repository.findExistingUser' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
    ... 28 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'matchingService.repository.findExistingUser' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
    ... 46 more`
</code></pre>

<p>I'm not sure why I'm getting an NoSuchBeanFoundException when the the app works. I can go to the that path and it doesn't break</p>

<p>EDIT= This is the findExistingUser class:</p>

<pre><code>@Component
public class findExistingUser {
    @Autowired
    MongoTemplate mongoTemplate;
    public Customer findUser(String username, String password){
        Query query = new Query();
        query.addCriteria(Criteria.where(""username"").is(username).and(""password"").is(password));
        return mongoTemplate.findOne(query, Customer.class, ""customer"");
    }

    public Customer findUser(String username){

        Query query = new Query();
        query.addCriteria(Criteria.where(""username"").is(username));
        return mongoTemplate.findOne(query, Customer.class, ""customer"");
    }
}
</code></pre>
",https://stackoverflow.com/questions/43956383/unable-to-find-bean-when-unit-testing-spring-mvc,"['java', 'spring', 'unit-testing', 'spring-mvc']",1133,FALSE,1,0
Unit test RxJava Observables,"<p>I am new to RxJava. I have written Observable which is calling a rest api using restTemplate. I want to unit test my Observables created in service class.
I am aware of unit testing the rest api controller and service class using MockMVC. So need help on how to test my async endpoints in controller and Observalbes in service class using Mockito or MockMVC or any framework available.</p>

<p>Here is my code</p>

<blockquote>
  <p>SampleController.java</p>
</blockquote>

<pre><code>@RequestMapping(value = ""/"", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public DeferredResult&lt;List&lt;Response&gt;&gt; getresponse() {
        DeferredResult&lt;List&lt;Response&gt;&gt; response = new DeferredResult&lt;&gt;();
            service
              .fetchJson()
              .subscribe(result -&gt; response.setResult(result));
        return response;
    }
</code></pre>

<blockquote>
  <p>Service.java</p>
</blockquote>

<pre><code>@Override
    public Observable&lt;List&lt;Response&gt;&gt; fetchJson() {
        Observable&lt;List&lt;Response&gt;&gt; list = Observable.&lt;List&lt;Response&gt;&gt;create(
                subscriber -&gt; subscriber.onNext(this.invokeRestCall(APIURL)))
                .subscribeOn(Schedulers.from(executor));*/
        return list;
    }
private List&lt;Response&gt; invokeRestCall(String APIURL) {  

    Response[] responses = restTemplate.getForObject(APIURL, Response[].class);
    return Arrays.stream(responses).collect(Collectors.toList());
}
</code></pre>

<p>Please put a unit test case if anyone has written for testing controller endpoint which is async as well as for Observable in service class.</p>
",https://stackoverflow.com/questions/47935865/unit-test-rxjava-observables,['rx-java'],501,FALSE,1,1
How to mock PropertyConfigurator.configure() with PowerMockito?,"<p>I am using log4j to log messages and the log4j properties are coming from user. I have used <code>PropertyConfigurator.configure(Properties)</code> to configure the properties provided by the user. </p>

<p>While writing test cases i am using PowerMock to mock <code>PropertyConfigurator</code> and configure method as well. <code>configure()</code> method is a void static method. I am getting nullpointer exception while trying to do so. Any way to do that?</p>

<p>I have tried doing </p>

<pre><code>PowerMockito.mockStatic(PropertyConfigurator.class);
PowerMockito.doNothing().when(PropertyConfigurator.class);
PropertyConfigurator.configure(slf4jPropertiesMock);
</code></pre>

<p>This is not working.</p>

<p>If possible, is there any option of doing some other way around where i will be getting seme result without using <code>PropertyConfigurator.configure(Properties)</code>? In that case unit testing will be easy.</p>
",https://stackoverflow.com/questions/42369407/how-to-mock-propertyconfigurator-configure-with-powermockito,"['java', 'log4j', 'mockito', 'powermockito']",391,FALSE,1,1
Ruby on Rails - dependency injection conundrum,"<p>I'm working on a Rails 2 app and the lack of a dependency injection container has me wondering about dependencies and their impact on unit testing. I have the following:</p>

<p>Controller</p>

<pre><code>def some_action
  object_a = ClassA.new
  object_a.do_something
end
</code></pre>

<p>ClassA</p>

<pre><code>def do_something
  # some code, then...
  object_b = ClassB.new(params)
end
</code></pre>

<p>Because ClassA's do_something method instantiates object_b, I won't be able to mock object_b's behavior in a unit test. The way around that is to pass that initialization param from the controller to ClassA, then in ClassA's initialize, I could pass in the needed params for ClassB.</p>

<p>By doing that, however, I expose the controller to a knowledge about ClassB (it's init params) that it shouldn't need to know about.</p>

<p>Thoughts?</p>
",https://stackoverflow.com/questions/45358044/ruby-on-rails-dependency-injection-conundrum,"['ruby-on-rails', 'ruby', 'unit-testing', 'dependency-injection', 'ruby-on-rails-2']",566,FALSE,1,0
How to test SignalR 2 hub only notifies a single user?,"<p>I've worked through the <a href=""https://learn.microsoft.com/vi-vn/aspnet/signalr/overview/testing-and-debugging/unit-testing-signalr-applications"" rel=""nofollow noreferrer"">unit testing examples in the SignalR 2 documentation</a>, but now I'd like to test that my hub only notifies a single user in certain situations.</p>

<p>My hub code looks like this:</p>

<pre><code>public class NotificationsHub : Hub
{
    public void RaiseAlert(string message)
    {
        Clients.All.RaiseAlert(message);
    }

    public void RaiseNotificationAlert(string userId)
    {
        if (userId == null)
        {
            // Notify all clients
            Clients.All.RaiseAlert("""");
            return;
        }

        // Notify only the client for this userId
        Clients.User(userId).RaiseAlert("""");

    }
}
</code></pre>

<p>My unit test for checking that all clients are notified looks like this (it's based on the Microsoft example):</p>

<pre><code>[Test]
public void NotifiesAllUsersWhenNoUserIdSpecified()
{
    // Based on: https://learn.microsoft.com/vi-vn/aspnet/signalr/overview/testing-and-debugging/unit-testing-signalr-applications

    // Arrange

    // This is faking the 
    var mockClients = new Mock&lt;IClientContract&gt;();
    mockClients.Setup(m =&gt; m.RaiseAlert(It.IsAny&lt;string&gt;())).Verifiable();

    // A mock of our SignalR hub's clients 
    var mockClientConnCtx = new Mock&lt;IHubCallerConnectionContext&lt;dynamic&gt;&gt;();
    mockClientConnCtx.Setup(m =&gt; m.All).Returns(mockClients.Object);

    // Set the hub's connection context to the mock context
    var hub = new NotificationsHub
    {
        Clients = mockClientConnCtx.Object
    };

    // Action
    hub.RaiseNotificationAlert(null);

    // Assert
    mockClients.Verify(m =&gt; m.RaiseAlert(It.IsAny&lt;string&gt;()));
}
</code></pre>

<p>What I'm not sure about is how to change the collection of clients represented by the <code>var mockClients = new Mock&lt;IClientContract&gt;()</code> line into a group of individual clients so that I can then test that if I notify user 1, then users 2 and 3 weren't notified?</p>
",https://stackoverflow.com/questions/46953516/how-to-test-signalr-2-hub-only-notifies-a-single-user,"['asp.net', 'asp.net-mvc', 'unit-testing', 'signalr', 'signalr-hub']",2287,TRUE,1,1
Unit test DB calls,"<p>I have a class with static functions performing DB operations such as save, retrieve and delete. </p>

<p>My DB class:</p>

<pre><code>public final class DbUtils {

    static {
        DB_USER = //get from secure server
        DB_PASSWORD = //get from secure server
    }


    private static Connection establishConnection() {
    }

    private static void closeConnection(Connection connection) {

    }

    public static boolean saveObject(final Object graph, final Object map) {

        Connection connection = establishConnection();
        try {
            byte[] bgraph = ConvertToByte(graph);
            byte[] bmap = ConvertToByte(map);
            statement = connection.prepareStatement(""INSERT IGNORE INTO "" + TABLE_NAME + "" VALUES (?,?)"");
            statement.setObject(1, graph);
            statement.setObject(2, map);
            statement.executeUpdate();
            //Close statement within try catch
        } catch(Exception e) { // also other exception
            //catch to catch all type of exception
        }
        closeConnection(connection);
        return true;
    }

    public static Map&lt;String, Object&gt; retrieveObject(final String key) {
        Connection connection = establishConnection();
        //read byte and convert to object
        closeConnection(connection);
        return map;
    }

    public static boolean deleteObject(final String key) {
        Connection connection = establishConnection();
        //delete all object except object with key
        closeConnection(connection);
        return (affectedRow &gt;= 1);

    }

}
</code></pre>

<p>I wrote a unit test to test it like this:</p>

<pre><code>@RunWith(PowerMockRunner.class)
@PrepareForTest(DbUtils.class)
@SuppressStaticInitializationFor(""DbUtils"")
public class DbUtilsTest {

    @Mock
    Connection connection;

    @Mock
    ModuleDependencyGraph dependencyGraph;

    @Mock
    private Map&lt;String , String&gt; moduleSDF;

    @Test
    public void testSaveObject() throws Exception {
        PowerMockito.spy(DbUtils.class);
        PowerMockito.doReturn(connection).when(DbUtils.class, ""establishConnection"");
        Assert.assertTrue(DbUtils.saveObject(dependencyGraph, moduleSDF));
    }
}
</code></pre>

<p>When i try to run this unit test i get a null pointer error at the <code>statement = connection.prepareStatement</code> line which is to be expected i think since I'm not mocking the connection properly. How do I mock the connection properly? Also is the way I have written the <code>saveObject</code> test correct? I am new to unit-testing so I don't know the best-practices and how to cover all cases.</p>
",https://stackoverflow.com/questions/43915333/unit-test-db-calls,"['java', 'unit-testing', 'mockito', 'powermock', 'powermockito']",398,TRUE,0,1
How to test the sequence of function calls in C?,"<p>I'm using Gtest to perform unit testing to a C module. One of the requirements is to verify that a function called <code>Supervision_Log()</code> is called after executing several different functions.
The C file includes the following:</p>

<pre><code>void MainFunction (void)
{
    .
    .
    .
    /*Some code*/
    .
    .
    .
    ModeMonitoring();
    RadarStatusMonitoring();
    CameraStatusMonitoring();
    Supervision_Log(ModeManager);
}
</code></pre>

<p>I came to know that there's a facility in CppUTest called <code>mock().strictOrder()</code> that does what I need. But, is there any similar thing like that in Gtest? or what shall I do?</p>

<p>P.S.: We need to put a test case that fails if anyone changed the order of function calls. This test case will act as a guardian to this order against any changes in future releases.</p>
",https://stackoverflow.com/questions/43684196/how-to-test-the-sequence-of-function-calls-in-c,"['c', 'unit-testing', 'googletest', 'googlemock', 'cpputest']",789,FALSE,-1,2
Is it need to destroy the unused instances in c#,"<p>I have a MVC web application, it is an old and large source, now am modifying it for unit testing purpose. I need to initialize multiple objects in controller's constructor to abstract the DB accessing codes. like below,</p>

<pre><code>            public DownloadsController(ICustomerHistory customerHistory = null, ICustomerInfo customerInfo = null, IDownloadInfo downloadInfo = null, IVersionAccess versionAccess = null,
        ILeadInformation leadInfo = null, ISalesForce salesForce = null,IEvaluationReleaseBuildModel evaluationReleaseBuildModel=null)
    {
        _customerHistory = customerHistory ?? new CustomerHistory();
        _customerInfo = customerInfo ?? new CustomerInfo();
        _downloadInfo = downloadInfo ?? new DownloadInfo();
        _versionAccess = versionAccess ?? new VersionAccess();
        _leadInformation = leadInfo ?? new LeadInformation();
        _salesForce = salesForce ?? new SalesForce();
        _evaluationReleaseBuildModel = evaluationReleaseBuildModel ?? new EvaluationReleaseBuildModel();
    }
</code></pre>

<p>now I am afraid of if any memory problem will occur due to creating multiple objects like this. </p>

<ol>
<li>is it create a memory problem?.</li>
<li>do I need to destroy the object manually or GC will take care of this..?.</li>
<li>if we manually need to destroy, how to destroy it. I don't know when we need to destroy this object</li>
</ol>

<p>thanks in advance.</p>
",https://stackoverflow.com/questions/41605145/is-it-need-to-destroy-the-unused-instances-in-c,"['c#', 'garbage-collection', 'idisposable']",1063,TRUE,-1,2
How can we perform headless testing for Protractor Testing in Jenkins or other CI integration tool?,"<p>I found out that it is not good to use PhantomJS to perform Protractor Testing , instead use Karma Testing. However I want to do end-to-end testing not unit testing. </p>

<p>End to End meaning I want to set commands which will make the browser acts like human user. Therefore I cannot switch back to Karma . I tried to use PhantomJS with Protractor as <code>browsername</code> but it doesn't seem work. If anyone can share knowledge on how to use PhantomJS and Protractor for Jenkins (CI) integration environment will be great help or any other headless browser you know of. </p>
",https://stackoverflow.com/questions/44965653/how-can-we-perform-headless-testing-for-protractor-testing-in-jenkins-or-other-c,"['continuous-integration', 'protractor', 'karma-runner', 'headless']",336,TRUE,0,1
How to not connect to service when testing with Spring?,"<p>I have an application built with JHipster which contains several tests.
I created a simple configuration class that instantiate a bean connected to an external service as such :</p>

<pre><code>@Configuration
public class KurentoConfiguration {

    @Bean(name = ""kurentoClient"")
    public KurentoClient getKurentoClient(@Autowired ApplicationProperties applicationProperties) {
        return KurentoClient.create(applicationProperties.getKurento().getWsUrl());
    }
}
</code></pre>

<p>But as you would guess, this code crash during testing because the external service is not up but this code is still run during application context loading.</p>

<p>So I need to create a ""stateless"" version of this bean to be used during testing.</p>

<p>Here is a simple example of a test that fail because of my configuration : </p>

<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest(classes = Face2FaceApp.class)
public class LogsResourceIntTest {

    private MockMvc restLogsMockMvc;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);

        LogsResource logsResource = new LogsResource();
        this.restLogsMockMvc = MockMvcBuilders
            .standaloneSetup(logsResource)
            .build();
    }

    @Test
    public void getAllLogs()throws Exception {
        restLogsMockMvc.perform(get(""/management/logs""))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));
    }
}
</code></pre>

<p>What is the solution to make this bean not highly dependent of an external service during unit testing ?</p>
",https://stackoverflow.com/questions/43325228/how-to-not-connect-to-service-when-testing-with-spring,"['java', 'spring', 'testing', 'jhipster', 'kurento']",242,TRUE,0,2
Compare Vector of Doubles Using Catch,"<p>I'm using the <a href=""https://github.com/philsquared/Catch"" rel=""noreferrer"">Catch</a> unit testing framework, and I'd like to compare a vector of doubles. This <a href=""https://stackoverflow.com/questions/6718343/how-to-use-floating-point-tolerances-in-the-catch-framework"">other answer</a> suggests using Approx to compare floating point/double values, but this doesn't work for a vector of them. Is there any convenient way of accomplishing this?</p>

<p>EDIT: An Example</p>

<p>With the following code:</p>

<pre><code>#define CATCH_CONFIG_MAIN
#include ""catch.hpp""

TEST_CASE(""Compare Vectors"", ""[vector]"") {
    std::vector&lt;int&gt; vec1 = {0, 1, 2, 3};
    std::vector&lt;int&gt; vec2 = {0, 1, 2, 4};
    REQUIRE(vec1 == vec2);
}
</code></pre>

<p>The test fails with following report:</p>

<pre><code>-------------------------------------------------------------------------------
Compare Vectors
-------------------------------------------------------------------------------
test/UnitTests/test_Example/example.cc:4
...............................................................................

test/UnitTests/test_Example/example.cc:7: FAILED:
  REQUIRE( vec1 == vec2 )
with expansion:
  { 0, 1, 2, 3 } == { 0, 1, 2, 4 }

===============================================================================
test cases: 1 | 1 failed
assertions: 1 | 1 failed
</code></pre>

<p>But if I change the code as follows, I would want the test to pass, but obviously it doesn't.</p>

<pre><code>#define CATCH_CONFIG_MAIN
#include ""catch.hpp""

TEST_CASE(""Compare Vectors"", ""[vector]"") {
    std::vector&lt;double&gt; vec1 = {0, 1, 2, 3};
    std::vector&lt;double&gt; vec2 = {0, 1, 2, 3.000001};
    REQUIRE(vec1 == vec2);
}
</code></pre>

<p>I could loop through the elements and compare them one-by-one, but in the event of a discrepancy, it will be more difficult to determine the source of the error.</p>
",https://stackoverflow.com/questions/41863505/compare-vector-of-doubles-using-catch,"['c++', 'unit-testing', 'catch-unit-test']",2725,TRUE,5,2
How can I properly organize my JS code into a more traditional class structure?,"<p>I'm struggling with my JS code structure that's becoming apparent during my unit testing attempts.  I'm used to the class structure, but I'm a bit lost in the JS world where there aren't any classes.  I'm looking for a way to organize my code in the traditional class/constructor architecture.  Here's what I have:</p>

<pre><code>function ddGridSelector(primaryId, templateDefault, gridObj) {
    //set the variables
    this.primaryId = primaryId,
    this.defaultTemplate = templateDefault,
    this.gridObj = gridObj,
    this.gridObj.searchVal = '',

    this.init = ddgs_init
}

function ddgs_init(ddgs_obj) {
    ddgs_setDefaultTemplate(ddgs_obj);
    ddgs_initGrid(ddgs_obj);
    ddgs_initKendoWindow(ddgs_obj);
    ddgs_initKendoButton(ddgs_obj);
    ddgs_initResetButton(ddgs_obj);
    ddgs_addGridEventListener(ddgs_obj);
}

function ddgs_setDefaultTemplate(ddgs_obj) {
    //doing stuff
}

function ddgs_initGrid(ddgs_obj) {
    //more stuff
}
</code></pre>

<p>To call any of these...</p>

<pre><code>var ddGridSelector_new = new ddGridSelector('PrimaryIdentifier', templateDefault, gridObj);

ddGridSelector_new.init(ddGridSelector_new);
</code></pre>

<p>It seems really redundant to pass my object to my function that's specified in my constructor so I'm sure I'm missing something obvious here.  Really would appreciate some guidance on the matter.  I think I'm close to being on a good path.</p>
",https://stackoverflow.com/questions/45678652/how-can-i-properly-organize-my-js-code-into-a-more-traditional-class-structure,"['javascript', 'class', 'constructor']",1332,TRUE,0,3
How do I unit test my MainActivity?,"<p>From what I understand unit testing is more about writing code that is actually testable than it is about writing the actual tests.</p>

<p>In order to write testable code, in languages like java at least, I should probably be using dependency injection right? the app I'm writing currently does not use any DI.</p>

<p>But I wanted to start by writing unit tests for my MainActivity which looks like this:</p>

<pre><code>public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private ImageButton buttonPlay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //setting the orientation to landscape
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        //Prevent screen from dimming when app is running
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        //getting the button and adding click listener
        buttonPlay = (ImageButton) findViewById(R.id.buttonPlay);
        buttonPlay.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        //starting game activity
        startActivity(new Intent(this, GameActivity.class));
    }

}
</code></pre>

<p>Should I have a test for every method here? like one for onCreate(), setContentView(), setRequestedOrientation(), etc? Because Im not even sure what I would be asserting for those methods.</p>
",https://stackoverflow.com/questions/46142852/how-do-i-unit-test-my-mainactivity,"['java', 'android', 'unit-testing', 'dependency-injection']",1077,TRUE,0,1
What can i test on these types of methods?,"<p>Sorry for this orrible title, i did my best.
Maybe someone with more imagination can help me and this title.</p>

<p>I am a newbie in Unit Testing and I am a bit lost. I am reading ""The Art of Unit Tesing"" anyway.</p>

<p>I am using Entity Framework 6 for a WebApi application.
In this applicantion i use this pattern:</p>

<p>Api calls Service that calls Repository that return data to service that return data to API.</p>

<p>So, I have a tons of this methods:</p>

<p>API:</p>

<pre><code>public async Task&lt;IHttpActionResult&gt; GetUserById(Guid id)
{
    try
    {
        UserService userService = new UserService();
        return Ok(await userService.GetById(id));
    }
    catch(Exception ex)
    {
        return InternalServerError(ex);
    }
}
</code></pre>

<p>Service:</p>

<pre><code>public class UserService
{
    private IUserRepository userRepo;
    public IUserRepository userRepo { get =&gt; userRepo; set =&gt; userRepo = value }

    public async Task&lt;AspNetUser&gt; GetById(Guid id)
    {
        if(id == Guid.Empty() || id == null)
            return null;

        return await Task.Run(() =&gt; userRepo.GetById(id));
    }
}
</code></pre>

<p>Repo:</p>

<pre><code>public interface IUserRepository
{
    Task&lt;AspNetUser&gt; GetById(Guid id);
}

public class UserRepository: IUserRepository
{

    public async Task&lt;AspNetUser&gt; GetById(Guid id)
    {
        return DbSet.Where(i =&gt; i.Id == id).FirstOrDefault();
    }
}
</code></pre>

<p>What can be faulty here? what can go wrong? What i should test?</p>
",https://stackoverflow.com/questions/47873688/what-can-i-test-on-these-types-of-methods,"['c#', 'visual-studio', 'entity-framework', 'unit-testing', 'entity-framework-6']",160,TRUE,-1,2
Type mismatch when cloning the lines of the trait BufRead,"<p>To get better with Rust, I've decided to implement a simple lexer that analyzes some documents line by line.</p>

<p>As I have to iterate at least two times over the lines of the trait <code>BufRead</code>, I am cloning the lines of my <code>BufRead</code> but I get the following error:</p>

<pre class=""lang-none prettyprint-override""><code>error[E0271]: type mismatch resolving `&lt;std::io::Lines&lt;T&gt; as std::iter::Iterator&gt;::Item == &amp;_`
  --&gt; &lt;anon&gt;:18:23
   |
18 |     let lines = lines.cloned();
   |                       ^^^^^^ expected enum `std::result::Result`, found reference
   |
   = note: expected type `std::result::Result&lt;std::string::String, std::io::Error&gt;`
   = note:    found type `&amp;_

error[E0271]: type mismatch resolving `&lt;std::io::Lines&lt;T&gt; as std::iter::Iterator&gt;::Item == &amp;_`
</code></pre>

<p>I understand what the error is, but based on the <a href=""https://play.rust-lang.org/?code=use%20std%3A%3Afmt%3A%3AWrite%3B%0Ause%20std%3A%3Aio%3A%3A%7BBufRead%2C%20BufReader%2C%20Lines%2C%20Read%7D%3B%0A%0Apub%20struct%20DocumentMetadata%20%7B%0A%20%20%20%20language%3A%20String%2C%0A%20%20%20%20%2F%2F%20...%0A%7D%0A%0Apub%20fn%20analyze%3CT%3A%20BufRead%3E(document%3A%20T)%20-%3E%20Result%3CDocumentMetadata%2C%20()%3E%20%7B%0A%20%20%20%20let%20lines%20%3D%20document.lines()%3B%0A%20%20%20%20let%20language%20%3D%20guess_language(%26lines)%3B%0A%20%20%20%20%0A%20%20%20%20%2F%2F%20Do%20more%20lexical%20analysis%20based%20on%20document%20language%0A%0A%20%20%20%20Ok(DocumentMetadata%20%7B%0A%20%20%20%20%20%20%20%20language%3A%20language%2C%0A%20%20%20%20%20%20%20%20%2F%2F%20...%0A%20%20%20%20%7D)%0A%7D%0A%0Afn%20guess_language%3CT%3A%20BufRead%3E(lines%3A%20%26Lines%3CT%3E)%20-%3E%20String%20%7B%0A%20%20%20%20let%20lines%20%3D%20lines.cloned()%3B%0A%20%20%20%20for%20line%20in%20lines%20%7B%0A%20%20%20%20%20%20%20%20let%20line%20%3D%20line.unwrap()%3B%0A%20%20%20%20%20%20%20%20%2F%2F%20Try%20to%20guess%20language%0A%20%20%20%20%7D%0A%20%20%20%20%22en%22.to_string()%0A%7D%0A%0A%23%5Btest%5D%0Afn%20it_guesses_document_language()%20%7B%0A%20%20%20%20let%20mut%20document%20%3D%20String%3A%3Anew()%3B%0A%20%20%20%20writeln!(%26mut%20document%2C%20%22%23%20language%3A%20en%22).unwrap()%3B%0A%20%20%20%20let%20document%20%3D%20BufReader%3A%3Anew(document.as_str().as_bytes())%3B%0A%0A%20%20%20%20match%20analyze(document)%20%7B%0A%20%20%20%20%20%20%20%20Ok(metadata)%20%3D%3E%20assert_eq!(%22en%22.to_string()%2C%20metadata.language)%2C%0A%20%20%20%20%20%20%20%20Err(_)%20%3D%3E%20panic!()%2C%0A%20%20%20%20%7D%0A%7D&amp;version=stable&amp;backtrace=0"" rel=""nofollow noreferrer"">following code</a>, how can I tell the compiler what the <code>Item</code> of the <code>Iterator</code> should be so it can correctly cast the type?</p>

<pre><code>use std::fmt::Write;
use std::io::{BufRead, BufReader, Lines, Read};

pub struct DocumentMetadata {
    language: String,
    // ...
}

pub fn analyze&lt;T: BufRead&gt;(document: T) -&gt; Result&lt;DocumentMetadata, ()&gt; {
    let lines = document.lines();
    let language = guess_language(&amp;lines);

    // Do more lexical analysis based on document language

    Ok(DocumentMetadata {
        language: language,
        // ...
    })
}

fn guess_language&lt;T: BufRead&gt;(lines: &amp;Lines&lt;T&gt;) -&gt; String {
    let lines = lines.cloned();
    for line in lines {
        let line = line.unwrap();
        // Try to guess language
    }
    ""en"".to_string()
}

#[test]
fn it_guesses_document_language() {
    let mut document = String::new();
    writeln!(&amp;mut document, ""# language: en"").unwrap();
    let document = BufReader::new(document.as_str().as_bytes());

    match analyze(document) {
        Ok(metadata) =&gt; assert_eq!(""en"".to_string(), metadata.language),
        Err(_) =&gt; panic!(),
    }
}
</code></pre>

<p>For unit testing purpose, I am building a buffer with a <code>String</code> but in a normal usage I read it from a <code>File</code>.</p>
",https://stackoverflow.com/questions/42239398/type-mismatch-when-cloning-the-lines-of-the-trait-bufread,"['types', 'rust', 'buffer', 'clone', 'lines']",403,TRUE,0,1
"Writing unit test for scrapy, yielding item","<p>So I'm trying to get into a habit of writing unit tests for my project in scrapy, but the thing is, I'm not sure how to go about this. For example, in my self.parse(), I always yield the item rather than return the item, so whenever I call a self.parse(), it returns a generator object. What I tried doing what generating a fake response as shown here:</p>

<p><a href=""https://stackoverflow.com/questions/6456304/scrapy-unit-testing"">Scrapy Unit Testing</a></p>

<p>It seems to work if you are returning an item, but what about an item that is being yielded? How do you test the items that are being yielded?</p>
",https://stackoverflow.com/questions/43596653/writing-unit-test-for-scrapy-yielding-item,"['python', 'unit-testing', 'scrapy']",1168,TRUE,0,1
Why doesn&#39;t the C# Standard Library (mscorlib) provide abstractions for its classes?,"<p>The C# standard library currently does not provide abstractions/interfaces for most of its offerings, such as <code>File</code>, <code>HttpClient</code>, etc. (Actually, I'm not certain that this is the case with VB.NET, F#, etc., so let's stick with C# for now.) Yet, the demand is quite high, as unit testing practically requires you to mock out dependencies to IO, network, etc. There are quite a few homebrew solutions, most of them ""wrappers.""</p>

<ul>
<li><a href=""https://www.nuget.org/packages/System.IO.Abstractions"" rel=""nofollow noreferrer"" title=""System.IO.Abstractions"">System.IO.Abstractions</a></li>
<li><a href=""https://www.nuget.org/packages/SystemWrapper/"" rel=""nofollow noreferrer"" title=""SystemWrapper"">SystemWrapper</a></li>
</ul>

<p>What I'm curious about is why the standard library does not make this easier by simply including the interfaces within the library. Are there design reasons? Stylistic?</p>
",https://stackoverflow.com/questions/41675229/why-doesnt-the-c-standard-library-mscorlib-provide-abstractions-for-its-clas,"['c#', 'dependency-injection', 'mocking', 'abstraction']",108,TRUE,0,1
this.refs is undefined for shallow tests using enzyme on React native,"<p>I have a component which has 2 input text fields.</p>

<p>In the <code>componentDidMount()</code> method I am calling             <code>this.refs.password.focus();</code></p>

<p>There is some amount of tricky business logic sitting inside my <code>componentDidMount</code> but while doing a shallow unit test on <code>componentDidMount</code>, I get error</p>

<blockquote>
  <p>cannot access password of undefined</p>
</blockquote>

<p>I checked the instance of the shallow component and see that <code>this.refs</code> is <strong><em>undefined</em></strong>.
My question is how can we set this through tests?</p>

<p>Shallow has a second parameter which we can pass called as the context where we can set the context for unit testing but it seems to be doing nothing.</p>

<p>Any help around this area would be highly appreciated.</p>
",https://stackoverflow.com/questions/46480345/this-refs-is-undefined-for-shallow-tests-using-enzyme-on-react-native,"['reactjs', 'react-native', 'jestjs', 'enzyme']",9331,TRUE,5,2
Jest: Mark function as untestable,"<p>I would like to reach 100% coverage on my javascript project using <a href=""http://facebook.github.io/jest/"" rel=""nofollow noreferrer"">Jest</a>. Some methods, in my opinion, are not suited for unit testing and should be skipped when analyzing the code coverage. I would like to be able to do something like this:</p>

<pre><code>function toto() {
    // Some function performing stuff we don't want to test e.g. 
    // promise called inside a complex authorization process 
    // involving an integration test really hard to mock.  
}

expect(toto()).toBeUntestable();
</code></pre>

<p>The <a href=""http://facebook.github.io/jest/docs/en/api.html"" rel=""nofollow noreferrer"">Jest API</a> doesn't appear to have such possibility. It could be really useful since we could use this to aggregate bad code/hard-to-test code using this technique.</p>

<p>I'm really interested in your input regarding this situation since when it comes to tests, I find it really hard to have the right angle of approach.</p>
",https://stackoverflow.com/questions/46918713/jest-mark-function-as-untestable,"['javascript', 'ecmascript-6', 'jestjs']",346,FALSE,0,0
C# locking on only distinct objects (not by threads)?,"<p>I have a WS that returns information about a trading symbol. I want to cache the results of the WS locally. WS lookups should be performed concurrently for different symbols, but only 1 lookup at a time for each distinct symbol. I can't seem to do both of these things.</p>

<p>Here is a simple version of the locking I am trying:</p>

<pre><code>private readonly ReaderWriterLockSlim _cacheLock = new ReaderWriterLockSlim();
private readonly ConcurrentDictionary&lt;string, object&gt; _symbolLock = new ConcurrentDictionary&lt;string, object&gt;();
private readonly MemoryCache _cache = MemoryCache.Default;

public TradingItem GetLinking(string symbol)
{
    lock (_symbolLock.GetOrAdd(symbol, new object()))
    {
        _cacheLock.EnterUpgradeableReadLock();
        try
        {
            if (_cache.Contains(symbol))
            {
                return _cache.GetCacheItem(symbol);
            }

            TradingItem item = _resolverService.getLinking(symbol);                   
            _cacheLock.EnterWriteLock();
            try
            {
                _cache.Set(symbol, item, new CacheItemPolicy());
                return item;
            }
            finally
            {
                _cacheLock.ExitWriteLock();
            }
        }
        finally
        {
            _cacheLock.ExitUpgradeableReadLock();
        }
    }
}
</code></pre>

<p>As a side, this looks very strange but seems to do what I want in unit testing:</p>

<pre><code>lock (_symbolLock.GetOrAdd(symbol, new object()))
</code></pre>

<p><strong>My question is</strong>, 
How can I make the WS call <code>_resolverService.getLinking(symbol)</code> concurrent? Distinct symbols are currently getting throttled.</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/43766977/c-locking-on-only-distinct-objects-not-by-threads,"['c#', 'multithreading', 'web-services', 'locking']",45,TRUE,0,1
Splitting MFC from business logic,"<p>I'm trying to add basic unit testing in an old MFC applications. The goal is to eventually clean out MFC, but until then I wish to at least split the business logic from the MFC code to its own library.</p>

<p>My question is how I best can do this? I want to make as few changes as possible with the sole purpose of getting the business logic free from MFC so I can test it.</p>

<p>I realize that this is only the first step to get the code testable, I have read Working Effectively with Legacy Code.</p>
",https://stackoverflow.com/questions/41428558/splitting-mfc-from-business-logic,"['c++', 'visual-c++', 'mfc']",121,FALSE,0,0
Bable Not Compiling JSX for Jest/React,"<p>Im trying to setup unit testing with JEST for React.</p>

<p>My current set up is inside Package.json:</p>

<pre><code> ""jest"": {
""transform"": {
  ""^.+\\.jsx?$"": ""babel-jest""
},
""moduleFileExtensions"": [
  ""js"",
  ""json"",
  ""jsx""
]
</code></pre>

<p>}</p>

<p>And then inside .babelrc I have:</p>

<pre><code>{
    ""plugins"": [""syntax-dynamic-import"", ""transform-runtime""],
  ""presets"": [
    [
      ""es2015"",
      {
        ""modules"": false
      }
    ],
    ""react""
  ],
  ""env"": {
    ""test"": {
      ""presets"": [""es2015"", ""react""]
    }
  }
  }
</code></pre>

<p>I then run npm test, and it then starts run jest. However, it will error/Fail with :
Test suite failed to run with a error at </p>

<pre><code>                 componentDidMount=()=&gt;{
           |                      ^
        25 |         window.addEventListener('scroll', this.handleScroll)
        26 |     }
</code></pre>

<p>This is telling me that while the test enters the correct Component, it eventually stops at some es2015 syntax.</p>

<p>Do I have something set up wrong? It seems that babelrc is NOT actually transpiling before JEST tries to run its test? Is this correct?
My .babelrc is at the root level.</p>
",https://stackoverflow.com/questions/43621213/bable-not-compiling-jsx-for-jest-react,"['reactjs', 'babeljs', 'jestjs']",644,FALSE,0,1
Pre-requisites for getting started with Pact Contract Testing,"<p>Our organisation team structure is such that there is a new independent team of testers who is supposed to do API Testing. So as a member of this team, I do not have java code set up for every API project.</p>

<ol>
<li>So how can I write Consumer driven tests in that case?</li>
<li>Or do I need to setup every consumer java project before i start testing?</li>
<li>Or do I need to request all the API providers/consumers about this framework and ask them to implement the same.</li>
</ol>

<p>Currently, the testing is limited to manual testing via Postman and Unit Testing by developers.</p>
",https://stackoverflow.com/questions/43582516/pre-requisites-for-getting-started-with-pact-contract-testing,"['java', 'api', 'testing', 'automated-tests', 'pact']",374,TRUE,0,1
Converting a JSON object into a response object,"<p>I am trying to pass mock JSON data into my jasmine unit test.</p>
<p>The format of my JSON is like the one below:</p>
<pre><code>{   
   &quot;CompanyResponse&quot;:{    
      &quot;CompanyCreatedDate&quot;:&quot;1990-10-02&quot;,    
      &quot;RunDate&quot;:&quot;2&quot;,   
      &quot;LastChangedDate&quot;:&quot;2015-10-02&quot;,   
      &quot;CompanySummary&quot;: {   
         &quot;Id&quot;:&quot;Apple&quot;,   
         &quot;MaximumCredit&quot;:&quot;10000000&quot;,   
         &quot;Margin&quot;:&quot;60000000&quot;,    
         &quot;Limit&quot;:&quot;-1500000&quot;,    
         &quot;HistoricData&quot;:{    
            &quot;CompanyHistoricData&quot;: [   
               {  
                  &quot;LaunchDate&quot;:&quot;2008-08-31&quot;,  
                  &quot;Product&quot;:&quot;Iphone2&quot;,  
                  &quot;TotalProductsCreated&quot;:&quot;1000000&quot;,  
                  &quot;TotalProductsSold&quot;:&quot;800000&quot;,  
                  &quot;TotalReturns&quot;:&quot;200000&quot;,  
                  &quot;TotalMargin&quot;:&quot;600000&quot;  
               },  
               {  
                  &quot;LaunchDate&quot;:&quot;2010-08-31&quot;,  
                  &quot;Product&quot;:&quot;Iphone4&quot;,  
                  &quot;TotalProductsCreated&quot;:&quot;2000000&quot;,  
                  &quot;TotalProductsSold&quot;:&quot;1500000&quot;,  
                  &quot;TotalReturns&quot;:&quot;350000&quot;,  
                  &quot;TotalMargin&quot;:&quot;800000&quot;  
               }  
            ]  
         },  
         &quot;RefurbishedData&quot;: {  
            &quot;CompanyRefurbished&quot;: [  
               {  
                  &quot;Id&quot;:&quot;Apple.201221.12&quot;,  
                  &quot;ProductId&quot;:&quot;iph-213454&quot;,  
                  &quot;StartDate&quot;:&quot;2015-09-07&quot;,  
                  &quot;FinishDate&quot;:&quot;2015-09-10&quot;,  
                  &quot;CostOfRefurbishing&quot;:&quot;50&quot;  
               },  
               {  
                  &quot;Id&quot;:&quot;Apple.201228.12&quot;,  
                  &quot;ProductId&quot;:&quot;iph-4155655&quot;,  
                  &quot;StartDate&quot;:&quot;2015-09-10&quot;,    
                  &quot;FinishDate&quot;:&quot;2015-09-12&quot;,  
                  &quot;CostOfRefurbishing&quot;:&quot;85&quot;  
               }  
            ]  
         }  
      }  
   }  
}  
</code></pre>
<p>I am using the above JSON to pass on to a function similar to the one below for unit testing:</p>
<pre><code>public getTotal(response: CompanyResponse): void {    
  var companySummary = response.CompanySummary;    
  
  //gets total 'CostOfRefurbishing' for all phones    
  var totalRefurbishmentAmount :number = 0;

  for (let companyRefurbishments of companySummary.RefurbishedData) {
    totalRefurbishmentAmount += Number.parseInt(companyRefurbishments.CostOfRefurbishing.toString());
  }
}
</code></pre>
<hr />
<p>The problem I am facing is that I am not able to pass <code>CompanyResponse</code> as a whole to the <code>getTotal()</code> function. It doesn't work even if I use <code>JSON.stringify()</code> because it just converts it to a string and it doesn't work if I use <code>JSON.parse()</code> either as it converts it back into the Object format.</p>
<p>Here's how we call the <code>getTotal()</code> method in a normal scenario:</p>
<pre><code>export class MyService{    
 async CompanySummary(): Promise&lt;CompanySummaryResponse&gt;    
{    
    const response = await this.http.fetch('CompanySummary');    
    return await response.json();    
  }    
}    

var myService = new MyService();    
CompanySummary: CompanySummaryResponse;    
CompanySummary = await myService.CompanySummary();    
this.calculator.getTotal(CompanySummary);    
</code></pre>
<p>Cheers,
Guru</p>
",https://stackoverflow.com/questions/44037816/converting-a-json-object-into-a-response-object,"['javascript', 'json', 'jasmine', 'aurelia']",9191,TRUE,5,1
How to unit test a custom XMLHttpRequest-based progress bar,"<p>I would like to unit test a custom XHR function that's used on a jQuery AJAX request to drive a progress bar showing upload/download progress. I'm using Sinon.js useFakeXMLHttpRequest to test other aspects of this code, including the AJAX request itself, but (if I understand correctly) useFakeXMLHttpRequest would replace my custom XHR function rather than testing it. What would be some useful approaches to consider for unit testing the custom XHR function itself?</p>

<p>Here is the custom XHR function that I want to unit test:</p>

<pre><code>function xhr() {
    var xhr = new window.XMLHttpRequest();

    xhr.upload.addEventListener('progress', function(event) {
        if (event.lengthComputable) {
            doProgressBar(event.loaded / event.total * 50);
        }
    }, false);

    xhr.addEventListener('progress', function(event) {
        if (event.lengthComputable) {
            doProgressBar(50 + event.loaded / event.total * 50);
        }
    }, false);

    return xhr;
}
</code></pre>

<p>And here is the jQuery AJAX request that uses it:</p>

<pre><code>$.ajax({
    type: 'POST',
    url: '/my/url',
    dataType: 'json',
    contentType: 'application/json',
    data: JSON.stringify({ foo: bar }),
    success: onSuccess,
    error: onError,
    xhr: xhr
});
</code></pre>

<p>Thank you!</p>
",https://stackoverflow.com/questions/45356244/how-to-unit-test-a-custom-xmlhttprequest-based-progress-bar,"['javascript', 'jquery', 'ajax', 'unit-testing', 'xmlhttprequest']",873,FALSE,0,1
Testing Chef script output in production,"<p>I have a Chef script that creates and configures couple of Linux servers on Amazon AWS. During the configuration step, it installs some software and installs the code from our project.</p>

<p>Is there a tool that can read the output of the Chef script (probably the log files) and provide me with information about the execution of the script? And point out if any step did not go smoothly?</p>

<p>There seems to be lots of content on TDD using Chef and unit testing but did not find any related to actual automated (or semi-automated) verification when the scripts are executed in production.</p>
",https://stackoverflow.com/questions/46196930/testing-chef-script-output-in-production,['chef-infra'],34,TRUE,0,1
python mock.mock_calls does not follow calls made inside @timeout decorated function,"<p>I'm unit-testing a function with mock, and trying to test if a call to mock object was made. In the code below the <code>requests.post</code> object is mocked, and I track the <code>requests.post.mock_calls</code> list.</p>

<p>In the following code the </p>

<p>Code construct:</p>

<pre><code>import timeout_decorator

def block_funds(trader_id, amounts):

    @timeout_decorator.timeout(3, use_signals=False)
    def _block_funds(block_url, amounts):

        # requests.post.mock_calls empty here
        result = requests.post(url=block_url, data=amounts)
        # requests.post.mock_calls here has correct call recorded

        return result.status_code

    block_url = 'http:/someurl/somepath/{trader_id}'.format(trader_id=trader_id)

    try:

        # requests.post.mock_calls empty here
        code = _block_funds(block_url, amounts)
        # requests.post.mock_calls empty again here

    except timeout_decorator.TimeoutError as ex:
        logger.error('request failed')
        code = 500

    return code
</code></pre>

<p>After the call to <code>code = _block_funds(block_url, amounts)</code> I expect the mock object to keep record of all calls to it, but the <code>mock_calls</code> list gets emptied as soon as the execution exits the internal timeout wrapped function <code>_block_funds()</code>. Mock object is certainly the same, I'm following the mock IDs to ensure object has not changed.</p>

<p>What I'm doing wrong and how to make the mock not forget it's calls?</p>
",https://stackoverflow.com/questions/47480370/python-mock-mock-calls-does-not-follow-calls-made-inside-timeout-decorated-func,"['python', 'unit-testing', 'mocking']",196,TRUE,0,1
Injecting Single Instance HttpClient with specific HttpMessageHandler,"<p>As part of an ASP.Net Core project that I am working on I have a requirement to communicate with a number of different Rest based API Endpoints from within my WebApi.  To achieve this I am using a number of service classes that each instantiate a static <code>HttpClient</code>.  Essentially I have a service class for each of the Rest based endpoints that the WebApi connects to.  </p>

<p>An example of how the static <code>HttpClient</code> is instantiated in each of the service classes can be seen below.</p>

<pre><code>private static HttpClient _client = new HttpClient()
{
    BaseAddress = new Uri(""http://endpointurlexample""),            
};
</code></pre>

<p>Whilst the above is working well, it does not allow for effective unit testing of the service classes that are using <code>HttpClient</code>.  To enable me to carry out unit testing I have a fake <code>HttpMessageHandler</code> that I would like to use for the <code>HttpClient</code> in my unit tests, whilst the <code>HttpClient</code> is instantiated as above however I am unable to apply the fake <code>HttpMessageHandler</code> as part of my unit tests.</p>

<p>What is the best way for the <code>HttpClient</code> in the service classes to remain a single instance throughout the application (one instance per endpoint), but to allow a different <code>HttpMessageHandler</code> to be applied during the unit tests?</p>

<p>One approach I have thought of would be not to use a static field to hold the <code>HttpClient</code> in the service classes, rather to allow it to be injected via constructor injection using a singleton lifecycle, which would allow me to specify a <code>HttpClient</code> with the desired <code>HttpMessageHandler</code> during unit tests, the other option I thought of would be to use a <code>HttpClient</code> Factory Class that instantiated the <code>HttpClient</code>s in static fields that could then be retrieved by injecting the <code>HttpClient</code> factory into the service classes, again allowing a different implementation with the relevant <code>HttpMessageHandler</code> to be returned in unit tests.  None of the above feel particularly clean however and it feels like there must be a better way?</p>

<p>Any questions, let me know.</p>
",https://stackoverflow.com/questions/43118874/injecting-single-instance-httpclient-with-specific-httpmessagehandler,"['c#', 'asp.net-core', 'asp.net-core-mvc', '.net-core', 'dotnet-httpclient']",21805,TRUE,15,5
Unittest project Azure Functions could not load file or assembly &#39;Newtonsoft.Json&#39;,"<p>I created a test project for a Function App as mentioned <a href=""https://stackoverflow.com/a/46290387/3652378"">here</a>. The Http triggered Azure Function I wrote, uses dependency injection (<a href=""https://github.com/introtocomputerscience/azure-function-autofac-dependency-injection"" rel=""nofollow noreferrer"">AzureFunctions.AutoFac</a>) and looks like this:  </p>

<pre><code>[DependencyInjectionConfig(typeof(DependencyConfig))]
public static class CreateDeclarationsFunction
{
    [FunctionName(""CreateDeclarationsFunction"")]
    public static HttpResponseMessage Run(
        [HttpTrigger(AuthorizationLevel.Function, ""post"", Route = ""CreateDeclarations"")]HttpRequestMessage req,
        TraceWriter log,
        [Inject]IDeclarationDataService declarationDataService,
        [Inject]IClientDataService clientDataService)
    {
        log.Info(""Http triggered function: CreateDeclarationsFunction  processed a request."");

        try
        {
            var clients = clientDataService.GetAll().ToList();

            foreach (var client in clients)
            {
                // Create and save new declaration for each client
                declarationDataService.CreateAndSaveNew(client.Id);
            }
        }
        catch (Exception ex)
        {
            return req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
        }

        return req.CreateResponse(HttpStatusCode.OK);
    }
}
</code></pre>

<p>And the unittest class (with Moq, Shouldly and NBuilder):</p>

<pre><code>[TestClass]
public class CreateDeclarationsFunctionTest
{
    private Mock&lt;IDeclarationDataService&gt; _declarationDataService;
    private Mock&lt;IClientDataService&gt; _clientDataService;

    [TestInitialize]
    public void Initialize()
    {
        _declarationDataService = new Mock&lt;IDeclarationDataService&gt;();
        _clientDataService = new Mock&lt;IClientDataService&gt;();
    }

    [TestMethod]
    public void CreateDeclarations_ReturnsOk()
    {
        // Arrange
        var clients = Builder&lt;Client&gt;.CreateListOfSize(10).Build();

        _declarationDataService.Setup(x =&gt; x.CreateAndSaveNew(It.IsAny&lt;int&gt;()))
            .Returns(Builder&lt;Declaration&gt;.CreateNew().Build);

        // Act &gt; Exception by calling the Run method
        var result = CreateDeclarationsFunction.Run(CreateRequest(""""), new TraceWriterStub(TraceLevel.Info),
            _declarationDataService.Object, _clientDataService.Object);

        // Assert
        // TODO
    }

    private static HttpRequestMessage CreateRequest(string json)
    {
        // Just a mocked request
        var request = new HttpRequestMessage
        {
            Method = HttpMethod.Post,
            RequestUri = new Uri(""https://localhost""),
            Content = new StringContent(json, Encoding.UTF8, ""application/json"")
        };

        return request;
    }
}
</code></pre>

<p>When I run this unittest, it gives an exception. </p>

<pre><code>Result StackTrace:  
at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter..ctor()
   at System.Net.Http.Formatting.JsonMediaTypeFormatter..ctor()
   at System.Net.Http.Formatting.MediaTypeFormatterCollection.CreateDefaultFormatters()
   at System.Web.Http.HttpConfiguration.DefaultFormatters(HttpConfiguration config)
   at System.Web.Http.HttpConfiguration..ctor(HttpRouteCollection routes)
   at System.Net.Http.HttpRequestMessageExtensions.CreateErrorResponse(HttpRequestMessage request, HttpStatusCode statusCode, Func`2 errorCreator)
   at System.Net.Http.HttpRequestMessageExtensions.CreateErrorResponse(HttpRequestMessage request, HttpStatusCode statusCode, Exception exception)
   at FunctionApp.CreateDeclarationsFunction.Run(HttpRequestMessage req, TraceWriter log, IDeclarationDataService declarationDataService, IClientDataService clientDataService)
   at FunctionApp.Tests.CreateDeclarationsFunctionTest.CreateDeclarations_ReturnsOk() in C:\TFS\...\FunctionApp.Tests\CreateDeclarationsFunctionTest.cs:line 63
Result Message: 
Test method FunctionApp.Tests.CreateDeclarationsFunctionTest.CreateDeclarations_ReturnsOk threw exception: 
System.IO.FileLoadException: Could not load file or assembly 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
</code></pre>

<p>The <code>FunctionApp</code> has 2 nested references to <code>Newtonsoft.Json (9.0.1)</code>, but none to version <code>6.0.0.0</code>. </p>

<p><code>Dependencies</code> > <code>Nuget</code> > <code>Microsoft.NET``.Sdk.Functions (1.0.6)</code> > <code>Newtonsoft.Json (9.0.1)</code></p>

<p><code>Dependencies</code> > <code>Nuget</code> > <code>AzureFunctions.Autofac (2.0.0)</code> > <code>Microsoft.Azure.Webjobs (2.1.0-beta4)</code> > <code>Newtonsoft.Json (9.0.1)</code></p>

<p>The test project has a reference to the <code>FunctionApp</code> project. The exception is only shown when unit testing and not when its running (and being invoked from the browser). 
Does anybody have a solution for upper exception? Thanks. </p>

<p><strong>UPDATE</strong></p>

<p>I found out that the <code>System.IO.FileLoadException</code> occurs when returning <code>req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);</code></p>

<p>When returning <code>req.CreateResponse(HttpStatusCode.OK);</code> instead, it does not give the mentioned exception. </p>
",https://stackoverflow.com/questions/47288398/unittest-project-azure-functions-could-not-load-file-or-assembly-newtonsoft-jso,"['c#', '.net', 'unit-testing', 'azure', 'azure-functions']",672,TRUE,4,1
Unable to test a component with a service,"<p>After reading this <a href=""https://angular.io/docs/ts/latest/guide/testing.html#!#stub-observable"" rel=""nofollow noreferrer"">guide</a> I've decided to test my simple login page which contains just 2 input boxes and a submit button. The component then uses a <code>LoginService</code> to pass these data to backend. </p>

<p>( <em>Also note that I'm new to Unit testing as such, so I'm not sure if this is a good approach as how to test such component.</em> )</p>

<p>For starters, I only wanted to check, if the initial value of <code>#username</code> input element is empty. But I couldn't even make the spec to work due to the below reported issues:</p>

<pre><code>Chrome 55.0.2883 (Windows 7 0.0.0) LoginComponent Username field should be empty FAILED
        Failed: Unexpected value 'Http' imported by the module 'DynamicTestModule'
        Error: Unexpected value 'Http' imported by the module 'DynamicTestModule'
        TypeError: Cannot read property 'detectChanges' of undefined
Chrome 55.0.2883 (Windows 7 0.0.0): Executed 4 of 4 (1 FAILED) (0 secs / 0.348 secs)
</code></pre>

<p>When I tried deleting the Http module, I got this error :</p>

<pre><code>Chrome 55.0.2883 (Windows 7 0.0.0) LoginComponent Username field should be empty FAILED
        Error: DI Error
        Error: Uncaught (in promise): Error: No provider for Http!
        TypeError: Cannot read property 'detectChanges' of undefined
Chrome 55.0.2883 (Windows 7 0.0.0): Executed 4 of 4 (1 FAILED) (0 secs / 0.456 secs)
</code></pre>

<p><strong>login.component.html</strong></p>

<pre><code>&lt;div class=""login jumbotron center-block""&gt;
  &lt;h1&gt;Login&lt;/h1&gt;

  &lt;form (ngSubmit)=""onSubmit($event)"" #loginForm=""ngForm""&gt;

    &lt;div class=""form-group""&gt;
      &lt;label for=""username""&gt;Username&lt;/label&gt;
      &lt;input type=""text"" class=""form-control"" [(ngModel)]=""model.username"" name=""username"" 
              placeholder=""Username"" #username=""ngModel"" required&gt;
      &lt;div [hidden]=""username.valid || username.pristine"" class=""alert alert-danger""&gt; Username is required &lt;/div&gt;
    &lt;/div&gt;
    &lt;div class=""form-group""&gt;
      &lt;label for=""password""&gt;Password&lt;/label&gt;
      &lt;input type=""password"" class=""form-control"" [(ngModel)]=""model.password"" name=""password"" placeholder=""Password"" #password=""ngModel"" required&gt;
      &lt;div [hidden]=""password.valid || password.pristine"" class=""alert alert-danger""&gt; Password is required &lt;/div&gt;
    &lt;/div&gt;

    &lt;button type=""submit"" class=""btn btn-default"" [disabled]=""!loginForm.form.valid"" &gt;Submit&lt;/button&gt;
    &lt;a [routerLink]=""['/signup']""&gt;Click here to Signup&lt;/a&gt;
  &lt;/form&gt;
&lt;/div&gt;
</code></pre>

<p><strong>login.component.ts</strong></p>

<pre><code>import { Component }      from '@angular/core';
import { Router }         from '@angular/router';
import { LoginService }   from '../services/login.service';
import { User }           from '../extensions/user.class';

@Component({
  moduleId: module.id,
  selector: 'login',
  templateUrl: '../templates/login.component.html',
  styleUrls: [ '../styles/login.component.css' ],
  providers: [ LoginService ]
})
export class LoginComponent {

  private submitted = false;
  private model = new User();

  constructor(
    private router: Router,
    private loginService: LoginService
  ) {}

  public onSubmit(event: any): void {
    event.preventDefault();
    if ( ! this.submitted ) {
      this.submitted = true;

      if ( this.model.username &amp;&amp; this.model.password ) {
        this.loginService.login(this.model).then( (token) =&gt; {
          localStorage.setItem('id_token', token.id);
          this.router.navigate(['home']);
        }).catch( (error) =&gt; this.onLoginFailed(error) );
      } else {
        console.warn('No username or password provided');
      }

    }
  }

  private onLoginFailed( error: any ): void { 
    //// errors are already handled in login-service ////
    console.error(error);
    this.submitted = false; /// reset form submit funcitonality ///
  }

  public signup(event: any): void {
    event.preventDefault();
    this.router.navigate(['signup']);
  }
}
</code></pre>

<p><strong>login.component.spec.ts</strong></p>

<pre><code>import { async }                             from '@angular/core/testing';

import { FormsModule }                       from '@angular/forms';
import { RouterTestingModule }               from '@angular/router/testing';
import { Component }                         from '@angular/core';
import { Location }                          from '@angular/common';

import { LoginComponent }                    from './login.component';
import { LoginService }                      from '../services/login.service';
import { Http }   from '@angular/http';

import { User }           from '../extensions/user.class';

@Component({
  template: ''
})
class DummyComponent{}

class LoginServiceStub {
  login( user: User ){
    return true;
  }
}

describe('LoginComponent', () =&gt; {
  let comp:      LoginComponent;
  let fixture:   ComponentFixture&lt;LoginComponent&gt;;
  let de:        DebugElement;
  let el:        HTMLElement;
  let location:  Location;

  // async beforeEach
  beforeEach( async(() =&gt; {

    TestBed.configureTestingModule({
      declarations: [ LoginComponent, DummyComponent ], // declare the test component
      providers: [
       { provide: LoginService,  useClass: LoginServiceStub }
      ],
      imports: [ 
        FormsModule , 
        RouterTestingModule.withRoutes([
         { path: 'singup', component: DummyComponent }
        ])
      ]
    }).compileComponents()  // compile template and css
    .then( () =&gt; {
      fixture = TestBed.createComponent(LoginComponent);
      comp = fixture.componentInstance; // LoginComponent test instance
      de = fixture.debugElement.query(By.css('input[name=""username""]'));
      el = de.nativeElement;
    });

  }));

  it('Username field should be empty', () =&gt; {
    fixture.detectChanges();
    expect(el.textContent).toContain('');
  });

});
</code></pre>
",https://stackoverflow.com/questions/41680280/unable-to-test-a-component-with-a-service,"['unit-testing', 'angular', 'jasmine', 'karma-jasmine', 'angular2-testing']",2577,TRUE,4,2
Is NSInMemoryStoreType Incompatible with NSBatchDeleteRequest?,"<p>I am currently unit testing a layer that interacts with Core Data. It saves, deletes, and updates an <code>Item</code> object. However, my test that attempts to save a couple of <code>Item</code>s and then perform a batch deletion keeps failing.</p>

<p>This is <code>Item</code>:</p>

<pre class=""lang-swift prettyprint-override""><code>extension Item {

    // MARK: - Properties

    @NSManaged public var date: NSDate

    @NSManaged public var isTaxable: Bool

    @NSManaged public var name: String

    @NSManaged public var price: NSDecimalNumber

    @NSManaged public var quantity: Double

    // MARK: - Fetch Requests

    @nonobjc public class func fetchRequest() -&gt; NSFetchRequest&lt;Item&gt; { return NSFetchRequest&lt;Item&gt;(entityName: ""Item"") }

    // MARK: - Validation

    // Manual validation for `Decimal` values is needed. A radar is still open, which is located at https://openradar.appspot.com/13677527.
    public override func validateValue(_ value: AutoreleasingUnsafeMutablePointer&lt;AnyObject?&gt;, forKey key: String) throws {
        if key == ""price"", let decimal = value.pointee as? Decimal { if decimal &lt; Decimal(0.01) { throw NSError(domain: NSCocoaErrorDomain, code: 1620, userInfo: [""Item"": self]) } }
        if key == ""quantity"", let double = value.pointee as? Double { if double == 0 { throw NSError(domain: NSCocoaErrorDomain, code: 1620, userInfo: [""Item"": self]) } }
    }

}
</code></pre>

<p>This is the object that interacts with Core Data, <code>CoreDataStack</code>:</p>

<pre class=""lang-swift prettyprint-override""><code>internal class CoreDataStack {

    // MARK: - Properties

    private let modelName: String

    internal lazy var storeContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: self.modelName)
        container.loadPersistentStores { (storeDescription, error) in if let error = error as NSError? { fatalError(""Unresolved error \(error), \(error.userInfo)"") } }
        return container
    }()

    internal lazy var managedContext: NSManagedObjectContext = { return self.storeContainer.viewContext }()

    // MARK: - Initialization

    internal init(modelName: String = ""Cart"") { self.modelName = modelName }

    // MARK: - Saving

    internal func saveContext() throws {
        guard managedContext.hasChanges else { return }
        do { try managedContext.save() } catch let error as NSError { throw error }
    }

}
</code></pre>

<p>This is the object that manages persistence with Core Data:</p>

<pre class=""lang-swift prettyprint-override""><code>internal final class ItemPersistenceService {

    // MARK: - Properties

    private let coreDataStack: CoreDataStack

    // MARK: - Initialization

    internal init(coreDataStack: CoreDataStack) {
        self.coreDataStack = coreDataStack
        print(""init(coreDataStack:) - ItemPersistenceService"")
    }

    // MARK: - Saving

    @discardableResult internal func saveItem(withInformation information: ItemInformation) throws -&gt; Item {
        let item = Item(context: coreDataStack.managedContext)
        item.name = information.name
        item.quantity = information.quantity
        item.price = information.price as NSDecimalNumber
        item.date = information.date as NSDate
        item.isTaxable = information.isTaxable
        do {
            try coreDataStack.saveContext()
        } catch let error as NSError {
            throw error
        }
        return item
    }

    // MARK: - Deleting

    internal func delete(item: Item) throws {
        coreDataStack.managedContext.delete(item)
        do {
            try coreDataStack.saveContext()
        } catch let error as NSError {
            throw error
        }
    }

    internal func deleteAllItems() throws {
        let fetchRequest = NSFetchRequest&lt;NSFetchRequestResult&gt;(entityName: Item.description())
        let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
        do {
            try coreDataStack.managedContext.persistentStoreCoordinator?.execute(deleteRequest, with: coreDataStack.managedContext)
        } catch let error as NSError {
            throw error
        }
    }

     // MARK: - Fetching

    internal func itemsCount() throws -&gt; Int {
        let fetchRequest = NSFetchRequest&lt;NSNumber&gt;(entityName: Item.description())
        fetchRequest.resultType = .countResultType
        do {
            let result = try coreDataStack.managedContext.fetch(fetchRequest)
            guard let count = result.first?.intValue else { fatalError(""Invalid result"") }
            return count
        } catch {
            throw error
        }
    }

}
</code></pre>

<p>This is the <code>CoreDataStack</code> subclass that I use for testing, which contains an in-memory store:</p>

<pre class=""lang-swift prettyprint-override""><code>internal final class TestCoreDataStack: CoreDataStack {

    // MARK: - Initialization

    internal override init(modelName: String = ""Cart"") {
        super.init(modelName: modelName)
        let persistentStoreDescription = NSPersistentStoreDescription()
        persistentStoreDescription.type = NSInMemoryStoreType
        let container = NSPersistentContainer(name: modelName)
        container.persistentStoreDescriptions = [persistentStoreDescription]
        container.loadPersistentStores { (storeDescription, error) in
            if let error = error as NSError? { fatalError(""Unresolved error \(error), \(error.userInfo)"") }
            self.storeContainer = container
        }
    }

}
</code></pre>

<p>Finally, this is the test that keeps failing:</p>

<pre class=""lang-swift prettyprint-override""><code>internal func test_ItemPersistenceService_Delete_All_Managed_Object_Context_Saved() {
    do {
        try service.saveItem(withInformation: information)
        try service.saveItem(withInformation: information)
    } catch { XCTFail(""Expected `Item`"") }
    expectation(forNotification: .NSManagedObjectContextDidSave, object: coreDataStack.managedContext) { (notification) in return true }
    do { try service.deleteAllItems() } catch { XCTFail(""Expected deletion"") }
    waitForExpectations(timeout: 2.0) { error in XCTAssertNil(error, ""Expected save to occur"") }
}
</code></pre>

<p><strong>Questions</strong></p>

<p>Is NSInMemoryStoreType incompatible with NSBatchDeleteRequest?</p>

<p>If not, then what am I doing incorrectly that is causing my test to fail repeatedly?</p>
",https://stackoverflow.com/questions/45134431/is-nsinmemorystoretype-incompatible-with-nsbatchdeleterequest,"['core-data', 'nspersistentstore', 'nsbatchdeleterequest']",1119,TRUE,4,2
Webpack DefinePlugin in Karma (how to access vaiables?),"<p>I have an Angular 2 project building with Webpack.</p>

<p>I use DefinePlugin to pass variables (such as ENV) to the application.</p>

<p>For unit testing I do the same (ie. use DefinePlugin in webpack.test.js too)</p>

<p>In my tests, I want to be able to change the variables to be able to access some branches. For example:</p>

<pre><code>showMonitor = (ENV === 'development' &amp;&amp; !AOT);
</code></pre>

<p>In my test spec, I want to simulate AOT being false </p>

<p>How can I access AOT from the test spec? I have a fixture and component instance as follows:</p>

<pre><code>const fixture = TestBed.createComponent(AppComponent);
const instance = fixture.componentInstance;
</code></pre>

<p>But I can't access AOT since its a global variable defined by the DefinePlugin</p>

<p>Any ideas will help a lot!</p>

<p>Cheers!</p>
",https://stackoverflow.com/questions/42768824/webpack-defineplugin-in-karma-how-to-access-vaiables,"['angular', 'webpack', 'karma-runner']",391,FALSE,4,0
@NgRx/Effects with Jasmine Marble testing,"<p>I am creating a web app using Angular 4 and NgRx 4 and I am having some problems with unit testing.</p>

<p>I created the test below to see if I could get the return value of an effect:</p>

<pre><code>it('should load orders and call load orders complete action', fakeAsync(() =&gt; {

    let responsePayload;
    const mockData = [{ id: 1 }, { id: 2 }, { id: 3 }];

    const orderService = TestBed.get(OrderService);
    const testScheduler = new TestScheduler(null);
    orderService.getAllOrders.and.returnValue(hot('a|', { a: mockData }));

    actions = Observable.of(new orderActions.LoadAllOrdersAction(new Date()));

    const subscription = effects.loadAllOrders$.subscribe((result: orderActions.LoadAllOrdersCompleteAction) =&gt; {
      responsePayload = result.payload;
    });


    getTestScheduler().flush();
    tick();
    expect(responsePayload).toEqual(mockData);

    subscription.unsubscribe();

  }));
</code></pre>

<p>And this is the effect that I am testing:</p>

<pre><code>@Injectable()
export class OrderEffect {

  @Effect()
  loadAllOrders$: Observable&lt;Action&gt; = this.actions.ofType(orderActions.LOAD_ALL_ORDERS)
    .withLatestFrom(this.store$) // Get the latest state from the store and add as the second value of the array below
    .switchMap((input: any[]) =&gt; {
      const action: orderActions.LoadAllOrdersAction = input[0];
      const store: AppState = input[1];

      return Observable.timer(0, store.orders.pollingInterval) // Timer to create the polling effect.
        .switchMap(() =&gt; this.orderService.getAllOrders(action.payload)
          .map((orders: Array&lt;any&gt;) =&gt; new orderActions.LoadAllOrdersCompleteAction(orders))
          .catch(error =&gt; Observable.throw(new orderActions.LoadAllOrdersFailAction(error)))
        );
    });

  constructor(private actions: Actions, private orderService: OrderService, private store$: Store&lt;AppState&gt;) { }
}
</code></pre>

<p>However when I run this test I get the following error: <code>Expected undefined to equal [ Object({ id: 1 }), Object({ id: 2 }), Object({ id: 3 }) ].</code></p>

<p>If I change this line of the test: <code>orderService.getAllOrders.and.returnValue(hot('a|', { a: mockData }));</code> to: <code>orderService.getAllOrders.and.returnValue(Observable.of(mockData));</code> then everything works, so I think that I am doing something wrong with the marble testing.</p>

<p>Please note that I am using the <code>jasmine-marbles</code> to import the <code>hot</code> and <code>cold</code> functions.</p>

<p>Below is the full code of the test that is working.</p>

<pre><code>  it('should load orders and call load orders complete action', fakeAsync(() =&gt; {

    let responsePayload;
    const mockData = [{ id: 1 }, { id: 2 }, { id: 3 }];

    const orderService = TestBed.get(OrderService);
    const testScheduler = new TestScheduler(null);
    orderService.getAllOrders.and.returnValue(Observable.of(mockData));

    actions = Observable.of(new orderActions.LoadAllOrdersAction(new Date()));

    const subscription = effects.loadAllOrders$.subscribe((result: orderActions.LoadAllOrdersCompleteAction) =&gt; {
      responsePayload = result.payload;
    });

    tick();
    expect(responsePayload).toEqual(mockData);

    subscription.unsubscribe();

  }));
</code></pre>
",https://stackoverflow.com/questions/45872112/ngrx-effects-with-jasmine-marble-testing,"['angular', 'unit-testing', 'rxjs', 'ngrx']",1103,FALSE,3,0
can we create unit tests for custom widgets in a django app?,"<p>I'm new with unit testing in django, I have referred to the django <a href=""https://docs.djangoproject.com/en/1.11/topics/testing/"" rel=""nofollow noreferrer"">documentation</a> to write unit tests for views, forms and models. But a question came to my mind about widgets if they could be also tested, since unit tests are made to test every single unit in the project.</p>

<p>For example I have a widget that let me write multiple emails in one inputText using a plugin and the widget as follow is made to change <code>'</code> to <code>""</code> so that the plugin can work.</p>

<pre><code>class MultiEmailWidget(Input):
def value_from_datadict(self, data, files, name):
    if name in data:
        if data[name]:
            return data[name].replace(']' ,'').replace('[','').replace('""' ,'').replace(',' , '\n')
    return None
def render_value(self , value):
    """"""
    change ' to "" because multiple_email.js do split with ""
    """"""

    if value:
        return str(value).replace(""'"",'""')
    return value

def render(self, name, value, attrs=None):
    value = self.render_value(value)
    return super(MultiEmailWidget, self).render(name, value, attrs)
</code></pre>

<p>Is this widget testable ? 
Or do somebody have some useful links about testing widgets in django ? (if this is testable ofcourse)</p>

<p>Thank you in advance :)</p>
",https://stackoverflow.com/questions/46406557/can-we-create-unit-tests-for-custom-widgets-in-a-django-app,"['django', 'unit-testing', 'widget']",690,FALSE,3,0
How do you test that a new instance of an object has been created?,"<p>I'm using C#, xUnit, and Moq for unit testing. I have an object with a property of a complex type. To ""clear"" the property and all its properties, I do this:</p>

<pre><code>this.ComplexTypeInstance = new ComplexType();
</code></pre>

<p>Now I'm trying to assert that ComplexTypeInstance has been assigned to a brand new object. My first thought was to compare ComplexTypeInstance to new ComplexType() and see if they are equal. But to do something like that I think I'd have to override the equals operator. Is there any way to easily check that all properties are set to their defaults? Or is there a way to assert that I've newed up the object?</p>
",https://stackoverflow.com/questions/42686456/how-do-you-test-that-a-new-instance-of-an-object-has-been-created,"['c#', 'unit-testing', 'xunit']",2182,TRUE,3,2
How to traverse a shallow component nested in ThemeProvider HOC?,"<p>Following up the issue on <a href=""https://github.com/cssinjs/react-jss/issues/184"" rel=""nofollow noreferrer"">Github</a>, I have a component <code>Comp</code> that when exported, is wrapped with <code>injectSheet</code> from <code>reactjss</code>. <em>Please see the setup on <a href=""https://codesandbox.io/s/674jknj4z"" rel=""nofollow noreferrer"">codesandbox</a></em>.</p>

<p>In a unit test, I'd like to assert that that component contains <code>&lt;a&gt;</code>, which it does (see codesandbox), but the test fails regardless:</p>

<pre><code>describe(""&lt;Comp /&gt; component"", () =&gt; {
  const wrapper = shallow(&lt;Comp /&gt;);

  it(""should render a &lt;a&gt;"", () =&gt; {
    expect(wrapper.find('a')).to.have.length(1);
  });
});
</code></pre>

<p>I get <code>Error: [undefined] Please use ThemeProvider to be able to use WithTheme</code>. So my natural (perhaps not the correct?) reaction was to wrap the component with <code>ThemeProvider</code>:</p>

<pre><code>const wrapper = shallow(
  &lt;ThemeProvider theme={{}}&gt;
    &lt;Comp /&gt;
  &lt;/ThemeProvider&gt;
)
</code></pre>

<p>Then I get <code>AssertionError: expected { length: 0 } to have a length of 1 but got 0</code>.</p>

<p>I tried a whole slew of approaches, including calling <code>dive</code>, <code>find</code> or <code>first</code> with an extra <code>shallow</code> call, but I would <strong>always</strong> end up with <code>Please use ThemeProvider to be able to use WithTheme</code>:</p>

<pre><code>// 1. dive(), as suggested in
// https://github.com/cssinjs/react-jss/issues/30#issuecomment-268373765
expect(wrapper.dive('Comp')).to.have.length(1);
expect(wrapper.dive('Comp').find('a')).to.have.length(1);
expect(wrapper.dive().find('a')).to.have.length(1);

// 2. find() / first(), as suggested in https://github.com/airbnb/enzyme/issues/539
expect(wrapper.find(Comp).shallow().find('a')).to.have.length(1);
expect(wrapper.first().shallow().find('a')).to.have.length(1);
</code></pre>

<p>Any ideas here? I am a bit new to unit testing with React, so I would appreciate if someone could enlighten me on this ;)</p>
",https://stackoverflow.com/questions/47704909/how-to-traverse-a-shallow-component-nested-in-themeprovider-hoc,"['javascript', 'reactjs', 'enzyme', 'jss']",492,FALSE,3,1
TSQL Unit Test tools 2017: SQL Server Data Tools 2017 vs tSQLt,"<p>I have a new project that needs SQL Server unit test, and CI/CD with VSTS.</p>

<p>Below is the features that are required</p>

<ul>
<li><p>SQL server unit test against stored procedure, initial target tables setup for each test and clean up</p></li>
<li><p>Unit test in sql</p></li>
<li><p>CI/CD with VSTS and Git</p></li>
<li><p>Easy setup and easy to use</p></li>
</ul>

<p>I looked into SSDT 2017, which seems good. But it seems it lacks a feature where common setup script can be shared easily between each test in Pre-Test step. It might lack other features that should be available for daily usage. But I might be wrong.</p>

<p>Which tool fits better for general sql server unit testing in 2017?</p>

<p><a href=""https://www.visualstudio.com/vs/ssdt/"" rel=""noreferrer"">SQL Server Data Tools for Visual Studio</a></p>

<p><a href=""http://tsqlt.org/"" rel=""noreferrer"">TSQLT</a></p>
",https://stackoverflow.com/questions/47860037/tsql-unit-test-tools-2017-sql-server-data-tools-2017-vs-tsqlt,"['sql-server', 'visual-studio', 'sql-server-data-tools', 'tsqlt', 'sql-server-unit-testing']",5445,TRUE,12,3
Multiple clauses in EUnit&#39;s assertMatch?,"<p>I am using Erlang's <a href=""http://erlang.org/doc/apps/eunit/chapter.html"" rel=""nofollow noreferrer"">EUnit</a> for unit testing an application.</p>

<p>I want to assert that a certain test value is between 2 and 3.  <a href=""https://github.com/richcarl/eunit/issues/10"" rel=""nofollow noreferrer"">There's no built-in support for this</a>, so I am trying to use a pair of guards, like this:</p>

<pre><code>myTestCase -&gt;
  ?assertMatch({ok, V} when V&gt;2, V&lt;3,
               unitUnderTest() % expected to return 2.54232...
  ).
</code></pre>

<p>This tries to use the <a href=""http://learnyousomeerlang.com/syntax-in-functions"" rel=""nofollow noreferrer"">guard syntax</a> for <code>andalso</code>.</p>

<p>However, this does not work, presumably because Erlang's parser can't tell the difference between multiple guards and multiple arguments to <code>assertMatch</code>.  I tried wrapping various things in parentheses, but haven't found anything that works.  On the other hand, when I reduce the expression to just one clause, it succeeds.</p>

<p>Is there a way to express multiple clauses here?</p>
",https://stackoverflow.com/questions/44212785/multiple-clauses-in-eunits-assertmatch,"['erlang', 'eunit']",506,TRUE,2,2
C# and flags/bit tests - &quot;Except if&quot; - ... how to?,"<p>Messy title, but am feeling the veins in my brain snap in vain while trying to find a ""pretty"" (=readable &amp; easily maintainable) way to figure out a way to do something like this in simple terms:</p>

<pre><code>[Flags]
enum SomeFlags {
    _unset_ = 0,
    SomeFlag = 1 &lt;&lt; 1,
    ExceptionalFlag = 1 &lt;&lt; 16,
}
private SomeFlags someenum = SomeFlags._unset_;

...

int times = 1;
while(times &gt; 0)
{
     times--;
     ...
     rnd_num = /*make random number in range X to Y*/ fooRandom();
     ...
     if (rnd_num &lt;= arbitrary_const &amp;&amp;
          ( !someenum.HasFlag(Flags.SomeFlag)
            [[except if]]
            somenum.HasFlag(Flags.ExceptionalFlag) )
     )
     {
        /* do stuff if numeric condition matches, AND someenum does
          -not- contain SomeFlag, EXCEPT if someenum has -also-
          ExceptionalFlag set alongside SomeFlag */
     }
     else if (...yaddayadda...)
     ...
     else {
         times++;
         someenum |= SomeFlags.ExceptionalFlag;
         continue;
     }
     break;
}
</code></pre>

<p>Maybe?:</p>

<pre><code>if ( /* some_numeric_condition == */ true &amp;&amp;
    (!someenum.HasFlag(Flags.SomeFlag) ||
      someenum.HasFlag(Flags.SomeFlag | Flags.ExceptionalFlag) ) )
{ /* foobar */ }
</code></pre>

<p>Is there any ""simpler"" way to express such?
Just clearing my mind, as that sort of test's buried behind/in pretty lots of code and I'm not familiar with 'unit testing' stuff yet.</p>

<p>Truth table which is sought for:</p>

<pre><code>SomeFlag    SomeFlag|ExceptionalFlag  True?
   0           0                      true
   1           0                      false
   0           1                      false
   1           1                      true
</code></pre>

<p>edit: clarifying a little (I hope) - the if stuff is within a loop, in this particular case... and conditions change.</p>

<p>edit2: edited for truth table sought... And mucked that up, so - another #3 go!</p>
",https://stackoverflow.com/questions/41567121/c-and-flags-bit-tests-except-if-how-to,['c#'],142,TRUE,2,2
Where does the string in ExpectedException.NoExceptionMessage appear?,"<p>I am doing some unit testing in Visual studio: </p>

<pre><code>/// &lt;summary&gt;
/// Padding14 should throw an ArgumentOutOfRangeException if string is longer than 14
/// &lt;/summary&gt;
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException), ""Missing ArgumentOutOfRange exception when argument too long"")]
public void TestPadding14_ArgTooLong()
{
    string input = ""abcdefghijklmnop""; 
    input.Padding14();

}
</code></pre>

<p>This line tests the function:</p>

<pre><code>public static string Padding14(this string input)
{
    if (input == """")
    {
        throw new ArgumentNullException(""StringExtensions.Padding14: Input string empty"");
    }
    if (input.Length &gt; 14)
    {
        //throw new ArgumentOutOfRangeException(""stringExtenstions.Padding14: Input string too long"");
    }
    //throw new NotImplementedException();
    return null;
}
</code></pre>

<p>Expected outcome: The test should fail, and the information about the failure should include the string ""Missing ArgumentOutOfRange exception when argument too long"", because the exception in the tested function is commented out.</p>

<p>The test is working as expected, but i cannot find the string i put in the second argument of ExpectedException anywhere. Not in the test explorer window, not in the output -> Tests window.</p>

<p>So where is it supposed to go, and what could cause it not to appear there? This applies to both Visual studio 2015 and 2017, community edition.</p>
",https://stackoverflow.com/questions/42454181/where-does-the-string-in-expectedexception-noexceptionmessage-appear,"['c#', 'string', 'visual-studio', 'unit-testing']",369,TRUE,2,1
Unit tests fail when tests run as set?,"<p><a href=""https://github.com/kbajpai/algo"" rel=""nofollow noreferrer"">Link to repo</a></p>

<p>I'm <strong>learning</strong> Java Unit Testing, and wrote some Unit Tests for some algorithms.</p>

<p>When I run the Unit Tests <strong>individually</strong>, they pass fine, but when I run them <strong>as a set</strong>, only the first one passes and rest of them fails.</p>

<p>For example, Test1, Test2, and Test3 are run as a set; then Test1 passes, and Test2 and Test3 fail.</p>

<p>If I comment out code for Test1, and run Test2, and Test3; Test2 passes and Test3 fails.</p>

<p>When I run them individually, they all pass.</p>

<p><strong>Code for the Algorithm</strong>:</p>

<pre><code>package com.kbajpai.algorithms.ds;

class Node {
    private static Node sInstance;

    static {
        try {
            sInstance = new Node();
        } catch (Exception e) {
            throw new RuntimeException(""Could not create singleton instance"");
        }
    }

    static Node getInstance() {
        return sInstance;
    }

    private long mData;
    private int mCount;
    private Node mLeft;
    private Node mRight;

    private Node() {
        mCount = 0;
        mLeft = null;
        mRight = null;
    }

    private Node(long data) {
        mData = data;
        mLeft = null;
        mRight = null;
        mCount = 1;
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();

        if (mCount == 0) {
            return """";
        } else {
            if (mLeft != null) {
                sb.append(mLeft.toString()).append("","");
            }
            sb.append(mData).append("":"").append(mCount);
            if (mRight != null) {
                sb.append("","").append(mRight.toString());
            }
        }
        return sb.toString();
    }

    private void insert(long data) {
        if (mCount == 0) {
            mData = data;
            mCount++;
        } else {
            if (data == mData) {
                mCount++;
            } else if (data &gt; mData) {
                if (mRight != null) {
                    mRight.insert(data);
                } else {
                    mRight = new Node(data);
                }
            } else {
                if (mLeft != null) {
                    mLeft.insert(data);
                } else {
                    mLeft = new Node(data);
                }
            }
        }
    }

    String getScores(long[] data) {
        for (long aData : data) {
            insert(aData);
        }

        return toString();
    }
}
</code></pre>

<p><strong>Code for UnitTests:</strong></p>

<pre><code>package com.kbajpai.algorithms.ds;

import com.kbajpai.datagen.ds.ScoreStatsData;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

import static junit.framework.TestCase.assertTrue;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class NodeTest {
    @Test
    public void test01ScoreStats_Ten() throws Exception {
        long[] data = ScoreStatsData.getInstance().getNumbers(ScoreStatsData.FILE_TEN);
        String expected = ScoreStatsData.getInstance().getStats(ScoreStatsData.FILE_TEN_STATS);

        assertTrue(expected.equals(Node.getInstance().getScores(data)));
    }

    @Test
    public void test02ScoreStats_Hundred() throws Exception {
        long[] data = ScoreStatsData.getInstance().getNumbers(ScoreStatsData.FILE_HUNDRED);
        String expected = ScoreStatsData.getInstance().getStats(ScoreStatsData.FILE_HUNDRED_STATS);

        String actual = Node.getInstance().getScores(data);
        assertTrue(expected.equals(actual));
    }

    @Test
    public void test03ScoreStats_Thousand() throws Exception {
        long[] data = ScoreStatsData.getInstance().getNumbers(ScoreStatsData.FILE_THOUSAND);
        String expected = ScoreStatsData.getInstance().getStats(ScoreStatsData.FILE_THOUSAND_STATS);

        String actual = Node.getInstance().getScores(data);
        assertTrue(expected.equals(actual));
    }

    @Test
    public void test04ScoreStats_Million() throws Exception {
        long[] data = ScoreStatsData.getInstance().getNumbers(ScoreStatsData.FILE_MILLION);
        String expected = ScoreStatsData.getInstance().getStats(ScoreStatsData.FILE_MILLION_STATS);

        String actual = Node.getInstance().getScores(data);
        assertTrue(expected.equals(actual));
    }

    @Test
    public void test05ScoreStats_TenMillion() throws Exception {
        long[] data = ScoreStatsData.getInstance().getNumbers(ScoreStatsData.FILE_TEN_MILLION);
        String expected = ScoreStatsData.getInstance().getStats(ScoreStatsData.FILE_TEN_MILLION_STATS);

        String actual = Node.getInstance().getScores(data);
        assertTrue(expected.equals(actual));
    }
}
</code></pre>

<p>N.B:</p>

<ul>
<li>Using <strong>Gradle</strong> with <strong>IntelliJ IDEA</strong></li>
<li><a href=""https://github.com/kbajpai/algo"" rel=""nofollow noreferrer"">Link to repo</a></li>
</ul>
",https://stackoverflow.com/questions/41987478/unit-tests-fail-when-tests-run-as-set,"['java', 'unit-testing', 'intellij-idea', 'gradle', 'junit']",1326,TRUE,2,1
Why does Spark call &quot;main&quot; instead of using an interface like &quot;SparkJob&quot;?,"<p>Spark calls the main method on the specified class, and that main method is expected to construct a SparkContext or SparkSession.  Configuration not specified explicitly, like master URL, will come from properties passed in on the command line or from configuration files.</p>

<p>What I'm wondering about: why does Spark look for a <code>main</code> method instead of using an interface like <code>SparkJob</code> with a <code>run</code> method that takes <code>SparkSession</code> as an injected argument?  This is a common convention with other forms of managed code that run inside a container; you could still have a <code>main</code> method to construct and inject a <code>SparkSession</code> in local mode for unit testing.</p>

<p>In other words why not this</p>

<pre><code>public class MySparkJob implements SparkJob {
  public void run(SparkSession spark) {
  }
}
</code></pre>

<p>instead of this:</p>

<pre><code>public class MySparkJob {
  public static void main(String[] args) {
     SparkSession spark = ...
  }
}
</code></pre>
",https://stackoverflow.com/questions/45260812/why-does-spark-call-main-instead-of-using-an-interface-like-sparkjob,['apache-spark'],118,FALSE,2,0
ASP.Net Core RouteBuilder and Dependency Injection,"<p>I'm experimenting with routing in ASP.NET Core 2.0. I have a class that wraps the <code>System.DateTime.UtcNow</code> functionality (for simpler Unit Testing)</p>

<pre><code>public interface IDateTimeWrapper
{
    DateTime UtcNow();
}

public sealed class DateTimeWrapper : IDateTimeWrapper
{
    public DateTime UtcNow()
    {
        return DateTime.UtcNow;
    }
}
</code></pre>

<p>This is used by a class that has a single method <code>Execute</code> which writes the result of the <code>DateTimeWrapper</code> to the <code>HttpResponse</code></p>

<pre><code>public class WhatIsTheTimeHandler
{
    private readonly IDateTimeWrapper _dateTimeWrapper;

    public WhatIsTheTimeHandler(
        IDateTimeWrapper dateTimeWrapper)
    {
        this._dateTimeWrapper = dateTimeWrapper;
    }

    public async Task Execute(Microsoft.AspNetCore.Http.HttpContext httpContext)
    {
        httpContext.Response.StatusCode = 200;            
        await httpContext.Response.WriteAsync(this._dateTimeWrapper.UtcNow().ToString());
    }
}
</code></pre>

<p>In <code>Startup</code> I want any requests going to <code>/whatisthetime/</code> to be handled by the <code>WhatIsTheTimeHandler</code> (see the !!! comment).</p>

<pre><code>public sealed class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder();

        builder.SetBasePath(env.ContentRootPath);
        builder.AddJsonFile(""appsettings.json"", false, true);
        // we must lowercase the json file path due to linux file name case sensitivity
        builder.AddJsonFile($""appsettings.{env.EnvironmentName.ToLower()}.json"", false, true);
        builder.AddEnvironmentVariables();

        this.Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; set; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRouting();

        services.AddScoped&lt;IDateTimeWrapper, DateTimeWrapper&gt;();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        var routeBuilder = new Microsoft.AspNetCore.Routing.RouteBuilder(app);

        // !!!
        // I want to do something like
        // routeBuilder.MapGet(""whatisthetime"", WhatIsTheTimeHandler.Execute);

        var routes = routeBuilder.Build();
        app.UseRouter(routes);
    }
}
</code></pre>

<p>I can't do what I want above because <code>WhatIsTheTimeHandler.Execute</code> is an instance method. I.e. the error:</p>

<blockquote>
  <p>An object reference is required for the non-static field, method or property 'WhatIsTheTimeHandler.Execute(HttpContext)'
  Cannot access non-static method in static context).</p>
</blockquote>

<p>If I make it <code>static</code> then I won't be able to use the <code>_dateTimeWrapper</code> instance member.</p>

<p>Any ideas?</p>
",https://stackoverflow.com/questions/47673463/asp-net-core-routebuilder-and-dependency-injection,"['c#', 'asp.net-core', 'url-routing']",2565,TRUE,2,1
How to mock Entity Framework using IdentityDbContext?,"<p>I am working on an ASP.NET MVC web app with individual authentication to store details about users cars. I will need to unit test the web app by mocking the entity framework, thus I have read I will need to implement an interface for the <code>ApplicationDbContext</code> class. </p>

<p>This is my first attempt at using entity framework and I just wanted to check whether my <code>ApplicationDbContext</code> class and interface will be suitable for mocking the framework when unit testing?</p>

<pre><code>public interface IApplicationDbContext : IDisposable
{
    IDbSet&lt;ApplicationUser&gt; Users { get; set; }
    DbSet&lt;CarModel&gt; Cars { get; set; }
    int SaveChanges();
    void MarkAsModified(CarModel car);
}

public class ApplicationDbContext : IdentityDbContext&lt;ApplicationUser&gt;, IApplicationDbContext
{
    public ApplicationDbContext()
        : base(""ApplicationDb"", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    public DbSet&lt;CarModel&gt; Cars { get; set; }

    public override IDbSet&lt;ApplicationUser&gt; Users { get; set; }

    public void MarkAsModified(CarModel car)
    {
        Entry(car).State = EntityState.Modified;
    }
}
</code></pre>

<p>Some of the classes were formed by autocorrect using Visual Studios ""Quick Actions"". Could anyone explain why the <code>ApplicationUser</code> models require <code>IDbSet</code>, but the <code>CarModels</code> require just <code>DbSet</code>, and why the <code>Users</code> in the <code>ApplicationDbContext</code> class require an override?</p>
",https://stackoverflow.com/questions/46274868/how-to-mock-entity-framework-using-identitydbcontext,"['c#', 'asp.net', 'asp.net-mvc', 'entity-framework', 'unit-testing']",1598,TRUE,2,1
What are examples of test suite property uses in CPPUnit? (CPPUNIT_TEST_SUITE_PROPERTY),"<p>I joined a project where CPPUnit is used for unit testing and will be adding some tests that probably share setup and teardown code.  In researching this more I came across </p>

<pre><code>CPPUNIT_TEST_SUITE_PROPERTY
</code></pre>

<p>(from <a href=""https://people.freedesktop.org/~mmohrhard/cppunit/group___writing_test_fixture.html"">https://people.freedesktop.org/~mmohrhard/cppunit/group___writing_test_fixture.html</a>)</p>

<p>Its description says </p>

<blockquote>
  <p>Adds a property to the test suite builder context.</p>
</blockquote>

<p><a href=""http://cppunit.sourceforge.net/doc/cvs/group___writing_test_fixture.html"">http://cppunit.sourceforge.net/doc/cvs/group___writing_test_fixture.html</a> says the following:</p>

<blockquote>
  <p>Adds a property to the test suite builder context</p>
</blockquote>

<p>I am not sure what the expected use or purpose of that would be, though it <strong><em>appears</em></strong> like it could be useful for sharing common information, etc.  I don't see examples of its use.  </p>

<p><strong>What is the value of this and are there some examples to point me to?</strong></p>
",https://stackoverflow.com/questions/41986088/what-are-examples-of-test-suite-property-uses-in-cppunit-cppunit-test-suite-pr,"['c++', 'unit-testing', 'cppunit']",387,TRUE,7,1
Testing Angular Controller that is dependent on a factory,"<p>I am new to Unit Testing, I am trying to test a controller that is dependent  on a factory that makes the calls to a URL to fetch data. </p>

<p>Below is my controller code(The sqResultReviewTable module code is in a separate file):</p>

<pre><code>    (function () {
angular.module('sqResultReviewTable')
       .controller('sqResultReviewTableController', fetchJsonData);  //fetchJsonData is the controller function name.
function fetchJsonData($scope, fetchDataFromJsonFile) {              // fetchDataFromJsonFile is the the service that return the data that is fetched fron the JSON file.
    labResultData = fetchDataFromJsonFile.getOrders().then(function (returnedArray) {   //function call to the service method getOrders and storing the resultant array in a varaible called labResultData.
        $scope.labResultData = returnedArray;                   //Assigning labresultData to the $scope.
        console.log($scope.labResultData);
    });
}
})()
</code></pre>

<p>And here is my factory service(The factory service is in a separate file):</p>

<pre><code>    (function () {
angular.module('sqResultReviewTable')
.factory('fetchDataFromJsonFile', ['$http', function ($http) {
    return {
        getOrders: function () {                //getOrders is function which can be used to fetch data from the JSON file. It return an Array.
            return $http({
                method: 'GET',
                url: '/ResultReview/GetDataFromService',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(function (response) {
                return JSON.parse(response.data);           //Returning the array that is fetched from the JSON file.
            });
        }
    };
}]);
})();
</code></pre>

<p>Below is test case that I have tried:</p>

<pre><code>    describe('sqResultReviewTable', function () {    
beforeEach(angular.mock.module('sqResultReviewTable'));
var $controller;
beforeEach(angular.mock.inject(function(_$controller_){
    $controller = _$controller_;
}));
describe('resultReviewTableController', function () {
    it('should have an array of length 4', function () {
        var $scope = {};
        var controller = $controller('sqResultReviewTableController', { $scope: $scope });
        var len = $scope.labResultData.length;
        expect(len).toBe(4);
    });
});
});
</code></pre>

<p>I am getting this error:
    TypeError: Cannot read property 'length' of undefined</p>

<p>Any help regarding this is appreciated. Thank you.</p>

<p>Edit 1:
I also tried in this manner, but the result is same
TypeError: Cannot read property 'length' of undefined</p>

<pre><code>    describe('resultReviewTableController', function () {
beforeEach(module('sqResultReviewTable'));
var $scope;
describe('Table Controller', function () {
    beforeEach(inject(function ($rootScope, $controller) {
        $scope = $rootScope.$new();
        $controller('sqResultReviewTableController', {$scope : $scope});
    }));
    it('should contain an array of length 4', function () {
        expect($scope.labResultData.length).toBe(4);
    });
});
});
</code></pre>
",https://stackoverflow.com/questions/43361156/testing-angular-controller-that-is-dependent-on-a-factory,"['angularjs', 'unit-testing', 'jasmine']",45,FALSE,1,0
"One or more child tests had errors, Exception doesn&#39;t have a stacktrace","<p>I am fairly new to unit testing and am trying to conduct a test using Nunit but get the following message when running the test plan. </p>

<p>I have tried to step through the code, however it doesnt hit a breakpoint, so I am guessing at the moment that its failing before its hitting the Test Method </p>

<blockquote>
  <p>One or more child tests had errors
    Exception doesn't have a stacktrace</p>
</blockquote>

<p>The code below is what I am working with but cannot seem to get this to work;</p>

<pre><code>[TestFixture]
class PaymentServicetTest
{

    [Test]
    public void MakePayment()
    {
        var paymentRequestDetails = new MakePaymentRequest
        {
            Amount = 876.36m,
            CreditorAccountNumber = ""12345678"",
            DebtorAccountNumber = ""87654321"",
            PaymentDate = DateTime.Now,
            PaymentScheme = PaymentScheme.Chaps

        };
        var paymentService = new PaymentService();
        var result = paymentService.MakePayment(paymentRequestDetails);
        Assert.True(result.Success);
    }

}
</code></pre>

<p>I would be grateful if someone can point me in the direction of what I am doing wrong and how to fix it </p>

<p>Thanks</p>

<p>Simon</p>
",https://stackoverflow.com/questions/44613107/one-or-more-child-tests-had-errors-exception-doesnt-have-a-stacktrace,"['c#', 'unit-testing', 'nunit']",5145,FALSE,1,2
Laravel Testing login Credential using phpunit + multiprocess,"<p>I'm pretty new on unit testing and I want to try to test my login page 
my Goal for this unit are :
-> if it match in database -> redirect to route '/'
-> if not -> redirect to route '/login'</p>

<pre><code>&lt;?php

namespace Tests\Feature;

use App\Domain\Core\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class userTest extends TestCase
{
    use DatabaseMigrations;
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testLoginTrue()
    {
        $credential = [
            'email' =&gt; 'user@ad.com',
            'password' =&gt; 'user'
        ];
         $this-&gt;post('login',$credential)-&gt;assertRedirect('/');
    }

    public function testLoginFalse()
    {
        $credential = [
            'email' =&gt; 'user@ad.com',
            'password' =&gt; 'usera'
        ];
        $this-&gt;post('login',$credential)-&gt;assertRedirect('/login');
    }
}
</code></pre>

<p>when I test on TestLoginTrue , its successfully return to '/' But when i try the TestLoginFalse ... it return same like TestLoginTrue, it should be stayed on '/login' route,
Any Idea?</p>

<p>Plus I want to try to check if when I already login I couldn't access the login page so my initial idea is :
public function testLoginTrue()</p>

<pre><code>{
    $credential = [
        'email' =&gt; 'user@ad.com',
        'password' =&gt; 'user'
    ];
     $this-&gt;post('login',$credential)
         -&gt;assertRedirect('/')
         -&gt;get('/login')
         -&gt;assertRedirect('/');
}
</code></pre>

<p>but... it returns</p>

<blockquote>
  <p>1) Tests\Feature\userTest::testLoginTrue BadMethodCallException:
  Method [get] does not exist on Redirect.</p>
</blockquote>

<p>So how to do it correctly?</p>

<p>Thanks in advance </p>
",https://stackoverflow.com/questions/45052228/laravel-testing-login-credential-using-phpunit-multiprocess,"['phpunit', 'laravel-5.4']",6515,TRUE,6,1
Binding a callback function when using Async Waterfall,"<p>I was trying for a while to figure out a good solution for abstracting a function from an async waterfall (async library) function (to keep my code DRY), but I kept getting an error saying that <code>cb</code> was not defined. Also, when passing just <code>this</code> to <code>bind</code>, the function that <code>async</code> was defined in was the scope, and when passing <code>cb</code> as well.
Eventually, I found a solution which works (adding <code>cb</code> as a function to the <code>this</code> object), but it looks a bit messy and there is probably a better way of doing it. Any suggestions?:</p>

<pre><code>// registerController.js
const async = require('async');
const registerService = require('../services/register');

// Api endpoint code
...

// is there a better way than (this.cb = cb)
let callbackHandler = (err, res) =&gt; {
    if (err) this.cb(err);
    this.cb(null, res);
};

// asynchronously perform registration
async.waterfall([
    (cb) =&gt; {
        registerService.createAccount(username, email, callbackHandler.bind(this.cb = cb));
    },
    (res, cb) =&gt; {
        registerService.doSomethingElse(domain, callbackHandler.bind(this.cb = cb);
    },
....

// registerService.js
module.exports = {

    createAccount: (username, email, callback) =&gt; {
        httpService.request({
            host: myHost,
            method: 'POST',
            path: '/api/signup',
            body: {
                username,
                email
            }
        }).then((res) =&gt; {
            return callback(null, res);
        }).catch((err) =&gt; {
            return callback(err);
        });
    },
...
}
</code></pre>

<p>Note: code refactored into Services file for unit testing purposes and lean controllers (taking an MVC approach)</p>
",https://stackoverflow.com/questions/44290532/binding-a-callback-function-when-using-async-waterfall,"['javascript', 'asynchronous', 'callback']",320,FALSE,1,1
React-Redux-Form nested component testing,"<p>I am using React-Redux-Form and React-Bootstrap on client side of application.</p>

<p>I'm stuck on how to testing my components. I have made a small project on github with one of my components named LoginModal: 
<a href=""https://github.com/DmitryIvanovIAMM/react-redux-form-login-test/blob/master/src/__tests__/Foo-test.js"" rel=""nofollow noreferrer"">https://github.com/DmitryIvanovIAMM/react-redux-form-login-test/blob/master/src/<strong>tests</strong>/Foo-test.js</a>.</p>

<p>To start testing, I am following this tutorial <a href=""https://www.codementor.io/vijayst/unit-testing-react-components-jest-or-enzyme-du1087lh8"" rel=""nofollow noreferrer"">https://www.codementor.io/vijayst/unit-testing-react-components-jest-or-enzyme-du1087lh8</a>.
But when I try to .find() button in my rendered component, the result is an array of length zero. So I can't simulate its behaviour. I try find it (button) several different way but unsuccessful. Please, your suggestion.</p>
",https://stackoverflow.com/questions/44860011/react-redux-form-nested-component-testing,"['reactjs', 'jestjs', 'react-redux-form']",293,FALSE,1,1
How do I setup a private variable in a unit test,"<p>I have a difficulty unit testing my class which contain a list of object.</p>

<p>Here is what I have</p>

<pre><code>public class A 
{
    List&lt;B&gt; _list;

    public A() 
    {
        _list = new List&lt;B&gt;();
    }
    public void AddNewB(DateTime time)
    {
        _list.Add(new B(time));
    }
    public List&lt;B&gt; GetAllBs()
    {
        return _list;
    }
}
</code></pre>

<p>I want to have a test that prove that adding a new B doesn't clear my list. But since the list is private, I can't setup an existing list whitout going through the code I want to test. Since class A is responsible of creating all new B's and adding them to it's list and that all new A's should have an empty list of B's, adding a parameter in the constructor for the sake of testing feels weird.</p>

<p>Edit: I fixed GetAllBs since it was a copy-paste error of AddNewBs.</p>
",https://stackoverflow.com/questions/42583369/how-do-i-setup-a-private-variable-in-a-unit-test,"['c#', 'unit-testing', 'asp.net-core', 'nunit']",5502,TRUE,1,2
FluentValidation Testing Not Handling Expected Nulls,"<p>I'm using the great FluentValidation library and have run into an issue in Unit Testing a validator. I have following the example on this wiki page as closely as possible (but I'm using xUnit) <a href=""https://github.com/JeremySkinner/FluentValidation/wiki/g.-Testing"" rel=""nofollow noreferrer"">https://github.com/JeremySkinner/FluentValidation/wiki/g.-Testing</a></p>

<p>The test which uses the <strong>ShouldHaveValidationErrorFor</strong> extension method.</p>

<p>I am getting a <strong>NullReferenceException</strong> with the test failing. But that is exactly what I am testing for - a null ref for a required field.</p>

<p>Here's is my code:  </p>

<p><strong>Validator:</strong>  </p>

<pre><code>public class ChangeEmailRequestInputModelValidator : AbstractValidator&lt;ChangeEmailRequestInputModel&gt;
{
    public ChangeEmailRequestInputModelValidator()
    {
        RuleFor(x =&gt; x.NewEmail)
            .NotEmpty(); 

        RuleFor(m =&gt; m.NewEmail.Trim())
            .EmailAddress()
            .When(m =&gt; m.NewEmail != null)
            .WithMessage(ValidationConstants.SymbolIsNotAValidEmailAddress, x =&gt; x.NewEmail)
            .WithName(""NewEmail""); 

        RuleFor(m =&gt; m.NewEmailConfirm.Trim())
            .Cascade(CascadeMode.Continue)
            .NotEmpty().WithMessage(""Confirm New Email field cannot be empty."")
            .Equal(m =&gt; m.NewEmail.Trim()).WithMessage(""Confirm New Email field must be equal to the New Email."");
    }
}
</code></pre>

<p><strong>The Test:</strong>  </p>

<pre><code>public class ChangeEmailRequestInputModelValidatorTests
{
    [Fact]
    public void Errors_Where_NewEmail_Is_Null()
    {
        var val = new ChangeEmailRequestInputModelValidator();

        val.ShouldHaveValidationErrorFor(v =&gt; v.NewEmail, null as string);            
    }
}
</code></pre>

<p>Any idea why this is happening? I must have something wrong, but it looks so similar to the example that I am baffled.</p>
",https://stackoverflow.com/questions/46595736/fluentvalidation-testing-not-handling-expected-nulls,"['unit-testing', 'fluentvalidation']",945,TRUE,1,1
What does these few lines do as a small test framework in C++?,"<p>Hi I am reading through the implementation of <code>std::optional</code> <a href=""https://github.com/akrzemi1/Optional/blob/master/test_optional.cpp"" rel=""nofollow noreferrer"">here</a> and I found the following lines in its unit testing files.</p>

<pre><code>struct caller {
    template &lt;class T&gt; caller(T fun) { fun(); }
};
# define CAT2(X, Y) X ## Y
# define CAT(X, Y) CAT2(X, Y)
# define TEST(NAME) caller CAT(__VAR, __LINE__) = []
</code></pre>

<p>I don't really understand what do these lines do. <code>caller</code> seems to be a template to invoke functions, but how can it be used as <code>caller CAT ...</code>?
What does <code>X ## Y</code> mean here? Later in the file, the user define unit tests using <code>TEST</code>, but they do not appear in any executable code (I mean they are not called in <code>main</code> function at least), so I am not even sure if the compiled binary actually run the tests. Could you explain what is going on here? Thanks!  </p>

<p>Edit: pretty sure the tests are executed when I run the binary, but how is that achieved? </p>
",https://stackoverflow.com/questions/45290485/what-does-these-few-lines-do-as-a-small-test-framework-in-c,"['c++', 'c++11']",322,TRUE,6,1
running xunit tests included in a .NET Standard 1.6 library,"<p>I just created a netstandard library in Visual Studio 2017 and added references to <code>xunit</code> and <code>xunit.runner.visualstudio</code>, but the VS Test Explorer and Resharper 2017 EAP 3 are not recognizing any tests. I've seen:  <a href=""https://stackoverflow.com/questions/41350323/unit-testing-a-net-standard-1-6-library"">Unit testing a .NET Standard 1.6 library</a> but project.json is gone and csproj is back in place. </p>

<p>What do I have to do, to be able to run the unit tests included in a netstandard library?</p>

<p><strong>Library.csproj</strong></p>

<pre class=""lang-xml prettyprint-override""><code>&lt;Project Sdk=""Microsoft.NET.Sdk""&gt;
  &lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;netstandard1.6&lt;/TargetFramework&gt;
  &lt;/PropertyGroup&gt;
  &lt;ItemGroup&gt;
    &lt;PackageReference Include=""xunit"" Version=""2.2.0"" /&gt;
    &lt;PackageReference Include=""xunit.runner.visualstudio"" Version=""2.2.0"" /&gt;
  &lt;/ItemGroup&gt;
&lt;/Project&gt;
</code></pre>

<p><strong>Test.cs</strong></p>

<pre class=""lang-cs prettyprint-override""><code>namespace ClassLibrary2
{
    public class Class1
    {
        [Fact]
        public void RescharperShouldRunTest()
        {
            Assert.True(true);
        }
    }
}
</code></pre>

<p><a href=""https://i.stack.imgur.com/DGuBI.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/DGuBI.png"" alt=""enter image description here""></a></p>

<p><strong>Edit</strong></p>

<p>Thanks to the answers I made some progress.</p>

<p>Adding </p>

<pre><code>&lt;PackageReference Include=""Microsoft.NET.Test.Sdk"" Version=""15.0.0"" /&gt;  
&lt;!-- ... and ...  --&gt; 
&lt;ItemGroup&gt;
    &lt;Service Include=""{82a7f48d-3b50-4b1e-b82e-3ada8210c358}"" /&gt;
&lt;/ItemGroup&gt;
</code></pre>

<p>did have no impact. Only if I change the <code>TargetFramework</code> to <code>netcoreapp1.1</code> VS discovered the test and could run them. With <code>netstandard1.6</code> the Test Explorer remains empty. But I don't want a netcore app. I want a .NET standard library.</p>
",https://stackoverflow.com/questions/42684047/running-xunit-tests-included-in-a-net-standard-1-6-library,"['c#', 'visual-studio-2017', 'resharper', 'xunit', '.net-standard']",2255,TRUE,6,4
Jest testing React component using Electron-Remote in ElectronJS,"<p>I'm currently developing an ElectronJS application using React for the UI. In some React components I'm using nodeJS packages via Electron remote, so I import packages from the main process into the renderer process. Looks like this:</p>

<p>main.js</p>

<pre><code>global.moment = moment;
</code></pre>

<p>Component.js</p>

<pre><code>const remote = window.require('electron').remote;
const moment = remote.getGlobal('moment');
</code></pre>

<p>Everything is working fine until I've started to implement unit testing with Jest.</p>

<p>I've created the first following test case:</p>

<pre><code>it('renders without crashing', () =&gt; {
    const div = document.createElement('div');
    ReactDOM.render(&lt;App /&gt;, div);
});
</code></pre>

<p>Running this test gives me the following output:</p>

<pre><code>TypeError: window.require is not a function
</code></pre>

<p>I have no idea how to solve this problem, maybe someone has an idea how to fix this. Maybe somebody have an idea how to setup unit tests for React in Electron which allows to use nodeJS packages in the React component.</p>

<p>I'm thankful for any help.</p>
",https://stackoverflow.com/questions/47571610/jest-testing-react-component-using-electron-remote-in-electronjs,"['node.js', 'reactjs', 'unit-testing', 'electron', 'jestjs']",802,FALSE,6,1
how can i get c++ code overage from google test suite in terminal?,"<p>I have started using the <strong>Google Test</strong> unit testing tools which I am building into a CI pipeline. Is there a code coverage tool that runs in the shell and would allow me to set thresholds and add as a job into the pipeline?</p>

<p>For reference I come from a NodeJS background and use a pipeline as follows:</p>

<ol>
<li>linter (eslint)</li>
<li>unit tests (jasmine)</li>
<li>code coverage (istanbul coverage &amp;&amp; istanbul check-coverage)</li>
</ol>

<p>The bit i'm struggling with is the third step. In NodeJS I can set the acceptable thresholds and the job fails if these are not met.</p>

<p>I was hoping to replicate this for my C++ code. Is this even possible?</p>
",https://stackoverflow.com/questions/47902627/how-can-i-get-c-code-overage-from-google-test-suite-in-terminal,"['c++', 'unit-testing', 'continuous-integration', 'code-coverage']",362,TRUE,1,1
Getting the resource path during testing,"<p>I am trying to write a unit tests that uses a file in my project. In my application, I use <code>FileManager.default.currentDirectoryPath</code> to get the path to my file. However, the test path is different when I use the same in tesing. After reading up the documentation I understood that XCode uses a different path for unit testing.</p>

<p>I was wondering how I can get the correct Bundle path for <code>File.txt</code> in my tests </p>

<p>I have tried this but it returns null</p>

<pre><code>let testBundle = Bundle(for: type(of: self))
let fileURL = testBundle.url(forResource: ""File"", withExtension: ""txt"")
</code></pre>

<p>The following is my directory structure. ShopTests is my unit test file and File.txt is the file for which I am trying to retrieve the path url for(both highlighted in picture)
<a href=""https://i.stack.imgur.com/prQTw.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/prQTw.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/47480472/getting-the-resource-path-during-testing,"['swift', 'swift4']",774,TRUE,1,1
Unit Test Custom MVC AuthorizationAttribute,"<p>This question is pretty much a duplicate of <a href=""https://stackoverflow.com/questions/18701433/asp-net-mvc-unit-testing-custom-authorizeattribute"">ASP.NET MVC unit testing custom AuthorizeAttribute</a> - however I cannot get my code to run without hitting the same <code>NullReferenceException</code></p>

<p>Something is clearly missing when I mock up my controller.</p>

<p>My attribute is simple - looks like this:</p>

<pre><code>public override void OnAuthorization(AuthorizationContext filterContext)
{
    if (!base.AuthorizeCore(filterContext.HttpContext))
    {
        filterContext.Controller.TempData.Add(""RedirectReason"", ""Unauthorized"");
    }
    base.OnAuthorization(filterContext);
}
</code></pre>

<p>My most recent attempt is below. I also tried the code from the question on that referenced link, including adding items to the context.</p>

<pre><code> // Arrange
        Mock&lt;IPrincipal&gt; userMock = new Mock&lt;IPrincipal&gt;();
        Mock&lt;HttpResponseBase&gt; responseMock = new Mock&lt;HttpResponseBase&gt;();
        responseMock.SetupGet(res =&gt; res.Cache).Returns(new Mock&lt;HttpCachePolicyBase&gt;().Object);

        Mock&lt;HttpContextBase&gt; contextMock = new Mock&lt;HttpContextBase&gt;(MockBehavior.Strict);
        contextMock.SetupGet(cm =&gt; cm.User).Returns(userMock.Object);
        contextMock.SetupGet(cm =&gt; cm.Response).Returns(responseMock.Object);
        contextMock.SetupGet(cm =&gt; cm.Items).Returns(new Mock&lt;IDictionary&gt;().Object);

        Mock&lt;ControllerContext&gt; controllerContextMock = new Mock&lt;ControllerContext&gt;();
        controllerContextMock.SetupGet(ctx =&gt; ctx.HttpContext).Returns(contextMock.Object);

        Mock&lt;ActionDescriptor&gt; actionDesMock = new Mock&lt;ActionDescriptor&gt;();
        actionDesMock.Setup(action =&gt; action.GetCustomAttributes(typeof(AllowAnonymousAttribute), true)).Returns(new object[0]);

        // Act
        CustomAuthorizationAttribute cusAtr = new CustomAuthorizationAttribute() { Roles = ""TestRole"" };

        // Assert
        cusAtr.OnAuthorization(new AuthorizationContext(controllerContextMock.Object, actionDesMock.Object));
</code></pre>

<p>I've also checked out the source code for <a href=""https://github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/System.Web.Mvc/AuthorizeAttribute.cs"" rel=""nofollow noreferrer"">AuthorizeCore</a>.</p>

<p>When ran, the test fails on <code>base.AuthorizeCore(filterContext.HttpContext)</code> with a <code>NullReferenceException</code></p>

<p>Can't figure what's missing.</p>

<p>any idea?</p>

<hr>

<p>For the sake of ease, code from the other question, adjusted to suit our models is:</p>

<pre><code>    // Arrange
    var httpContext = new Mock&lt;HttpContextBase&gt;();
    Dictionary&lt;object, object&gt; dictionary = new Dictionary&lt;object, object&gt;();
    httpContext.SetupGet(cm =&gt; cm.Items).Returns(dictionary);
    Mock&lt;IPrincipal&gt; userMock = new Mock&lt;IPrincipal&gt;();
    httpContext.SetupGet(c =&gt; c.User).Returns(() =&gt; userMock.Object); 
    var requestBase = new Mock&lt;HttpRequestBase&gt;();
    var headers = new NameValueCollection
    {
       {""Special-Header-Name"", ""false""}
    };
    requestBase.Setup(x =&gt; x.Headers).Returns(headers);
    requestBase.Setup(x =&gt; x.HttpMethod).Returns(""GET"");
    requestBase.Setup(x =&gt; x.Url).Returns(new Uri(""http://localhost/""));
    requestBase.Setup(x =&gt; x.RawUrl).Returns(""~/Maintenance/UnExistingMaster"");
    requestBase.Setup(x =&gt; x.AppRelativeCurrentExecutionFilePath).Returns(() =&gt; ""~/Maintenance/UnExistingMaster"");
    requestBase.Setup(x =&gt; x.IsAuthenticated).Returns(() =&gt; true);
    httpContext.Setup(x =&gt; x.Request).Returns(requestBase.Object);
    var controller = new Mock&lt;ControllerBase&gt;();
    var actionDescriptor = new Mock&lt;ActionDescriptor&gt;();
    var controllerContext = new ControllerContext(httpContext.Object, new RouteData(), controller.Object);

    CustomAuthorizationAttribute cusAtr = new CustomAuthorizationAttribute() { Roles = ""TestRole"" };

    // Act
    cusAtr.OnAuthorization(new AuthorizationContext(controllerContext, actionDescriptor.Object));
</code></pre>
",https://stackoverflow.com/questions/44415208/unit-test-custom-mvc-authorizationattribute,"['c#', 'asp.net-mvc', 'unit-testing']",1015,TRUE,1,1
Is this possible to write good tests avoiding mocking and &quot;expects&quot; on internal methods?,"<p>Is this possible to avoid mocking in phpunit?</p>

<p>My concept is to:
- write unit tests to test smaller parts
- when it comes to do a integration/functional test then it's possible to inject a null object class using the dependency injection (so it's good to have everything interfaced). But integration tests could be separated from unit tests.</p>

<p>The reason why I don't like the mocking is that I see that its underused in every test, it's totally not readable. I was thinking about separation on unit testing and integration testing.</p>

<p>Could this in most cases be alternative to mocking, or is the mocking not replaceable at all? What's the best practice?</p>
",https://stackoverflow.com/questions/42434833/is-this-possible-to-write-good-tests-avoiding-mocking-and-expects-on-internal,"['php', 'unit-testing', 'phpunit']",79,TRUE,1,1
How to mock a python library using patch in python regardless where it is used?,"<p>In the following question the function that uses the ftplib is defined in the same file, which makes it trivial to patch ('ftplib.FTP')</p>

<p><a href=""https://stackoverflow.com/questions/29817963/mocking-ftplib-ftp-for-unit-testing-python-code"">Mocking ftplib.FTP for unit testing Python code</a></p>

<p>My question is: How should I proceed if, in my test, I would like to make an instance of a class (let's call it 'A') that uses the ftplib somewhere (ie: the class A has an instance of a class B and B has an FTP object which calls connect()) ?</p>

<pre><code>import unittest
from mock import patch

class TestClass(unittest.TestCase):

  @patch(???)
  def test_1(self, mock_ftp_constructor):
      mock_ftp = mock_ftp_constructor.return_value
      a = A()
      self.assertTrue(mock_ftp.connect.called)


if __name__ == ""__main__"":
  unittest.main()
</code></pre>

<p>If I use the solution given in the other question, I find that the ftplib is called instead of the mock. How could I know the correct path of ftplib.FTP ?</p>
",https://stackoverflow.com/questions/44003217/how-to-mock-a-python-library-using-patch-in-python-regardless-where-it-is-used,"['python', 'unit-testing', 'ftp', 'mocking', 'magicmock']",341,TRUE,1,1
how to unit test a delete method using JustMock lite,"<p>I am just getting started with unit testing and now stuck writing a test method for delete. I am using JustMock. Below I have mentioned my controller action method and test method but the test method is not working. The return value of the method is not retaining it's always returning false. Please guide me on what I'm doing wrong here.</p>

<p>This is the test method.</p>

<pre><code>   [TestMethod]
    public void Delete_User()
    {
        Mapper.CreateMap&lt;UserViewModel,User&gt;();

        IStaticMembershipService membershipRepository = Mock.Create&lt;IStaticMembershipService&gt;();

        var mockUserViewModel = new UserViewModel { Id = 1};

        var mockUser = Mapper.Map&lt;UserViewModel, User&gt;(mockUserViewModel);
        var UserRepository = Mock.Create&lt;IUserRepository&gt;();

        Mock.Arrange(() =&gt; UserRepository.DeleteUser(mockUser)).Returns(new OperationStatus { Status = true }).MustBeCalled();

        UserController controller = new UserController(UserRepository, membershipRepository);
        ActionResult result = controller.Delete(mockUserViewModel);

        Mock.Assert(() =&gt; UserRepository.DeleteUser(mockUser), Occurs.AtLeastOnce());
    }
</code></pre>

<p>Any relevant controller info.</p>

<pre><code>    private IUserRepository _UserRepository;
    private IStaticMembershipService _membershipService;

    public UserController(IUserRepository UserRepo, IStaticMembershipService membershipService)
    {
        _UserRepository = UserRepo;
        _membershipService = membershipService;
    }
</code></pre>

<p>The repository is mocked correctly but the ""opStatus"" property getting returned is always false not the value I have specified to be the result in testmethod.</p>

<pre><code>    public ActionResult Delete(UserViewModel usr)
    {
        var selectedUser = Mapper.Map&lt;UserViewModel, User&gt;(usr);

        var opStatus = _UserRepository.DeleteUser(selectedUser);
        if (!opStatus.Status)
            throw new System.Web.Http.HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));

        return RedirectToAction(""Index"");
    }
</code></pre>

<p>I hope i have provided enough information. Any help much appreciated.</p>
",https://stackoverflow.com/questions/44367898/how-to-unit-test-a-delete-method-using-justmock-lite,"['c#', 'asp.net-mvc', 'unit-testing']",97,TRUE,1,1
Python: How to handle unicode in env variable in windows,"<p>I want to pass my custom environment variables for the location of my existing application log file directory location in in newly spawn process, Now the problem is that user directory path may contain unicode, depends on user's locale (It can be latin-1)    </p>

<pre><code># This Works fine if all the characters are ascii
self.app_log_dir = u'C:\\USERS_CUSTOM_PATCH\\logs\\'

env['APP_LOG_DIR'] = self.app_log_dir 

    p = Popen(
                    cmd, close_fds=False, env=env, stdout=stdout.fileno(),
                    stderr=stderr.fileno(), stdin=stdin.fileno(),
                    creationflags=(CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS)
                )

p.start()

##############################

# But path like this fails
self.app_log_dir = u'C:\\USERS_CUSTOM_PATCH\\xx_ÔÔ_xx\\logs\\'
...
...
p.start()
</code></pre>

<p>Below is the Exception I received from above non-ascii path with popen,</p>

<p><strong>Exception: environment can only contain strings</strong></p>

<p>Can anyone suggest work around as I need to handle non-ascii paths in my application?</p>

<p><strong>Updated:</strong></p>

<p>pp_log_dir variable is configurable by user, I am unit testing my code and found the issue as user can provide any path in config.py file</p>
",https://stackoverflow.com/questions/41761755/python-how-to-handle-unicode-in-env-variable-in-windows,"['python', 'python-2.7', 'python-3.x', 'subprocess']",1063,TRUE,1,1
Using Mockito to verify is method actually passed successfully and supporting exceptions,"<p>I have the next method that parses a JSON response.</p>

<pre><code>public void parseJSON(JSONObject itemObj) {

  try {
        setId(itemObj.getString(""Id""));
        setName(itemObj.getString(""Name""));
        JSONObject extraObj = itemObj.getJSONObject(""Items"");
        ExtraData extra = new ExtraData ();
        extra.parseResponse(extraObj);
    } catch (JSONException e) {
}
</code></pre>

<p>Now,I want to add some unit testing to it,I don’t know what more you can test here expect the parsing issue, so I prepped a test with the relevant fields and I want to make sure it parsing the relevant fields, and in case it fails to know about it. My problem is that because it’s a mockup , every  <code>itemObj.getString(“whatever”)</code> returns <code>Null</code> and doesn’t throw exception , so whatever I pass it always succeed.</p>

<p>How can I know that based on the data that I passed it succeeded /failed (throw exception) and not always getting success?</p>

<pre><code>@Test
public void parseJSON() throws Exception {
    myClass = Mockito.spy(MyClass.class)
    JSONObject jsonObject = Mockito.mock(org.json.JSONObject.class);
    when(jsonObject.getString(eq(""Id""))).thenReturn(""555555"");
    when(jsonObject.getString(eq(""Name""))).thenReturn(""John"");
    // if removing the “Name” and leaving only “NameIncorrect” it suppose to fails
    //when(jsonObject.getString(eq(""NameIncorrect""))).thenReturn(""John"");

    when(jsonObject.getJSONObject(eq(""Items""))).thenReturn(Mockito.mock(JSONObject.class));

    myClass.parseJSON(jsonObject);
}
</code></pre>
",https://stackoverflow.com/questions/44232440/using-mockito-to-verify-is-method-actually-passed-successfully-and-supporting-ex,"['java', 'unit-testing', 'mockito']",572,FALSE,1,2
"How can I compare object properties, but not the values, in karma/jasmine?","<p>
I'm new to Unit Testing with karma/jasmine, and I am trying to test two objects of the same type, but with different values. Which means, same properties but with different values on each object, like this:
</p>

<pre><code>let myFirstObject: myType = {
    id: 1,
    name: ""name1"",
    //... some other properties, 
}

let mySecondObject: myType = {
    id: 2,
    name: ""name2"",
    //... some other properties, 
}

it('should be a true comparison', () =&gt; {
    expect(myFirstObject).toEqual(mySecondObject);
});
</code></pre>

<p>
    I want it to be true, because the type and the properties are equal (the structure is the same), although the values stored are different. But using jasmine .toEqual() only passes when both items are entirely equal (properties and values).

How can I do this comparison of structure/type but not considering the values, in karma/jasmine?</p>

<p>(note: my project is in ionic/angularIO, if that matters)</p>

<p>Any ideas?</p>
",https://stackoverflow.com/questions/47699007/how-can-i-compare-object-properties-but-not-the-values-in-karma-jasmine,"['angular', 'testing', 'ionic-framework', 'jasmine', 'karma-runner']",1149,TRUE,1,1
how can I mock a service to throw an exception a method that returns a List?,"<p>I am facing this little issue. I have a service this way</p>

<pre><code>public class Myservice {

   MyRestService myRestService; 

    public List&lt;String&gt; getNames() throws RestClientException {
        return myRestService.getNames();
    }

....
</code></pre>

<p>and a controller that is like this:</p>

<pre><code>@RequestMapping(value = URL, method = GET)
    public ModelAndView display(final ModelMap model) {
        ....
        try{
            List&lt;String&gt; listOfNames = myService.getNames();
        }catch(RestClientException e){
            LOG.error(""Error when invoking Names service"", e);
        }
        model.addAttribute(""names"", listOfNames);
        return new ModelAndView(VIEW, model);
    }....
</code></pre>

<p>So far works so good, the unit testing for the case the service actually
 returns a list of Strings works fine.</p>

<p>But since the service calls another one that is basically a rest client that could throw an exception, I want to mock that case.</p>

<p>If I have myService calling <code>myRestClientService</code> where <code>myRestClientService</code> throws an exception should I hadd to the method signature ""throws Exception"" ?</p>

<pre><code> final RestClientException myException =  mockery.mock(RestClientException.class);
        mockery.checking(new Expectations() {
            {
                oneOf(myService).getNames();
                will(returnValue(myException));
...
</code></pre>

<p>But I get an error that I cannot throw an exception from a method that only return List is there anyway to fix this? How could I test it? </p>
",https://stackoverflow.com/questions/43085322/how-can-i-mock-a-service-to-throw-an-exception-a-method-that-returns-a-list,"['java', 'unit-testing', 'junit', 'jmock']",2349,TRUE,1,2
How to set the dependency of dynamically generated .js library through require in jasmine specs,"<p>Currently I am writing jasmine specs for already developed backbone.js application. I have to write jasmine specs for each module for unit testing. I have a module in which one of the .js (say abc.js) file is generated after grunt build task and we are setting dependency using require.js. Now in the same way in my spec file also I am setting require('abc') but it says 404 not found error as this abc.js file is exists only in generated build. Can I get any suggestions how to create dependency of abc.js file for my specs. FYI, my application uses karma, jasmine, require, backbone.  </p>
",https://stackoverflow.com/questions/44103530/how-to-set-the-dependency-of-dynamically-generated-js-library-through-require-i,"['javascript', 'backbone.js', 'jasmine', 'requirejs', 'karma-jasmine']",47,FALSE,0,0
Python mock a dependancy object,"<p>I have a python class (MyClass) I am unit testing. It has a external dependency which creates a database, I would like to mock that object and check it was called.</p>

<pre><code>from entities_database import DBCreator

class MyClass():

    def __init__(self):
        self.db = DBCreator()

    def create(self, name):
        value = self.db.create_db(name)
</code></pre>

<p>I would like to test the init function, so see that a mock DBCreator called. And then to test the create function to check that create_db() was called with ""name"", and it returned ""name"" to value.</p>

<p>I am not sure how to go about this, so far I have this:</p>

<pre><code>from entities_database import DBCreator
from test_unit import MyClass
import unittest
import mock


class MyClassTest(unittest.TestCase):

    @mock.patch('entities_database.DBCreator', autospec=True)
    def test_myclass_init(self, dbcreator_mock):
        creator = mock.create_autospec(DBCreator)
        dbcreator_mock.return_value = creator

        myclass = MyClass()
        assert(dbcreator_mock.called)
</code></pre>

<p>Which results in:</p>

<pre><code>F
======================================================================
FAIL: test_myclass_init (unit_test.MyClassTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File ""/Users/paul/Data/TSC/Code/parltrack_eu/venv/lib/python3.6/site-packages/mock/mock.py"", line 1305, in patched
    return func(*args, **keywargs)
  File ""/Users/paul/Data/TSC/Code/parltrack_eu/unit_test.py"", line 32, in test_myclass_init
    assert(dbcreator_mock.called)
AssertionError

----------------------------------------------------------------------
Ran 1 test in 0.036s

FAILED (failures=1)
</code></pre>

<p>How can I fix my code?</p>

<p>---- UPDATE ----
Apart from the solution below with dependency injection, one can also do the following with patch, as suggested below @Goyo</p>

<pre><code>from entities_database import DBCreator
from test_unit import MyClass
import unittest
import mock


class MyClassTest(unittest.TestCase):

    @mock.patch('test_unit.DBCreator', autospec=True)
    def test_myclass_init(self, mock_db):
        '''
        Test the initialization of MyClass
        Test that DBCreator is initialized
        '''
        creator = mock.create_autospec(DBCreator)
        mock_db.return_value = creator

        # Assert that the DBCreator is initialised
        myclass = MyClass()
        assert(mock_db.called)

    @mock.patch('test_unit.DBCreator', autospec=True)
    def test_myclass_create(self, mock_db):
        '''
        Test the myclass.create() function
        and assert it calls db.create_db() with the correct
        argument
        '''
        name = 'unittest'
        myclass = MyClass()
        myclass.create(name)
        # Assert that create_db was called with name
        myclass.db.create_db.assert_called_with(name)
</code></pre>
",https://stackoverflow.com/questions/45211181/python-mock-a-dependancy-object,"['python', 'unit-testing', 'mocking']",779,TRUE,0,2
WebCam - Browser does not support getUserMedia in IE Edge,"<p>I am developing an Angular application that needs photo capturing functionality. For that purpose, I am using WebCam directive by referring following links.</p>

<p><a href=""https://github.com/jonashartmann/webcam-directive"" rel=""nofollow noreferrer"">https://github.com/jonashartmann/webcam-directive</a> </p>

<p><a href=""https://jonas.hartmann.site/webcam-directive/#/"" rel=""nofollow noreferrer"">https://jonas.hartmann.site/webcam-directive/#/</a></p>

<p>After developing whole page, I am now stuck unit testing on Edge due to 'Browser does not support getUserMedia' error. After googling for solution, I came across links that says, Edge doesn't have support for getUserMedia. </p>

<p><a href=""https://stackoverflow.com/questions/21015847/how-to-make-getusermedia-work-on-all-browsers"">how to make getUserMedia() work on all browsers</a></p>

<p><a href=""http://blog.teamtreehouse.com/accessing-the-device-camera-with-getusermedia"" rel=""nofollow noreferrer"">http://blog.teamtreehouse.com/accessing-the-device-camera-with-getusermedia</a></p>

<p>I think, there will be alternate solution for this scenario but I can't figure it out. </p>

<p>NOTE: webcam.min.js file already used </p>

<pre><code>navigator.getMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia 
</code></pre>

<p>Thanks in advance. </p>
",https://stackoverflow.com/questions/46406449/webcam-browser-does-not-support-getusermedia-in-ie-edge,"['javascript', 'angularjs', 'webcam', 'getusermedia', 'webcam.js']",848,FALSE,0,0
PhpStorm can not parse PHPUnit version output. Very strange error,"<p>I'm trying to set up PHPUnit in PhpStorm 2017.1 on Windows 10 using a Vagrant box for a Laravel project. I've set up a remote interpreter, and I've been using it for a couple of months now, everything working fine. </p>

<p>I've been asked to do some unit testing so I've set up PhpStorm with PHPUnit, following my coworkers' instructions (PhpStorm on Mac) but when I select <code>autoload.php</code> in my vendor folder I receive the error message </p>

<blockquote>
  <p>""Can not parse PHPUnit version output: Could not open input file: <code>/vagrant/vendorphpunitphpunitphpunit</code>"" (no slashes).</p>
</blockquote>

<p>If I run PHPUnit via <code>vagrant ssh</code> in the command line, my tests execute fine, and I can manually select the PHPUnit phar in PhpStorm, but then I'm missing the autoloaded classes, so everything fails.</p>

<p><a href=""https://i.stack.imgur.com/sRIK5.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/sRIK5.png"" alt=""Screenshot of PhpStorm&#39;s PHPUnit config""></a></p>
",https://stackoverflow.com/questions/43188606/phpstorm-can-not-parse-phpunit-version-output-very-strange-error,"['php', 'windows', 'vagrant', 'phpunit', 'phpstorm']",6329,TRUE,10,3
How to Python Unit Test,"<p>I'm tying to get into unit testing for python and I'm having trouble with finding a way to tackel the following problem (<a href=""https://jeffknupp.com/blog/2013/12/09/improve-your-python-understanding-unit-testing/"" rel=""nofollow noreferrer"">source</a>).</p>

<blockquote>
  <p>We have two functions, is_prime and print_next_prime. If we wanted to
  testprint_next_prime, we would need to be sure that is_prime is
  correct, asprint_next_prime makes use of it. In this case, the
  function print_next_prime is one unit, and is_prime is another.
  Since unit tests test only a single unit at a time, we would need to
  think carefully about how we could accurately test print_next_prime.</p>
</blockquote>

<pre><code>def is_prime(number):
    """"""Return True if *number* is prime.""""""
    for element in range(number):
        if number % element == 0:
            return False

    return True

def print_next_prime(number):
    """"""Print the closest prime number larger than *number*.""""""
    index = number
    while True:
        index += 1
        if is_prime(index):
            print(index) 
</code></pre>

<p>How would you write a unit test for both of these methods? Unfortunately the source never gives an answer to this question.</p>
",https://stackoverflow.com/questions/42957224/how-to-python-unit-test,"['python', 'unit-testing']",1324,TRUE,0,1
"Android Retrofit 2.0 use image, video and audio uploading with MultipartBody.Par method","<p>I am creating an android library and doing the Unit testing using instrument test.And I use Android Studio 3.0.</p>

<p>This is my code ( controller class )</p>

<pre><code>File file = new File(""/storage/emulated/0/DCIM/Facebook/FB_IMG_1496146656900.jpg"");

RequestBody reqFile = RequestBody.create(MediaType.parse(""image/jpeg""), file);
MultipartBody.Part body = MultipartBody.Part.createFormData(""file"", file.getName(), reqFile);
RequestBody name = RequestBody.create(MediaType.parse(""text/plain""), noteId);
String notebookId = getNotebookId(projectId);
if (isSessionAvailable(notebookId)) {
    String session = getNotebookSession(notebookId);
    Call&lt;ResponseBody&gt; call = mApiNotes.requestNotesAttachments(session, name, body);
    call.enqueue(new NoteAttachmentCallBacks.AddNoteAttachmentCallback(assetUploadCallbacks));
}
</code></pre>

<p>And the retrofit interface is</p>

<pre><code>@Multipart
@POST(""/NotebookAsset"")
Call&lt;ResponseBody&gt; requestNotesAttachments(@Header(""Cookie"") String notebookSession, @Part(""note_id"") RequestBody noteId, @Part MultipartBody.Part image);
</code></pre>

<p>But when I run the code this is not working. After call to the retrofit interface class the test just browsing and not even end.It continuously run the test but never ending.seems the asset is not uploading. </p>

<p>Roughly I thought,<br>
there is a problem with authority to access resources in the device. so I added permissions to manifest file.</p>

<pre><code>&lt;uses-permission android:name=""android.permission.READ_EXTERNAL_STORAGE"" /&gt;
&lt;uses-permission android:name=""android.permission.WRITE_EXTERNAL_STORAGE""/&gt;
</code></pre>

<p>But it is not the solution.The result is same.</p>

<p>Can you please look this problem?. I have completely blocked with this issue.</p>
",https://stackoverflow.com/questions/46129122/android-retrofit-2-0-use-image-video-and-audio-uploading-with-multipartbody-par,"['android', 'unit-testing', 'file-upload', 'retrofit2']",637,TRUE,0,1
How to use enzyme for react-native with jest,"<p>I have followed –or tried to– several posts on how to do it, including the airbnb enzyme's guide for (separatedly) <code>react-native</code> and <code>jest</code>. (E.g: <a href=""https://medium.com/@childsmaidment/testing-react-native-components-with-enzyme-d46bf735540#.6sxq10kgt"" rel=""nofollow noreferrer"">https://medium.com/@childsmaidment/testing-react-native-components-with-enzyme-d46bf735540#.6sxq10kgt</a>, <a href=""https://blog.callstack.io/unit-testing-react-native-with-the-new-jest-i-snapshots-come-into-play-68ba19b1b9fe#.4iqylmqh5"" rel=""nofollow noreferrer"">https://blog.callstack.io/unit-testing-react-native-with-the-new-jest-i-snapshots-come-into-play-68ba19b1b9fe#.4iqylmqh5</a> or <a href=""https://stackoverflow.com/questions/29730415/how-to-use-jest-with-react-native"">How to use Jest with React Native</a>)</p>

<p>But I keep getting lots of warnings (I have multiple set of concurrent tests) whenever I try to render (not mount, it crashes) any native component. Warnings are always about a native prop not being recognised.</p>

<pre><code>Warning: Unknown props `focus`, `secureTextEntry` on &lt;TextInput&gt; tag. Remove these props from the element.
          in TextInput (created by TextInput)
          in TextInput (created by PasswordInput)
</code></pre>

<p>Anyone who has a set up working, recognises how to remove the warning or how to solve it?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/42039383/how-to-use-enzyme-for-react-native-with-jest,"['react-native', 'jestjs', 'enzyme']",4580,TRUE,5,3
Need to write unit test for compound functions and DB functions?,"<p>I need to clear my thoughts about unit testing.</p>

<p>Q1.) Ex: Function A ;  Function B { do some other stuff; Function A;}</p>

<p>As per definition unit test should write for smallest (independent unit) of the application. In this case should i write unit test for Only for A  , or need to write for both A and B ?</p>

<p>Q2.) 2/3 part of the functions in my application deal (get/update/insert) with local database (sqlite) </p>

<p>(<a href=""https://stackoverflow.com/questions/1257560/when-is-a-test-not-a-unit-test"">When is a Test not a Unit-test?</a>) is mentioned that unit test should not touch database. So how do i make sure the my database queries work well or not? </p>
",https://stackoverflow.com/questions/42104215/need-to-write-unit-test-for-compound-functions-and-db-functions,"['c#', 'unit-testing']",51,TRUE,0,1
Using Google Test Adapter for Visual Studio with CMake,"<p>A have a CMake-based project which uses Google Test for unit testing and I am using the Visual Studio generator to create my project/solution files.</p>

<p>I would like to be able to run my Google Test unit tests from the Visual Studio Test Explorer so that I can keep everything within the IDE. I heard about <a href=""https://github.com/csoltenborn/GoogleTestAdapter"" rel=""nofollow noreferrer"">Google Test Adapter</a> but obviously right out of the box it does not ""know"" where my tests are or how to run them.</p>

<p>How can I set this up to properly discover my tests? Can I just throw them in a directory and have GTA look for them that way?</p>
",https://stackoverflow.com/questions/45883064/using-google-test-adapter-for-visual-studio-with-cmake,"['visual-studio', 'cmake', 'googletest']",1397,TRUE,0,2
Refactoring a project generated from Petapoco,"<p>I'm creating a C# Win Forms app using PetaPoco as micro ORM. I want to refactor the generated classes to make them easily testable and mockable.
When I started to write the Unit Test I get stuck with Mock because I do not use interfaces, but I dont know how to integrate the interfaces with the current classes.</p>

<p>This are the classes</p>

<pre><code>public partial class League : FutbolDB.Record&lt;League&gt;
{
    public int? id { get; set; }
    public string Name { get; set; }
    public int? CantTeams { get; set; }
}

public partial class Team : FutbolDB.Record&lt;Team&gt;
{
    public int? id { get; set; }
    public string Name { get; set; }
    private int? LeagueId { get; set; }
}
</code></pre>

<p>Then I extend this classes</p>

<pre><code>public partial class Team : FutbolDB.Record&lt;Team&gt;
{
    private League _league; 

    public Team() {}

    public Team(string name, League league)
    {
        if (string.IsNullOrEmpty(name))
            throw new ArgumentException(""The name cannot be empty or null"");
        if (league == null)
            throw new ArgumentException(""The League cannot be null"");
        Name = name;
        League = league;
    }

    [Ignore]
    public League League
    {
        get { return _league ?? League.GetById(LeagueId); }
        set {
            _league = value;
            LeagueId = _league?.id;
        }
    }
</code></pre>

<p>Now when I Unit Test</p>

<pre><code>    //this runs fine
    [TestMethod()] 
    public void EqualsTest()
    {
        Mock&lt;League&gt; mockLeague = new Mock&lt;League&gt;();

        var t1 = new Team(""team"",mockLeague.Object);
        var t2 = new Team(""Team"", mockLeague.Object);

        t1.id = 1;
        t2.id = 1;

        Assert.IsTrue(t1.Equals(t1));
        Assert.IsFalse(t1.Equals(null));
        Assert.IsTrue(t1.Equals(t2));
    }
</code></pre>

<p>The problem is when I try to Stub the method CantTeams from League, that without interfaces Mock throws and error.</p>

<pre><code>    public TeamTests()
    {
        List&lt;Team&gt; teams = new List&lt;Team&gt;();
        teams.Add(new Team(""barca"", mockLeague.Object));
        teams.Add(new Team(""atletico"", mockLeague.Object));
        teams.Add(new Team(""madrid"", mockLeague.Object));

        // Error stubbing this method from a concrete class
        mockLeague.Setup(x =&gt; x.CantTeams).Returns(teams.Count);
    }
</code></pre>

<p>Unit testing, Mock and Patterns are new to me and I'm currently trying to learn them. Thanks in advance</p>
",https://stackoverflow.com/questions/44464158/refactoring-a-project-generated-from-petapoco,"['c#', 'unit-testing', 'mocking', 'refactoring', 'petapoco']",66,FALSE,0,0
Powermock without JUnit,"<p>to extract some data from a legacy application, I currently use powermock to prepare a few quite-mangled-up classes and replace a few dependencies with mocks.</p>

<p>Thus, I have a JUnit test, which essentially does:</p>

<pre><code>@RunWith(PowerMockRunner.class)
@PrepareForTest(LegacyDependency.class)
public class ThisIsNotReallyATest {
    @Test
    public void extractData() {
        ... prepare and wire mocks

        // new ClassUnderTest() will essentally call LegacyDependency.getInstance()
        Object result = new ClassUnderTest().doSomething();
        // save result for later reference
    }
}
</code></pre>

<p>Thus: this is NOT A TEST. This is a utility class which uses Powermock features to get around various badly modeled dependencies.</p>

<p>As using a test framework to create a utility which is not connected to unit testing whatsoever makes me feel real bad, the question is:</p>

<p>Can I use powermock (esp. the the PrepareForTest feature for static/final/etc.) in a standalone piece of software? If so: how?</p>
",https://stackoverflow.com/questions/41757541/powermock-without-junit,"['java', 'powermockito']",409,TRUE,0,2
Why action does not executes function?,"<p>I'm unit testing my validators with xUnit and there is a case when action does not executes function.</p>

<p>The validator is able to throw exception and and also able to populate a list containing error messages. The <code>shouldThroException</code> parameter defines when the validator should and should not throw exception. When it is not expected then it should populate errorCollection.</p>

<p>This test fails, because when the code gets into the else action does not calls ValidateEmailAddress, at least as I go through the code with debugger I see this. And as a consequence the errorcollection is not populated and the test fails.</p>

<p>How can I make it sure action calls ValidateEmailAddress?</p>

<pre><code>[Theory]
[MemberData(""StringValidatorValidateEmailAddressShouldPopulateErrorCollection"")]
public void StringValidator_ValidateEmailAddress_ShouldPopulateErrorCollection(
    int order,
    string emailAddress,
    List&lt;string&gt; errorCollection,
    bool shouldThroException,
    int expectedAmountOfErrorsInErrorCollection)
{
    // Given

    // When
    Action action = () =&gt; this.stringValidator.ValidateEmailAddress(emailAddress, errorCollection);

    // Then
    if (shouldThroException)
    {
        action.ShouldThrowExactly&lt;InvalidEmailAddressDigitalLibraryValidationException();
    }
    else
    {
        action.ShouldNotThrow();
    }
    errorCollection.Count.Should().Be(expectedAmountOfErrorsInErrorCollection);
}

public static IEnumerable&lt;object[]&gt; StringValidatorValidateEmailAddressShouldPopulateErrorCollection
{
    get
    {
        return new List&lt;object[]&gt;
        {
           new object[] { 3, ""asd@c"", new List&lt;string&gt;(), false, 1 };
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/45298175/why-action-does-not-executes-function,"['c#', 'unit-testing', 'action', 'xunit']",70,TRUE,0,1
Testing a map contained in a mocked class,"<p>I am trying to test a <code>ExampleController</code> class which works kind of like a facade for my POJO <code>Example</code> class.   </p>

<p>I started to write a <code>InstrumentedTest</code> for the <code>ExampleController</code> because it works with Greenrobots EventBus, and got a <code>NullPointerException</code> when I tried to retrieve values which are stored in a <code>Map</code> in my <code>Example</code> class.<br>
I use <code>Mockito v2.7.19</code>, <code>Espresso 2.2.2</code> and  <code>JUnit 4.12</code>.</p>

<p>I recreated my problem in a Unit test with the following example setup:</p>

<pre><code>class Example {
    private HashMap&lt;Integer, String&gt; map;
    Example(){ map = new HashMap&lt;&gt;(); }
    //getter and setter for map
}

class ExampleController {
    private Example example;
    ExampleController(Example example){ this.example = example; }

    public HashMap&lt;Integer, String&gt; getMap(){ return example.getMap(); }
}
</code></pre>

<p>Test class: </p>

<pre><code>class ExampleControllerTest {
    ExampleController exampleController;

    @Before
    public void setUp() throws Exception {
        Example example = mock(Example.class);
        exampleController = new ExampleController(example);
    }

    @Test
    public void testPutThingsInMap() throws Exception {
        HashMap&lt;Integer, String&gt; map = exampleController.getMap();
        map.put(1, ""Test"");
        exampleController.getMap().putAll(map);

        assertEquals(1, exampleController.getMap().size());
    }
}
</code></pre>

<p>When I run the test class I get the following output:</p>

<pre><code>java.lang.AssertionError: 
Expected :1
Actual   :0
</code></pre>

<p>As I am relatively new to testing, I don't know where I went wrong. When I search for unit testing lists, I only find tests for lists that are not contained in an object.</p>
",https://stackoverflow.com/questions/43134289/testing-a-map-contained-in-a-mocked-class,"['java', 'android', 'unit-testing', 'mockito']",3707,TRUE,0,1
Spring MVC - testing services,"<p>i have a question regarding service layer testing in Spring framework.
I have a class ProductService which has method:</p>

<pre><code>public List&lt;Product&gt; getProducts() {
    return productDAO.getProducts();
}
</code></pre>

<p>Is there any way to test it properly? This method retrieve all products using dao layer, when i, for example fill a list with five products(which are in database right now) and test this method by asserting size of the list it seems useless because when i add one product it still passes, but it shouldn't - after adding one product it should return 6 not 5 products...
If you have any usefull sites/yt videos about spring unit testing please let me know.
Thanks for Your help in advance!
Regards</p>
",https://stackoverflow.com/questions/44853137/spring-mvc-testing-services,"['java', 'spring', 'unit-testing', 'spring-mvc', 'spring-mvc-test']",334,TRUE,-1,1
Xtext testing framework in Eclipse Oxygen,"<p>I've got a quite large codebase in Xtext. Today I tried to use the new Eclipse Oxygen. In my Xtext unit-testing package, I've now got a lot of deprecated warnings regarding everything coming from <code>org.eclipse.xtext.junit4</code> package (like <code>@RunWith</code>, <code>@InjectWith</code>, <code>XtextRunner</code> and so on). By googling, I found out, that apparenty the package <code>org.eclipse.xtext.testing</code> should be used instead (see for example here: <a href=""https://github.com/eclipse/xtext-xtend/issues/29"" rel=""nofollow noreferrer"">https://github.com/eclipse/xtext-xtend/issues/29</a>). However I get the error message in Eclipse <code>""org.eclipse.xtext.testing.XXXX cannot be resolved to a type""</code>. Why? Where do I get that package? My auto-completion in Eclipse does not propose anything for <code>org.eclipse.xtext.testing</code>. I have the standard ""Eclipse for DSL developers"" distribution (Oxygen). Here are my environment details.</p>

<pre><code>Eclipse DSL Tools

Version: Oxygen Release (4.7.0)
Build id: 20170620-1800

  Xtext Complete SDK    2.12.0.v20170519-1412   org.eclipse.xtext.sdk.feature.group Eclipse Xtext
    MWE 2 language SDK  2.9.1.201705291011  org.eclipse.emf.mwe2.language.sdk.feature.group Eclipse Xtext
    Xbase   2.12.0.v20170519-1412   org.eclipse.xtext.xbase.feature.group   Eclipse Xtext
    Xbase Library   2.12.0.v20170518-0758   org.eclipse.xtext.xbase.lib.feature.group   Eclipse Xtext
    Xtend IDE   2.12.0.v20170519-1412   org.eclipse.xtend.sdk.feature.group Eclipse Xtend
    Xtext Documentation 2.12.0.v20170519-0809   org.eclipse.xtext.docs.feature.group    Eclipse Xtext
    Xtext Examples  2.12.0.v20170519-1412   org.eclipse.xtext.examples.feature.group    Eclipse Xtext
    Xtext Redistributable   2.12.0.v20170519-1412   org.eclipse.xtext.redist.feature.group  Eclipse Xtext
    Xtext Runtime   2.12.0.v20170519-1412   org.eclipse.xtext.runtime.feature.group Eclipse Xtext
    Xtext UI    2.12.0.v20170519-1412   org.eclipse.xtext.ui.feature.group  Eclipse Xtext
    Xtext Xtext UI  2.12.0.v20170519-1412   org.eclipse.xtext.xtext.ui.feature.group    Eclipse Xtext
</code></pre>
",https://stackoverflow.com/questions/45277038/xtext-testing-framework-in-eclipse-oxygen,"['xtext', 'deprecation-warning', 'eclipse-oxygen']",250,TRUE,0,1
Webpack 2 - Problems parsing node_module,"<p>I'm unit testing with mocha-webpack v1.0.1, node v6.10. However, I'm getting an error from one of our node modules, where webpack couldn't parse a <code>@</code>. This is an internal library that we use that runs fine in another development environment. So, I'm confused why this is happening since you would think that a library in your node_module would be sort of self-sustaining and would know how to parse itself (and is validated as working in another environment).</p>

<pre><code>Error in ./~/abc-components/src/abc-theme/index.scss

  Module parse failed: /path/to/app/node_modules/abc-components/src/abc-theme/index.scss Unexpected character '@' (1:0)
  You may need an appropriate loader to handle this file type.
  | @charset ""UTF-8"";
  | @import ""abc-variables"";
  | @import ""alert"";
</code></pre>

<p>I believe <code>@</code> is an alias we use for resolving the module path in that library. I've modeled my setup after this <a href=""https://eddyerburgh.me/unit-test-vue-components-beginners"" rel=""nofollow noreferrer"">tutorial</a>. 
From <code>package.json</code>:</p>

<pre><code>""unit"": ""BABEL_ENV=test mocha-webpack --webpack-config build/webpack.test.conf.js --require test/unit/.setup src/**/*.spec.js --recursive --watch""
</code></pre>

<p>From <code>build/webpack.test.conf.js</code> config, including some comments of things I've tried:</p>

<pre><code>var path = require('path')
var webpack = require('webpack')
var utils = require('./utils')
var config = require('../config')
// var nodeExternals = require('webpack-node-externals');

function resolve(dir) {
  return path.join(__dirname, '..', dir)
}

module.exports = {
  entry: {
    app: './src/main.js'
  },
  resolve: {
    modules: [path.resolve('./src'), ""node_modules""],
    extensions: ['.js', '.vue', '.json', '.ts'],
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      '@': resolve('src')
    }
  },
  // externals: [nodeExternals()],
  output: {
    path: config.build.assetsRoot,
    filename: '[name].js',
    publicPath: process.env.NODE_ENV === 'production'
      ? config.build.assetsPublicPath
      : config.dev.assetsPublicPath
  },
  // plugins: [
    // new webpack.optimize.CommonsChunkPlugin({
    //   name: ""vendor"",
    //   filename: ""vendor.js"",
    //   minChunks: function (module) {
    //     // This prevents stylesheet resources with the .css or .scss extension
    //     // from being moved from their original chunk to the vendor chunk
    //     if(module.resource &amp;&amp; (/^.*\.(css|scss)$/).test(module.resource)) {
    //       return false;
    //     }
    //     return module.context &amp;&amp; module.context.indexOf(""node_modules"") !== -1;
    //   }
    // }),
  //   new webpack.DefinePlugin({
  //     'process.env': require('../config/test.env')
  //   })
  // ],
  module: {
    loaders: [
      {
        test: /\.(js|vue)$/,
        // loader: 'eslint-loader',
        // enforce: 'pre',
        include: [resolve('src'), resolve('test'), resolve('node_modules')],
        /* options: {
          formatter: require('eslint-friendly-formatter')
        } */
      },
      {
        test: /\.pug$/,
        loader: 'pug-loader'
      },
      {
        test: /\.vue$/,
        loader: 'vue-loader'
        // options: vueLoaderConfig
      },
      {
        test: /\.ts$/,
        loader: ""awesome-typescript-loader"",
        include: [resolve('src'), resolve('test')]
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        query: {
          presets: ['es2015']
        },
        include: [resolve('src'), resolve('test')]
        // exclude: /node_modules/
      },
      {
        test: /\.(mp3|wav)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('audio/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      }
    ]
  },
  resolveLoader: {
    alias: {
      // necessary to to make lang=""scss"" work in test when using vue-loader's ?inject option 
      // see discussion at https://github.com/vuejs/vue-loader/issues/724
      'scss-loader': 'sass-loader'
    }
  }
}
</code></pre>
",https://stackoverflow.com/questions/47948675/webpack-2-problems-parsing-node-module,"['node.js', 'webpack', 'webpack-2']",250,FALSE,0,1
Testing communications software in two different JVMs,"<p>I've written a module in Java that communicates over a socket. I'd like to write a unit test that tests sending and receiving. </p>

<p>To really test the system, I'd like to put the sender in one JVM and the receiver in another and test them together.</p>

<p>From what I've read here and in various blog posts, this isn't really unit testing, it's integration testing. Ok, fine, but I still want it to be part of the build process.</p>

<p>Is there an official, recommended way to launch a second JVM from within a Junit test case? If not, is there another standard testing framework that is designed for this? </p>
",https://stackoverflow.com/questions/42142809/testing-communications-software-in-two-different-jvms,"['java', 'unit-testing', 'junit', 'integration-testing']",26,TRUE,-1,1
Jira Agile: Claim story points at a stage other than closed/done,"<p>I have a scrum process in place for my team and i want to make a little change in the JIRA Agile plugin. I have four columns:</p>

<ol>
<li>Open/Todo</li>
<li>In Progress</li>
<li>Resolved/In UAT</li>
<li>Closed/Done</li>
</ol>

<p>when I place a story in closed column the burndown chart shows the claimed story point and the graph goes down. What I want to do is change that and make JIRA claim the story points as soon as I have put a story into Resolved column. This is because my definition of ""done"" is once the developer has finished working on a story and has performed unit testing we will call that story ""done"". </p>
",https://stackoverflow.com/questions/42365389/jira-agile-claim-story-points-at-a-stage-other-than-closed-done,"['jira', 'scrum', 'jira-plugin', 'jira-agile']",375,TRUE,-3,2
Retrieving DateTime from SQL Server DB,"<p>I am using entity framework and storing a DateTime with kind as 'Utc'.</p>

<p>For unit testing puroposes when retrieving this DateTime from the database it is coming out with an 'unspecified' kind and different ticks value. </p>

<p>I understand that Entity Framework cannot automatically assign it the Utc kind but I cannot understand why it would come out with a different ticks value. </p>

<p>This is a problem since I am using Mspec to test the retrieved value against the one that was put in using</p>

<pre><code>result.Date.ShouldEqual(retrievedDate)
</code></pre>

<p>This statement is returning false since the kinds on each value are different. I also tried:</p>

<pre><code>DateTime.Compare(result.Date, retrievedDate)
</code></pre>

<p>but this returned false since the ticks value is different.</p>
",https://stackoverflow.com/questions/42073719/retrieving-datetime-from-sql-server-db,"['c#', 'asp.net-mvc', 'entity-framework', 'datetime']",203,FALSE,0,1
Does dependency injection mean no inline initialization?,"<p>If I follow dependency injection principle for a class design, I should make sure my class does not try to instantiate its dependencies within my class, but rather ask for the object through the constructor. </p>

<p>This way I am in control of the dependencies I provide for the class while unit-testing it. This I understand. </p>

<p>But what I am not sure is does this mean that a good class design which follows dependency injection principle means that its fields should never be initialized inline? Should we totally avoid inline initialization to produce testable code?</p>

<p>EDIT</p>

<p>Which is better 1 or 2?</p>

<p>1</p>

<pre><code>  public class Car {
       private Tire tire = new Tire(); // 
    }
</code></pre>

<p>2</p>

<pre><code>public class Car {

   private Tire tire;
   public Car(Tire tire) {
       this.tire = tire
   }
}
</code></pre>
",https://stackoverflow.com/questions/46503103/does-dependency-injection-mean-no-inline-initialization,"['java', 'unit-testing', 'testing']",118,FALSE,-1,2
Can&#39;t test POST $http request with $httpBackend,"<p>Trying to cover http requests of my app by unit tests. I use Jasmine and Karma and step by step write my code using this tutorial: <a href=""https://docs.angularjs.org/api/ngMock/service/"" rel=""nofollow noreferrer"">https://docs.angularjs.org/api/ngMock/service/</a>$httpBackend. But I get an error:</p>

<pre><code>Error: No pending request to flush !
        at Function.$httpBackend.flush (eval at &lt;anonymous&gt; (app/index.js:105:1), &lt;anonymous&gt;:1839:41)
        at Object.eval (eval at &lt;anonymous&gt; (app/index.js:137:1), &lt;anonymous&gt;:37:20)
</code></pre>

<p>This answer <a href=""https://stackoverflow.com/questions/16427968/unit-testing-angularjs-controller-with-httpbackend#16429425"">Unit testing AngularJS controller with $httpBackend</a> is so popular for my problem but when I move <code>const controller = createController();</code> down - I've got another one error: <code>Error: Unsatisfied requests: POST http://loalhost:5000/register</code>.</p>

<p>Where is my mistake? What I implemented wrong?</p>

<p>My unit test:</p>

<pre><code>beforeEach(window.module(ngModule.name));

let $httpBackend, $rootScope, $controller, $scope, createController;

beforeEach(
  inject($injector =&gt; {
    $httpBackend = $injector.get('$httpBackend');
    $controller = $injector.get('$controller');
    $rootScope = $injector.get('$rootScope');
    $scope = $rootScope.$new();

    createController = () =&gt;
      $controller('RegistrationController', { $scope });
  })
);

afterEach(() =&gt; {
  $httpBackend.verifyNoOutstandingExpectation();
  $httpBackend.verifyNoOutstandingRequest();
});

it('should successfully register user', () =&gt; {
  const controller = createController();
  $httpBackend.flush();
  $httpBackend.expectPOST('http://localhost:5000/register').respond();
  $scope.next('hello@gmail.com', '123456');
  $httpBackend.flush();
});
</code></pre>

<p>Block of code from the controller:</p>

<pre><code>  $scope.status;
  $scope.isFetching = false;

  const handleResponse = response =&gt; {
    $scope.status = response.status;
    $scope.isFetching = false;
  };

  $scope.next = (email, password) =&gt; {
    $scope.isFetching = true;
    $http
      .post('http://localhost:5000/register', { email, password })
      .then(response =&gt; handleResponse(response))
      .catch(response =&gt; handleResponse(response));
  };
</code></pre>

<p><strong>UPD</strong></p>

<p>I also tried to add before each <code>$httpBackend.flush()</code> this one (like here <a href=""https://stackoverflow.com/questions/17573817/angularjs-testing-jasmine-http-returning-no-pending-request-to-flush"">Angularjs testing (Jasmine) - $http returning &#39;No pending request to flush&#39;</a>):</p>

<pre><code>if(!$rootScope.$$phase) {
    $rootScope.$apply();
}
</code></pre>

<p>But anyway, nothing change.</p>
",https://stackoverflow.com/questions/44607153/cant-test-post-http-request-with-httpbackend,"['javascript', 'angularjs', 'jasmine', 'karma-runner', 'karma-jasmine']",524,TRUE,0,1
How to create a dummy QQuickItem in C++ at runtime,"<p>I am using <code>Qt 5.7</code> &amp; unit testing using <code>gtest</code> or as its called <a href=""https://github.com/google/googletest"" rel=""nofollow noreferrer"">googletests</a>.</p>

<p>I have a function to test which intakes a <code>QQuickItem</code>. To test this, I <strong>want to create a <code>QQuickItem</code> on fly when my unit test in run</strong>. <em>Is it possible?</em>  </p>

<p>Note that I do have access to <code>QQmlApplicationEngine</code> or the any qml files like <code>main.qml</code>. However I should be able to create a <code>dummy.qml</code> in the resources of my tests project ?<br>
I also thinking that doing a <code>#include &lt;QQmlApplicationEngine&gt;</code> should give me access to <code>QQmlApplicationEngine</code> ? </p>

<p><strong>How do I create dummy <code>QQuickItem</code> in C++ code <em>with some valid width &amp; height</em> in my unit test, &amp; pass it to my method at runtime?</strong></p>
",https://stackoverflow.com/questions/45640109/how-to-create-a-dummy-qquickitem-in-c-at-runtime,"['qt', 'unit-testing', 'googletest', 'qquickitem']",651,TRUE,0,1
"With regard to design patterns, why not just extend the Entity Framework classes with the business logic?","<p>I've got an ASP.NET MVC application and am looking at ways to improve readability, testing, etc.  Currently, much of the business logic is in the controller and I would like to move this to another location.</p>

<p>Here's one idea I have been looking at using: Entity framework creates entity classes for me (e.g. Product, Customer).  Why not just create partial classes to store the business logic?  Here is an example:</p>

<pre><code>public partial class Product()
{
   public static List&lt;Product&gt; GetGreenProducts()
   {
       using(MyEntities db = new MyEntities())
       {
           return db.Product.where(p =&gt; p.Color == ""green"").ToList();
       }
   }

}
</code></pre>

<p>Then, in the controller, I can do this:</p>

<pre><code>public class ProductController : Controller
{
   public ActionResult GreenProducts()
   {
       return View(Product.GetGreenProducts());
   }
}
</code></pre>

<p>This approach seems 1) Very simple 2) Very clean 3) would allow for easy unit testing.</p>

<p>I think this is a relevant pattern.  Can anyone identify any problems with this, or other thoughts?</p>
",https://stackoverflow.com/questions/45174558/with-regard-to-design-patterns-why-not-just-extend-the-entity-framework-classes,['asp.net-mvc'],25,TRUE,0,1
Is is possible to toggle an Event subscription in one line? (Subscribe/Unsubscribe),"<p>I have an application that will regularly create objects that will subscribe to a statically referenced class' events like so:</p>

<pre><code>protected override void OnSubscribeToggle(bool subscribe)
{
    if (subscribe)
    {
        SomeSingleton.Instance.SomeValueAChanged += OnSomeSingleton_SomeValueAChanged;
        SomeSingleton.Instance.SomeValueBChanged += OnSomeSingleton_SomeValueBChanged;
        SomeSingleton.Instance.SomeValueCChanged += OnSomeSingleton_SomeValueCChanged;
        //...
    }
    else
    {
        SomeSingleton.Instance.SomeValueAChanged -= OnSomeSingleton_SomeValueAChanged;
        SomeSingleton.Instance.SomeValueBChanged -= OnSomeSingleton_SomeValueBChanged;
        SomeSingleton.Instance.SomeValueCChanged -= OnSomeSingleton_SomeValueCChanged;
        //...
    }
}
</code></pre>

<p>My problem is that with this setup I have to have an almost complete copy of the same list of subscriptions to either subscribe or unsubscribe. Without complex unit testing, making sure all the lines were identical and correct comes down to just eye balling it.</p>

<p>Is there a way to toggle subscriptions to events so that I don't have to (pretty much) copy-paste the same lines and hope they match up for all classes that do this?</p>

<p>What I'm looking to do is something like the following:</p>

<pre><code>// My goal (if this were valid code)
protected override void OnSubscribeToggle(bool subscribe)
{
    SomeSingleton.Instance.SomeValueAChanged (subscribe ? (+=) : (-=)) OnSomeSingleton_SomeValueAChanged;
    SomeSingleton.Instance.SomeValueBChanged (subscribe ? (+=) : (-=)) OnSomeSingleton_SomeValueBChanged;
    SomeSingleton.Instance.SomeValueCChanged (subscribe ? (+=) : (-=)) OnSomeSingleton_SomeValueCChanged;
    //...
}
</code></pre>
",https://stackoverflow.com/questions/42804381/is-is-possible-to-toggle-an-event-subscription-in-one-line-subscribe-unsubscri,"['c#', 'events']",181,TRUE,0,1
Creating multiple &quot;main&quot; methods in a Spring Boot project?,"<p>Before using Spring Boot, I would define a main method inside the class where I want to test some methods and eventually delete if for the final version. Here is what I do:</p>

<pre><code>public class UserDAO {

public int getUserSSN( int userId )
{
     //Connect to database and get stuff and return it 
}

public static void main(String[] args)
{
   int x = new UserDAO().getUserSSN( 12 );
   System.out.println( x );
}

}
</code></pre>

<p>This allowed me to quickly test stuff as I develop(as opposed to mocking stuff with JUnit). How can I do the same thing in Spring Boot ?</p>

<p><strong>EDIT:</strong> This is not a best practice question - I think it is generally accepted that JUnits and other unit testing/mocking frameworks are necessary ensure good developer-level testing. I just want to know how to do this quickly(as in less typing - not speed of execution).</p>
",https://stackoverflow.com/questions/42463213/creating-multiple-main-methods-in-a-spring-boot-project,"['java', 'spring', 'spring-mvc']",3133,FALSE,0,1
Set system property in jmockit unit test,"<p>Using a combination of testng and jmockit to do some unit testing. In a method I am testing, it tries to access a system property that I set using a JBoss deploy script, therefore my unit test doesn't have access to the entire JBoss environment to access the properties, so it returns null when testing that method. Tried mocking and setting the system variable directly in my test, but the system property is still returning null in the class that I am testing.</p>

<p>The class being tested:</p>

<pre><code>//returns the correct value in the application but returns null for the test
public static final String webdavrootDir = System.getProperty(""property.name"");

public String getFileUrl(){
       StringBuilder sb = new StringBuilder();
       return sb.append(webdavrootDir)
               .append(intervalDir)
               .append(fileName)
               .toString();
}
</code></pre>

<p>The test:</p>

<pre><code>@Test
    public void getUrl(@Mocked System system){
        system.setProperty(""property.name"", ""https://justatest.com/dav/bulk"");
        String fileUrl = csvConfig.getFileUrl();

        assertEquals(fileUrl, ""https://justatest.com/dav/bulk/otherstuff"");
}
</code></pre>

<p>The test finds the value <code>null/otherstuff</code> but expects <code>https://justatest.com/dav/bulk/otherstuff</code></p>

<p>I have also tried setting the system property in a testng <code>@BeforeMethod</code> method without any success.</p>
",https://stackoverflow.com/questions/44265605/set-system-property-in-jmockit-unit-test,"['java', 'unit-testing', 'testng', 'jmockit', 'system-properties']",10446,TRUE,0,2
"How to execute this code using dependency injection, spring and maven","<p>I'm new to Spring, Maven and Unit Testing (TDD), and I must use all 3 at the same time for a new project.<br>
I've been reading tutorials and code examples for the past day and cannot find a solution.</p>

<p>For this example (a calculator), let's say I have the following Interface:</p>

<pre><code>public interface CalculatorService {
  public double add(double input1,
                    double input2);

  public double substract(double input1,
                          double input2);
}
</code></pre>

<p>This is the implementation of the interface, dependency injection style:</p>

<pre><code>public class MathApplication {
  private CalculatorService calcService;

  public void setCalcService(final CalculatorService calcService) {
    this.calcService = calcService;
  }

  public double add(final double input1,
                    final double input2) {
    return this.calcService.add(input1, input2);
  }

  public double substract(final double input1,
                          final double input2) {
    return this.calcService.substract(input1, input2);
  }
}
</code></pre>

<p>The tests class:</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)
public class MathApplicationTester {
    @Rule
    public final ExpectedException exception = ExpectedException.none();

  @InjectMocks // Marks where to inject the mocks.
  MathApplication mathApplication = new MathApplication();

  @Mock // Marks the mocks to be injected.
  CalculatorService calcService;

  @Test
  public void whenAddCorrectThenDoOperation() { 
    // GIVEN

    // WHEN
    when(this.calcService.add(10.0, 20.0)).thenReturn(30.00); // Adds the behaviour of calc service
                                                              // to add two numbers.

    // THEN
    assertThat(this.mathApplication.add(10.0, 20.0)).isEqualTo(30.0); // Tests the functionality
                                                                      // added.
    verify(calcService, times(1)).add(10.0, 20.0);
  }

    @Test
    public void whenSubstractIsCorrectThenDoOperation() throws Exception {
        // GIVEN

        // WHEN
        when(calcService.substract(20.0, 8.0)).thenReturn(12.0);

        // THEN
        assertThat(mathApplication.substract(20.0, 8.0)).isEqualTo(12.0);
    }
}
</code></pre>

<p>And this is the Main, as I have it right now:</p>

<pre><code>@SpringBootApplication
public class TddMockitoApplication {

    public static void main(String[] args) {
        SpringApplication.run(TddMockitoApplication.class, args);
    }
}
</code></pre>

<p>My question is: what do I have to put into the main, or how do I run this code, if let's say I want to make an addition or a subtraction.</p>
",https://stackoverflow.com/questions/45011578/how-to-execute-this-code-using-dependency-injection-spring-and-maven,"['java', 'spring', 'maven', 'unit-testing', 'dependency-injection']",574,TRUE,0,3
How to test client-server flows with boost::test,"<p>Currently I do it this way (pseudocode):</p>

<pre><code>#include &lt;boost/test/unit_test.hpp&gt;
#include &lt;string&gt;

bool testingClient = true;

BOOST_AUTO_TEST_SUITE(ProtocolSchema)
BOOST_AUTO_TEST_CASE(server)
{
    testingClient = false;
    // start server listener
    FILE *client_stdout = popen((argv[0] + std::string("" --run_test=ProtocolSchema/client 2&gt;&amp;1"")).c_str(), ""r"");
    for (1000ms)
    {
       // listen for ping, reply with a pong  
    }
    pclose(fl);
}

BOOST_AUTO_TEST_CASE(client)
{
    if (!testingClient)
        return;
    // send ping to the server
    // check that it replies with a pong
}
}
</code></pre>

<p>The idea is clear: <code>boost::test</code> runs tests sequentially, once it tries to run server, the server unit test flips <code>testingClient</code> this way next test simply doesn't do anything and exits. server test starts the same test executable with <code>run_test</code> arg set to run client test only. In the second process <code>testingClient</code> flag isn't flipped, this makes it actually run client test.</p>

<p>Is there a proper way to do this kind of client-server unit testing with boost::test? In my case all the test logging from client process are kind of lost: I'd need to fread them from client_stdout and then perhaps write it all to BOOST_MESSAGE?</p>
",https://stackoverflow.com/questions/42869374/how-to-test-client-server-flows-with-boosttest,"['unit-testing', 'boost', 'boost-test']",226,FALSE,0,1
java.lang.NoClassDefFoundError: org/apache/lucene/codecs/simpletext/SimpleTextCodec,"<p>I want to perform unit testing in Elasticsearch for that I am using <code>Java-test-framework</code><br>
I am using <code>Elasticsearch-1.6.0</code>
and referring to these link for help 
<a href=""https://www.elastic.co/guide/en/elasticsearch/reference/1.6/using-elasticsearch-test-classes.html"" rel=""nofollow noreferrer"">https://www.elastic.co/guide/en/elasticsearch/reference/1.6/using-elasticsearch-test-classes.html</a>
<a href=""https://github.com/elastic/elasticsearch/blob/master/core/src/test/java/org/elasticsearch/action/search/SearchRequestBuilderTests.java"" rel=""nofollow noreferrer"">https://github.com/elastic/elasticsearch/blob/master/core/src/test/java/org/elasticsearch/action/search/SearchRequestBuilderTests.java</a></p>

<p>here is the code </p>

<pre><code>class CampaignESTest extends ESTestCase {

  def getCLient():MockTransportClient={
     val settings = Settings.builder()
                .put(Environment.PATH_HOME_SETTING.getKey(), Files.createTempDir().toString())
                .build();
     val client = new MockTransportClient(settings);  
     client
  }
 }

class CampaignTestSearch extends PlaySpec{
  val client=new CampaignESTest

val response = client.prepareSearch(""dbtest"")
      .setTypes(CAMPAIGN_COLLECTION_NAME)
      .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
      .addFields(""uuid"",""campaignName"",""artworkID"",""activationDate"",""_source"")
      .setQuery(query)
      .execute()
      .actionGet()
  }
</code></pre>

<p>I am getting this exception </p>

<pre><code>Exception encountered when attempting to run a suite with class name: org.scalatest.DeferredAbortedSuite *** ABORTED ***
[info]   java.lang.NoClassDefFoundError: org/apache/lucene/codecs/simpletext/SimpleTextCodec
[info]   at org.apache.lucene.util.LuceneTestCase.&lt;clinit&gt;(LuceneTestCase.java:616)
[info]   at testcontrollers.campaign.CampaignTestSearch.&lt;init&gt;(CampaignTestSearch.scala:40)
[info]   at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
[info]   at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
[info]   at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
[info]   at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
[info]   at java.lang.Class.newInstance(Class.java:442)
[info]   at org.scalatest.tools.Framework$ScalaTestTask.execute(Framework.scala:468)
[info]   at sbt.ForkMain$Run$2.call(ForkMain.java:296)
[info]   at sbt.ForkMain$Run$2.call(ForkMain.java:286)
[info]   ...
[info]   Cause: java.lang.ClassNotFoundException: org.apache.lucene.codecs.simpletext.SimpleTextCodec
[info]   at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
[info]   at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
[info]   at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
[info]   at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
[info]   at org.apache.lucene.util.LuceneTestCase.&lt;clinit&gt;(LuceneTestCase.java:616)
[info]   at testcontrollers.campaign.CampaignTestSearch.&lt;init&gt;(CampaignTestSearch.scala:40)
[info]   at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
[info]   at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
[info]   at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
[info]   at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
[info]   ...
</code></pre>

<p>getting an exception on this line </p>

<pre><code>val client=new CampaignESTest
</code></pre>

<p>in class <code>CampaignTestSearch</code></p>

<p>here is the dependencies in <code>build.sbt</code> file </p>

<pre><code>""org.elasticsearch"" % ""elasticsearch"" % ""1.6.0"",
                ""org.elasticsearch.test"" % ""framework"" % ""5.0.0"" % ""test"",
                ""org.apache.lucene"" % ""lucene-test-framework"" % ""4.10.4"" % ""test"",
                ""com.carrotsearch.randomizedtesting"" % ""randomizedtesting-runner"" % ""1.6.0"" % ""test"",
                ""org.a""org.apache.lucene"" % ""lucene-expressions"" % ""4.10.4"",
                pache.lucene"" % ""lucene-backward-codecs"" % ""5.4.0"",
</code></pre>

<p>i suspect the cause of the exception maybe due to some versions of the dependencies can anyone please help with the correct library dependency version to make it to work or is tehre something else which i am missing  </p>
",https://stackoverflow.com/questions/45758937/java-lang-noclassdeffounderror-org-apache-lucene-codecs-simpletext-simpletextco,"['java', 'scala', 'unit-testing', 'elasticsearch', 'lucene']",1640,TRUE,0,1
How do I access elements of child component from parent for testing Angular 2?,"<p>I'm trying to get an element of child component from a parent component for testing in Karma-Jasmine. 
I have a component(parent) with contact form which in-turn has a username and password component(child) which is used for validating the form and displaying error messages. Now I need to test the alert messages of child component from the parent component. I tried following</p>

<pre><code>   let parent = fixture.debugElement.query(By.css('input-component'));
   let child = parent.query(By.css('alert'));
</code></pre>

<p>But I did not manage to get any result. it just returns the parent HTML. I found a solution for E2E testing <a href=""https://angular.io/guide/component-interaction#test-it-4"" rel=""nofollow noreferrer"">here</a> but it doesn't work with Unit testing.</p>

<p>How can I accomplish the task. Here's the <a href=""https://plnkr.co/edit/p0S1ukTW1V3U1AK0hE92?p=preview"" rel=""nofollow noreferrer"">Plunker</a> for explaining my scenario.</p>
",https://stackoverflow.com/questions/46036766/how-do-i-access-elements-of-child-component-from-parent-for-testing-angular-2,"['html', 'angular', 'unit-testing', 'karma-jasmine']",2165,TRUE,0,1
Assert body of HTTP requests using requests_mock,"<p>I am using <a href=""http://requests-mock.readthedocs.io/en/latest/"" rel=""noreferrer"">requests-mock</a> with pytest to facilitate unit testing my library, which uses <a href=""http://docs.python-requests.org/en/master/"" rel=""noreferrer"">requests</a> for API calls.</p>

<p>In addition to mocking server responses, I often need to verify that my library sends the expected payload in the HTTP body.</p>

<p>I have been able to do this, albeit indirectly, using an <a href=""http://requests-mock.readthedocs.io/en/latest/matching.html#additional-matchers"" rel=""noreferrer"">additional_matcher</a> callback in my tests:</p>

<pre><code>def mylibrary_foo():
    """"""Library method that is under test.""""""
    r = requests.post('http://example.com/foo', data='hellxo')
    return r.text

@requests_mock.Mocker()
def test_foo(m):
    def matcher(request):
        assert request.body == 'hello'
        return True

    m.post('http://example.com/foo', text='bar', additional_matcher=matcher)

    result = mylibrary_foo()
    assert result == 'bar'
</code></pre>

<p>But it feels a little funny to be using the <code>additional_matcher</code> callback to verify the request format, as it is really intended to determine whether or not this particular request call should be mocked at all. Were I not using requests-mock, it seems I would be doing something more like:</p>

<pre><code>def test_foo():
   # setup api_mock here...
   mylibrary_foo()
   api_mock.assert_called_with(data='hello')
</code></pre>

<p>Is there a pattern commonly used with requests-mock to support HTTP request verification?</p>
",https://stackoverflow.com/questions/47723797/assert-body-of-http-requests-using-requests-mock,"['python', 'unit-testing', 'python-requests', 'pytest']",9891,TRUE,9,1
How do I generalize calling a list of functions in C++?,"<p>I have the following code which allows me to instantiate and then call a list of <code>void()</code> functions.</p>

<p>(I am using <a href=""https://github.com/philsquared/Catch"" rel=""nofollow noreferrer"">https://github.com/philsquared/Catch</a> for unit testing if you wish to compile and run this code).</p>

<pre><code>#include ""catch.hpp""

#include &lt;functional&gt;
#include &lt;vector&gt;

class ChainOfResponsibility : public std::vector&lt;std::function&lt;void()&gt; &gt;, public std::function&lt;void()&gt;
{
public:
    void operator()() const
    {
        for(std::vector&lt;std::function&lt;void()&gt; &gt;::const_iterator it = begin(); it != end(); ++it) {
            (*it)();
        }
    }
};

TEST_CASE(""ChainOfResponsibility calls its members when invoked"")
{
    bool test_function_called = false;
    std::function&lt;void()&gt; test_function = [&amp;]()
    {
        test_function_called = true;
    };

    ChainOfResponsibility object_under_test;

    object_under_test.push_back(test_function);
    object_under_test();

    REQUIRE(test_function_called);
}
</code></pre>

<p>My question is how do I template the <code>ChainOfResponsibility</code> class to accept functions with a different (but consistent) signature?</p>

<p>For example, consider a <code>ChainOfResponsibility&lt;void(int)&gt;</code> or a <code>ChainOfResponsibility&lt;ReturnClass(Argument1Class, Argument2Class)&gt;</code>.</p>

<p>For the sake of argument, lets say that the second example returns the value returned by the last member in the chain, or the default value for ReturnClass if the chain is empty.</p>

<p>Also, if the STL already contains a template class that achieves this, then I would prefer to use it over my home-grown class.</p>
",https://stackoverflow.com/questions/45752194/how-do-i-generalize-calling-a-list-of-functions-in-c,"['c++', 'templates', 'chain-of-responsibility']",469,TRUE,4,2
How to write unit tests supporting Javascript 6 modules,"<p>My Javascript codebase is based on new <a href=""https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import"" rel=""nofollow noreferrer"">ES6 Modules</a>.</p>

<p>So I have Javascript files like this for example:</p>

<pre><code>export class MyClass {
  constructor() {
    this.list = [];
  }

  add(el) { this.list.push(el); }
}
</code></pre>

<p>As a module, I import this file in other Javascript files like this:</p>

<pre><code>import * as lists from ""./myclass"";
</code></pre>

<p>And inside an HTML page, the following syntax has to be used:</p>

<pre><code>&lt;script src=""myclass.js"" type=""module""&gt;&lt;/script&gt;
</code></pre>

<h2>Unit testing</h2>

<p>I need a framework for testing my code. The problem is that I am using Javascript 6 modules, so modern frameworks like <a href=""https://karma-runner.github.io/1.0/index.html"" rel=""nofollow noreferrer"">karma</a> have problems as they import the files not as modules:</p>

<pre><code>module.exports = function(config) {
  config.set({
    files: [
      'src/**/*.js',
      'test/**/*.js'
    ],
    ...
  })
}
</code></pre>

<p>Above is an example of <code>karma.conf.js</code>. In the specific case of Karma, the runner will not import the files as modules, thus the injection in page fails.</p>

<p>What unit test frameworks can I use for testing Javascript 6 modules?</p>
",https://stackoverflow.com/questions/45749484/how-to-write-unit-tests-supporting-javascript-6-modules,"['javascript', 'unit-testing', 'ecmascript-6']",1769,TRUE,4,3
how to functional-test a console&#39;s command input validator,"<p>I want to functional-test a Symfony's <code>command</code> I'm creating. I'm taking advantage of the <code>Question</code> helper class, by associating a personal <code>validator</code>:</p>

<pre><code>    $helper = $this-&gt;getHelper('question');
    $question = new Question('Enter a valid IP: ');
    $question-&gt;setValidator($domainValidator);
    $question-&gt;setMaxAttempts(2);
</code></pre>

<p>the tests I'm performing are functionals, so in order to mock the interaction I added something like the following to my PHPUnit's test class. Here's an excerpt:</p>

<pre><code>public function testBadIpRaisesError()
{
            $question = $this-&gt;createMock('Symfony\Component\Console\Helper\QuestionHelper');
            $question
                -&gt;method('ask')
                -&gt;will($this-&gt;onConsecutiveCalls(
                    '&lt;IP&gt;',
                    true
                ));
    ...
}

protected function createMock($originalClassName)
{
    return $this-&gt;getMockBuilder($originalClassName)
                -&gt;disableOriginalConstructor()
                -&gt;disableOriginalClone()
                -&gt;disableArgumentCloning()
                -&gt;disallowMockingUnknownTypes()
                -&gt;getMock();
}
</code></pre>

<p>of course this mock is more than ok when I'm testing something that goes beyond the <code>Question</code> helper, but in this case what I'd like to do is testing the whole thing in order to make sure the validator is well written.</p>

<p>What's the best option in this case? Unit testing my validator is OK, but I would like to functional-testing it as a black box by the user point of view</p>
",https://stackoverflow.com/questions/43099623/how-to-functional-test-a-consoles-command-input-validator,"['symfony', 'unit-testing', 'symfony-2.8', 'symfony-console']",365,TRUE,4,1
Mocking DbSet.AddOrUpdate,"<p>I am following the instructions <a href=""https://msdn.microsoft.com/en-us/library/dn314429(v=vs.113).aspx"" rel=""nofollow noreferrer"">here</a> to try to mock my <code>DbSet</code> and <code>DbContext</code> for unit testing using Moq.</p>

<p>The service that I'm testing looks like this</p>

<pre><code>public class MyItemService
{
   private MyContext context;

   public void AddItem(MyItem item)
   {
      this.context.MyItems.AddOrUpdate(item);
      this.context.SaveChanges();
   }
}
</code></pre>

<p>My unit test looks like this</p>

<pre><code>[TestMethod]
public void AddItem_ShouldSucceed()
{
    var myItems = new Mock&lt;DbSet&lt;MyItem&gt;&gt;();

    var context = new Mock&lt;MyContext&gt;();
    context.Setup(e =&gt; e.MyItems).Returns(myItems.Object);          

    MyItemService service = new MyItemService(context.Object);

    service.AddItem(new MyItem
    {
        Id = ""1234""
    });
}
</code></pre>

<p>When I run the test, I am getting the exception </p>

<p><code>System.InvalidOperationException: Unable to call public, instance method AddOrUpdate on derived IDbSet&lt;T&gt; type 'Castle.Proxies.DbSet``1Proxy'. Method not found.</code> </p>

<p>I assume the problem is because <code>AddOrUpdate</code> is an extension method on <code>DbSet</code>.  I <strong>do</strong> have <code>System.Data.Entity.Migrations</code> included in my test .cs file.  </p>

<p>I tried adding the line</p>

<pre><code>myItems.Setup(e =&gt; e.AddOrUpdate(It.IsAny&lt;MyItem&gt;()));
</code></pre>

<p>to my unit test, but then I get the exception</p>

<p>System.NotSupportedException: Expression references a method that does not belong to the mocked object: e => e.AddOrUpdate(new[] { It.IsAny() })</p>

<p>Is there any way that I can have my unit test work when my method being tested is using <code>AddOrUpdate</code>?</p>
",https://stackoverflow.com/questions/43746737/mocking-dbset-addorupdate,"['c#', 'entity-framework-6', 'moq']",2448,TRUE,4,2
scipy curve_fit using linear weights instead of sigmas,"<p>I've been fiddling around with the scipy.optimize.curve_fit() function today and I can get some pretty good results, but I'm not too sure how to make some data points weigh more than others.</p>

<p>Let me briefly summarize the situation:
We need to fit a decay curve to some data gathered from our experiment. Some data points occur more often than others and these are determined by a weight. So that means that if we have one data point A with weight x and one data point B with weight 2x, this would be equal to fitting a curve to one data point A with weight x and two data point B's with weight x.</p>

<p>The problem is that the curve_fit function can only be weighed using uncertainties, i.e. sigmas. I thought I was smart to translate each weight into the proportion of the sum of all the weights and then translate this proportion to a Z-score (I thought that would be equivalent in terms of uncertainty) and while this gave a MUCH better fit than not weighing anything at all, I still found through some unit testing that it wasn't when comparing weights of 0.5 to having two actual data points.</p>

<p><strong>How can I use curve_fit with linear weights?</strong></p>

<p>PS: Through unit testing I've found that fitting data points:</p>

<pre><code>(0,0) with weight 1
(1,0) with weight 1
(1,1) with weight 1
(1,1) with weight 1
</code></pre>

<p>yields an equal result as fitting:</p>

<pre><code>(0,0) with weight 1
(1,0) with weight 1
(1,1) with weight 0.70710678118
</code></pre>

<p>And peculiarly, sin(0.5*pi) = 1 and sin(0.25*pi) = 0.70710678118!! So there seems to be a sine relation here? Unfortunately my math skills are limiting me in understanding the exact relation.</p>

<p>Also, sin(0.125*pi) unfortunately doesn't equal a weight of 3 or 4...</p>
",https://stackoverflow.com/questions/44318015/scipy-curve-fit-using-linear-weights-instead-of-sigmas,"['python', 'numpy', 'scipy', 'curve-fitting']",1724,FALSE,4,0
Sinonjs how to stub dependency injection class?,"<p>I have sample code written below (which simplifies from my actual code implementation), the main idea of this simplified version, is to understand how can I stub the class for unit testing</p>

<p>I have <code>Sensor</code> class which is dependency injected into <code>Context</code> class, this <code>Sensor</code> will obtain data from some <code>IO</code> port.</p>

<p>The sensor data will be compared at <code>ComputeSensor</code> class for an expected value, and it will insert <code>report</code> key into the <code>context.report</code> object.</p>

<p>May I know how can I stub or mock the <code>Sensor</code> class, so I could create a fake value to test the code?</p>

<pre><code>class Sensor {
  getData() {        
    return {
      heat: this.getHeatSensor(), // get data from some IO
      speed: this.getSpeedSensor() // get data from some IO
    }
  }
}

class Context {
  constructor(sensor) {
    this.report = {};
    this.sensor = sensor;
    this.computeSensor = new ComputeSensor();
  }

  execute() {
    this.computeSensor.compute(this, this.sensor.getData());
  }
}

class ComputeSensor {
  compute(context, sensorData) {
    if (sensorData.heat === 123
      &amp;&amp; sensorData.speed === 321) 
    {
      context.report = {
        sensor: 'ok'
      }  
    }
  }
}

const sensor = new Sensor();
const context = new Context(sensor);
context.execute();
console.log(context.report) // { sensor: 'ok }
</code></pre>

<p>Maybe desired stub code will be like this?</p>

<pre><code>const stubSensor = sinon.createStubInstance(Sensor);
// Inject the stub return value here?
stubSensor.getData() = {
  heat: 123,
  speed: 321,
}
</code></pre>

<p>Or I could write a mock class as below..But I think Sinon could do that..</p>

<pre><code>class MockSensor {
      getData() {
             return {
                   heat: 123,
                   speed: 321
             }
      }
 }
</code></pre>
",https://stackoverflow.com/questions/42323187/sinonjs-how-to-stub-dependency-injection-class,"['javascript', 'unit-testing', 'mocha.js', 'sinon', 'stub']",2144,TRUE,3,1
Service layer testing: Is it still unit testing when using dbUnit and not mocking a native Spring domain layer?,"<p>I have a service layer and a domain layer. I use plain native Spring repositories for the domain layer and in my test setup I'm mocking the db with <code>dbunit</code>. </p>

<pre><code>@Repository
public interface ExampleRepository extends PagingAndSortingRepository&lt;ExampleEntity, Long&gt;, JpaSpecificationExecutor&lt;ExampleEntity&gt; {
}
</code></pre>

<p>Naturally I will assume that the Spring repository implementation has no errors and therefor the domain layer is no subject to tests. </p>

<p>My general knowledge about unit testing is that I would need to mock my domain layer when writing unit tests for my service layer.</p>

<p>With my assumption that the domain layer does not need to be tested, and the with the fact, that I use <code>dbunit</code> to mock my database, am I allowed to use this setup for unit tests of my service layer?</p>
",https://stackoverflow.com/questions/46155130/service-layer-testing-is-it-still-unit-testing-when-using-dbunit-and-not-mockin,"['java', 'spring', 'unit-testing', 'spring-data', 'dbunit']",756,TRUE,3,2
Unit test private and static methods in java,"<p>I'm writing unit tests for an app of mine and as good practice I try to make all methods in my classes as private as possible, so I may end up with classes with mostly private methods, few public ones and sometimes some calls to static methods (either of my other classes or to some TextUtils, etc)</p>

<p>I would like to know how to get to test all of my classes trying to rely only on Mockito and JUnit since Robolectric and Powermockito seem to stretch the boundaries of what should be done in unit testing. Should I disregard all private and static methods along with public methods that by chance call some static or private ones? or how?</p>
",https://stackoverflow.com/questions/46207409/unit-test-private-and-static-methods-in-java,"['java', 'android', 'unit-testing', 'static', 'private']",5340,TRUE,3,2
Field injection in unit tests with Dagger 2,"<p>As advised in <a href=""https://google.github.io/dagger/testing.html"" rel=""noreferrer"">Dagger documentation</a>, for unit testing we don't have to involve Dagger at all, and for the provided example it makes sense:</p>

<pre><code>class ThingDoer {
  private final ThingGetter getter;
  private final ThingPutter putter;

  @Inject ThingDoer(ThingGetter getter, ThingPutter putter) {
    this.getter = getter;
    this.putter = putter;
  }

  String doTheThing(int howManyTimes) { /* … */ }
}
</code></pre>

<p>With this class structure it is simple to unit test, just mock the <code>getter</code> and <code>putter</code>, pass them as constructor arguments, instruct mockito what to return when interacting with any of these objects, and then make assertions on <code>doTheThing(...)</code>.</p>

<p>Where I am struggling at testing is when I have to unit test a class with a structure similar to this:</p>

<pre><code>class ThingDoer {
    @Inject
    ThingGetter getter;

    @Inject
    ThingPutter putter;

    @Inject
    ThingMaker maker;

    @Inject
    // other 10 objects

    public ThingDoer() {
        App.getThingComponent().inject(this);
    }

    String doTheThing(int howManyTimes) { /* … */ }
}
</code></pre>

<p>As you can see, I am no longer using constructor injection, but field injection instead. The main reason is not have too many parameters in the constructor.</p>

<p>Is there a way to inject mock dependencies in <code>ThingDoer</code> when all its dependencies are provided using field injections?</p>
",https://stackoverflow.com/questions/41485191/field-injection-in-unit-tests-with-dagger-2,"['android', 'unit-testing', 'dagger-2']",2694,TRUE,8,1
Laravel + VueJs + Webpack + Karma = world of pain,"<p>Is it possible to write unit tests for VueJs if you are using Laravel's Elixir for your webpack configuration?</p>
<p>VueJs 2x has a very simple example for a component test: <a href=""https://v2.vuejs.org/v2/guide/unit-testing.html"" rel=""nofollow noreferrer"">Vue Guide Unit testing</a></p>
<pre><code>&lt;template&gt;
  &lt;span&gt;{{ message }}&lt;/span&gt;
&lt;/template&gt;
&lt;script&gt;
  export default {
    data () {
      return {
        message: 'hello!'
      }
    },
    created () {
      this.message = 'bye!'
    }
  }
&lt;/script&gt;
</code></pre>
<p>and then...</p>
<pre><code>// Import Vue and the component being tested
import Vue from 'vue'
import MyComponent from 'path/to/MyComponent.vue'

describe('MyComponent', () =&gt; {
  it('has a created hook', () =&gt; {
    expect(typeof MyComponent.created).toBe('function')
  })
  it ...etc
})
</code></pre>
<p>and gives an example of a karma conf file here: <a href=""https://github.com/vuejs-templates/webpack/blob/master/template/test/unit/karma.conf.js"" rel=""nofollow noreferrer"">https://github.com/vuejs-templates</a></p>
<p>But the Karma configuration file requires a webpack configuration file</p>
<pre><code>webpack: webpackConfig,
</code></pre>
<p>The only problem is the Laravel's Elixir is creating the webpack configuration so it can't be included.</p>
<p>I have tried creating another webpack configuration file based on the example from <a href=""https://github.com/vuejs-templates/webpack"" rel=""nofollow noreferrer"">https://github.com/vuejs-templates/webpack</a>.</p>
<p>Something like this:</p>
<pre><code>var path = require('path');
var webpack = require('webpack');

module.exports = {
    entry: './src/main.js',
    output: {
        path: path.resolve(__dirname, './dist'),
        publicPath: '/dist/',
        filename: 'build.js'
    },
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: 'vue-loader',
                options: {
                    loaders: {
                        // Since sass-loader (weirdly) has SCSS as its default parse mode, we map
                        // the &quot;scss&quot; and &quot;sass&quot; values for the lang attribute to the right configs here.
                        // other preprocessors should work out of the box, no loader config like this necessary.
                        'scss': 'vue-style-loader!css-loader!sass-loader',
                        'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax'
                    }
                    // other vue-loader options go here
                }
            },
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            },
            {
                test: /\.(png|jpg|gif|svg)$/,
                loader: 'file-loader',
                options: {
                    name: '[name].[ext]?[hash]'
                }
            }
        ]
    },
    resolve: {
        alias: {
            'vue$': 'vue/dist/vue.esm.js'
        }
    },
    devServer: {
        historyApiFallback: true,
        noInfo: true
    },
    performance: {
        hints: false
    },
    devtool: '#eval-source-map'
}
</code></pre>
<p>and included it like...</p>
<pre><code>// Karma configuration
// Generated on Wed Mar 15 2017 09:47:48 GMT-0500 (CDT)
var webpackConf = require('./karma.webpack.config.js');
delete webpackConf.entry;

module.exports = function(config) {
  config.set({

    webpack: webpackConf, // Pass your webpack.config.js file's content

    webpackMiddleware: {
      noInfo: true,
      stats: 'errors-only'
    },
</code></pre>
<p>But I am getting errors that seem to indicate that webpack isn't doing anything.</p>
<pre><code>ERROR in ./resources/assets/js/components/test.vue
Module parse failed: /var/www/test/resources/assets/js/components/test.vue Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
| &lt;template&gt;
|     &lt;span &gt;{{test}}&lt;/span&gt;
| &lt;/template&gt;
</code></pre>
",https://stackoverflow.com/questions/42819983/laravel-vuejs-webpack-karma-world-of-pain,"['laravel', 'vue.js', 'karma-jasmine']",1377,TRUE,3,2
Angular 2 Test verify API was called,"<p>I am creating a service in Angular 2 which should call an API url to retrieve its data.</p>

<p>For unit testing I would like to verify that the service actually calls the API. To do this TDD, the service <code>getPicture</code> method is currently empty:</p>

<pre><code>@Injectable()
export class ImageService {

  getPicture(id: string) {
    //To be implemented later
  }

}
</code></pre>

<p>My test is as follows:</p>

<pre><code>describe('ImageService', () =&gt; {
  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [HttpModule],
      providers: [
        ImageService,
        { provide: XHRBackend, useClass: MockBackend }
      ]
    });
  });

  afterEach(inject([XHRBackend], (mockBackend) =&gt; mockBackend.verifyNoPendingRequests()));

  describe('getPicture', () =&gt; {

    it('should call picture API', inject([ImageService, XHRBackend], (service: ImageService, mockBackend) =&gt; {
      mockBackend.connections.subscribe((connection) =&gt; {
          expect(connection.request.url).toBe('localhost/some/url/picture');
      });
      service.getPicture('id');
    }));

  });

});
</code></pre>

<p>Wherever I look, I see code to deal with any incoming requests. However, I can't find anything that will cause a failed test when no request is made.</p>

<p>I could set some variable (request received) to false, set it true in the subscribe block but this feels clumsy and something that should have a proper implementation already.</p>

<p>How can I verify that the/any http request was made?</p>
",https://stackoverflow.com/questions/42927560/angular-2-test-verify-api-was-called,"['unit-testing', 'angular', 'mocking', 'jasmine']",313,FALSE,2,0
Is it good to keep android View references private?,"<p>So, in Java in general, encapsulation is obviously an important consideration, and it is generally standard practice to make every variable private unless there is a  good reason to do otherwise.</p>

<p>However, in most of the Google examples in all of the Android documentation, they never declare their references private.</p>

<p>As in, they write</p>

<pre><code>Button someButton;
</code></pre>

<p>instead of</p>

<pre><code>private Button someButton;
</code></pre>

<p>Currently, what I tend to do is make all view references private, and even then only declare them at the class level if I absolutely need class level access to their data.</p>

<p>Is this the right way to do things, or am I just being paranoid?</p>

<p>Perhaps this convention has something to do with unit testing?</p>
",https://stackoverflow.com/questions/43785888/is-it-good-to-keep-android-view-references-private,"['java', 'android', 'unit-testing', 'encapsulation']",93,TRUE,2,2
Java Multistep Validation Method - Refactoring,"<p>I have a method which does multiple validations which are dependent on earlier one. This is purely a REST Service with no form/frontend. e.g.</p>

<pre><code>public Json processPayment(User user, Amount amount, CardData cardData) {
    Json result = new Json();

    Json userResult = validateUser(user);
    if (userResult.isNotValid())
        result.put(""errorCode"", userResult.get(""errorCode"");
        result.put(""message"", userResult.get(""message"");
        return result;
    }

    Merchant merchant = getMerchant(user);
    Json merchantResult = validateMerchant(user);
    if (merchantResult.isNotValid())
        result.put(""errorCode"", merchantResult.get(""errorCode"");
        result.put(""message"", merchantResult.get(""message"");
        return result;
    }

    Json limitsResult = validateLimits(user, merchant, amount);
    if (limitsResult.isNotValid())
        result.put(""errorCode"", limitsResult.get(""errorCode"");
        result.put(""message"", limitsResult.get(""message"");
        return result;
    }

    // Like above there are few more steps.
    .
    .
    .

    // All validations are fine process transaction.
    Json transactionResult = processTransaction(user, merchant, amount, cardData);
    if (transactionResult.isNotValid())
        result.put(""errorCode"", transactionResult.get(""errorCode"");
        result.put(""message"", transactionResult.get(""message"");
    } else {
        result.put(""message"", ""Transaction Successful"");
        result.put(""referenceNumber, transactionResult.get(""rrn"");
    }

    return result;
}
</code></pre>

<p>In each step, if the results are invalid then it should return immediately with the error message otherwise continue to next step.</p>

<p>Due to multiple steps, this method has become too big and almost impossible to do unit testing.</p>

<p>I want to break this method into smaller ones. I have already moved all the business logic of each step into separate methods but still the flow remains in this big method.</p>

<p><strong>Sonarlint CC is 47</strong> which is a big worry.</p>

<p>Please suggest what would be the right approach to handle this.</p>

<p>Thank you.</p>
",https://stackoverflow.com/questions/43520021/java-multistep-validation-method-refactoring,['java'],887,TRUE,2,2
Mocking Sitecore Database using Sitecore FakeDb,"<p>I'm currently unit testing some methods that calls sitecore database. The class has an attribute of Sitecore Database and uses that to get the items. I'm thinking of using Sitecore FakeDb to mock the items. Is there a way that I can use Sitecore FakeDb to test the methods?</p>

<pre><code>public class myClass
{
    private Database myDb;

    public string getMyItemValue()
    {
        var myItem = myDb.GetItem(SomeID);
        string myItemValue = myItem[""value""];

        return myItemValue;
    }
}
</code></pre>

<p>I also created a constructor for the class</p>

<pre><code>public myClass(myDatabase)
{
    myDb = myDatabase;
}
</code></pre>

<p>Now on the unit test I'm trying to use Sitecore FakeDB. I've tried using the basic FakeDb information that I got from this link <a href=""https://github.com/sergeyshushlyapin/Sitecore.FakeDb"" rel=""nofollow noreferrer"">https://github.com/sergeyshushlyapin/Sitecore.FakeDb</a>. The code breaks when passing the FakeDb parameter to the class since it is not a Database. I'm using Xunit by the way.</p>

<pre><code>public class myClassTests
{
    [Fact]
    public void myItemValueTest()
    {
        using (var db = new Db
        {
          new DbItem(""myItem"") { { ""value"", ""hello world!"" } }
        }){
            myClass myclass = myClass(db); /*code breaks here*/

            string myItemValue = myclass.getMyItemValue();
            Assert.Equal(""hello world!"", myItemValue);
        }
    }
}
</code></pre>

<p>Any help would be much appreciated.</p>
",https://stackoverflow.com/questions/44106409/mocking-sitecore-database-using-sitecore-fakedb,"['c#', 'unit-testing', 'sitecore']",2043,TRUE,2,1
"Unit Test a Node.js application with Mocha, Chai, and Sinon","<p>I am new to unit testing Node.js application. My application converts CSV file to JSON after some filtering.</p>

<pre><code>var fs = require('fs');
var readline = require('readline');

module.exports = ((year) =&gt; {
if (typeof year !== ""number"" || isNaN(year)){
    throw new Error(""Not a number"");
}
var rlEmitter = readline.createInterface({
  input: fs.createReadStream('./datasmall.csv'),
  output: fs.createWriteStream('./data.json')
});

rlEmitter.on('line', function(line) {
   /*Filter CSV line by line*/
});
rlEmitter.on('close', function() {
   /*Write to JSON*/
 });
});
</code></pre>

<p>I want to unit test the code, particularly using Sinon spy, stub, and mock. For example spy that createInterface, and the callback for the ""close"" event is called only once. Similarly, the callback for the ""line"" event is called that number of times corresponding to the number of lines in the csv.
Also, how to mock the CSV if it's not present during development time? </p>

<p>One test I tried is, but not sure if this is the right way:</p>

<pre><code>describe(""Test createInterface method of readline"", function(err){
    it(""should be called only once"", function() {
        var spyCreateInterface = sinon.spy(readline, 'createInterface');
        convert(2016);
        readline.createInterface.restore();
        sinon.assert.calledOnce(spyCreateInterface);
});
</code></pre>

<p>Additional suggestion on proper unit test to make this code robust will be highly appreciated.   </p>
",https://stackoverflow.com/questions/41829963/unit-test-a-node-js-application-with-mocha-chai-and-sinon,"['node.js', 'unit-testing', 'tdd', 'sinon', 'chai']",1307,TRUE,1,1
How to unit test a class that depends heavily on other classes?,"

<p>My understanding is that unit testing should test classes in isolation, focusing on granular behavior and substituting objects of other classes using doubles/mocks wherever possible. (Please correct me if I'm wrong here.)</p>

<p>I'm writing a gem with a class called <code>MatchList</code>. <code>MatchList::new</code> takes two arguments, each an instance of another class called <code>MatchPhrase</code>. <code>MatchPhrase</code> contains some behavior that <code>MatchList</code> depends heavily on (<em>i.e.,</em> if you feed anything other than a <code>MatchPhrase</code> to <code>MatchList::new</code>, you're going to get a bunch of ""undefined method"" errors). </p>

<p>My current (naive?) test setup uses <code>let</code> statements to assign variables for use in my examples:</p>

<pre class=""lang-rb prettyprint-override""><code>let(:query)      { MatchPhrase.new('Good Eats') }
let(:candidate)  { MatchPhrase.new('Good Grief') }
let(:match_list) { MatchList.new(query, candidate) }
</code></pre>

<p>How do I write this unit test? Am I right in thinking it should be done without invoking the <code>MatchPhrase</code> class? Is that even possible?</p>

<hr>

<p>For reference, here is what the <code>MatchList</code> class looks like:</p>

<pre class=""lang-rb prettyprint-override""><code>class MatchList &lt; Array
  attr_reader :query, :this_phrase, :that_phrase

  def initialize(query, candidate)
    super(query.length)
    @query = query
    @this_phrase = query.dup
    @that_phrase = candidate
    find_matches until none?(&amp;:nil?)
  end

  private

  def find_matches
    query.each.with_index do |this_token, i|
      next unless self[i].nil?
      that_token = this_token.best_match_in(that_phrase)
      next if that_token.match?(that_token) &amp;&amp;
              this_token != that_token.best_match_in(this_phrase)
      self[i] = this_token.match?(that_token) ? that_token : NilToken.new
      this_phrase.delete_once(this_token)
      that_phrase.delete_once(that_token)
    end
  end
end
</code></pre>
",https://stackoverflow.com/questions/42064022/how-to-unit-test-a-class-that-depends-heavily-on-other-classes,"['ruby', 'unit-testing', 'rspec']",2119,TRUE,6,3
gtest linking error in VS2015: unresolved externals for functions defined in cpp file,"<p>I have created a sample project in VS2015, having one header file and one cpp file. Content of my files are:</p>

<p>Header.h</p>

<pre><code>int fun2(int a);
</code></pre>

<p>Source.cpp</p>

<pre><code>#include ""Header.h""

void main()
{
 fun()2;
}
int fun2(int a) {
  return ++a;
}
</code></pre>

<p>Steps followed:</p>

<ol>
<li>Download Google test (gtest-1.7.0)</li>
<li>Compile gtest into a static library</li>
<li>Create a unit test project</li>
<li>Make a test case </li>
</ol>

<p>The above setup is working fine and able to test the function, if defined in header file of given project. But if the function is defined in Source.cpp file, as written above then compilation is failing with the below linking errors:</p>

<pre><code>Error   LNK2019 unresolved external symbol ""int __cdecl fun2(int)"" (?fun2@@YAHH@Z) referenced in function ""private: virtual void __thiscall a_b_Test::TestBody(void)"" (?TestBody@a_b_Test@@EAEXXZ)  

Error   LNK1120 1 unresolved externals
</code></pre>

<p>Please let me know how resolve this error or how to do the unit testing of a function defined in cpp file using gtest?
I have followed the steps given on this <a href=""http://www.bogotobogo.com/cplusplus/google_unit_test_gtest.php"" rel=""nofollow noreferrer"">link</a>.</p>
",https://stackoverflow.com/questions/47776108/gtest-linking-error-in-vs2015-unresolved-externals-for-functions-defined-in-cpp,"['c++', 'linker-errors', 'googletest']",127,FALSE,1,0
Java mock function to change its behavior,"<p>I am working on writing a unit test for piece of class like this:</p>

<pre><code>public class AClass{
    private List&lt;String&gt; testStringList;

    public void upperMethod(){

        testStringList = new ArrayList&lt;String&gt;();
        // add some thing to the string here
        List&lt;String&gt; newStringList = lowerMethod(testStringList)
        // .......
    }

    public List&lt;String&gt; lowerMethod(testStringList){
        //modify the test string list, like reverse it
        return modifiedString;
    }
}
</code></pre>

<p>I want to change <code>lowerMethod's</code> behavior, when unit testing <code>upperMethod</code>.
For example, append the <code>testStringList</code> with a new item, instead of reverse it.</p>

<p>After reading the <a href=""https://static.javadoc.io/org.mockito/mockito-core/2.7.7/org/mockito/stubbing/Answer.html"" rel=""nofollow noreferrer"">mockito doc</a> I generate some ideas like this:</p>

<pre><code>public class testClass{
    AClass aOriginal;
    AClass aSpy;

    @Before
    public void setUp(){
        aOriginal = new AClass();
        aSpy = spy(aOriginal);

        when(aSpy.lowerMethod(any())).thenAnswer(new Answer() {
            public List&lt;String&gt; answer(InvocationOnMock invocation){
                Object[] objects = invocation.getArguments();

                //Get String list from it somehow, and append a new item, return it
            }
        });
    }

    @Test
    //test method later with new lowerMethod behavior
}
</code></pre>

<p>I think my major question is how to get this idea work? What is the best way to do this?</p>

<p>I've read multiple documents and questions here, my difference is</p>

<ol>
<li>how to pass a list of string through invocation, that is how to extract the list of string for that Object list?</li>
<li>in <code>Mockito.when</code>, when I pass called with <code>any()</code>, the list append function in answer method always return a <code>java.lang.NullPointerException</code>.</li>
</ol>
",https://stackoverflow.com/questions/48026900/java-mock-function-to-change-its-behavior,"['java', 'unit-testing', 'mockito', 'spy']",3242,TRUE,1,4
Stubbing file tests in shUnit2,"<p>I am using shUnit2 to do unit testing in Bash shell scripts.</p>

<p>I have code like this:</p>

<pre><code>if [ ! -x /usr/local/rvm/bin/rvm ]; then
  ...
fi
</code></pre>

<p>etc</p>

<p>I want to write unit tests to test this code, but to do that I need to stub out the behaviour of Bash file tests.</p>

<p>One way I could do this would be to refactor as:</p>

<pre><code>if ! test -x /usr/local/rvm/bin/rvm; then
  ...
fi
</code></pre>

<p>Then I can stub out the test built-in using something like:</p>

<pre><code>test() {
  case ""$*"" in
  ""-x /usr/local/rvm/bin/rvm"")
    false
    ;;
  esac
}
</code></pre>

<p>Creating the files that are expected during <code>setUp</code> might be an option sometimes, but obviously not always.</p>

<p>Or, I could refactor to move file tests inside custom functions, e.g.</p>

<pre><code>rvm_installed() {
  [ -x /usr/local/rvm/bin/rvm ]
}
</code></pre>

<p>Then I can stub this function in my tests.</p>

<p>Is there any way to test this code without refactoring it though?</p>
",https://stackoverflow.com/questions/44870065/stubbing-file-tests-in-shunit2,"['bash', 'unit-testing', 'shunit2']",614,TRUE,1,2
Angular test dependency module,"<p>I am successfully unit-testing a component-under-test. I had to add some more functionality to the component - tooltips and translations. The translation service is my code and I was able to both test component-under-test with the translation service and also with mocked translation service.</p>

<p>The issue I am having is the tooltips. Those come from ng-bootstrap and are usable via importing NgbModule.forRoot() in my app.module. 
I am not able to test the component-under-test without importing this module like so:</p>

<pre><code>  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ComponentUnderTest, TestHostComponent],
      imports: [NgbModule.forRoot()],
      providers: [LocaleService],
    })
      .compileComponents();
  }));
</code></pre>

<p>This doesn't seem right, I do not want to test anything from the module. </p>

<p>How do I go around importing this module in all my tests? </p>
",https://stackoverflow.com/questions/47770597/angular-test-dependency-module,"['angular', 'unit-testing', 'angular-test']",869,TRUE,1,1
How to you test a redux dumb component that renders smart components?,"<p>A ""dumb"" React view can be testing by passing it props before rendering it with <code>enzyme</code>/<code>jsdom</code>. Snapshot testing can then be used to validate the behavior (as in <code>jest</code>).</p>

<p>A smart component composed of a 'dumb view' connected with <code>mapStateToProps</code>/<code>mapDispatchToProps</code> can be tested by:</p>

<ol>
<li>unit testing <code>mapXxxToProps</code> to check the logic is right</li>
<li>testing the <code>dumb</code> view</li>
</ol>

<p>and optionnaly: </p>

<ol start=""3"">
<li>render the smart component by wrapping it in a Provider</li>
</ol>

<p>However, this seems to break whenever a dumb view starts to nest other smart containers ; the rendering of the dumb view is not possible simply with props, since some child components down the chain might need a store.</p>

<p>Is there a way around that ?</p>

<p>Am I missing something ?</p>
",https://stackoverflow.com/questions/43203951/how-to-you-test-a-redux-dumb-component-that-renders-smart-components,"['reactjs', 'redux']",779,FALSE,1,1
Using a mocked Core Data container with background processes,"<p>I implemented unit testing with my Swift iOS app that uses Core Data, but I am having trouble getting unit tests to pass. I referenced the guide linked below and some stack overflow threads, but I'm still having trouble. </p>

<p>The app runs without flaws when actually built, but the tests fail, leading me to believe that I've messed up somewhere with integrating the mocked the Core Data container and background persistent containers. However, I can't seem to figure out where I'm going wrong here, so any advice is appreciated. </p>

<p>I apologize if my post is lacking any key details, but I'll add them in as necessary.</p>

<p>Main reference material: <a href=""https://medium.com/flawless-app-stories/cracking-the-tests-for-core-data-15ef893a3fee"" rel=""nofollow noreferrer"">Cracking the Tests for Core Data</a></p>

<h2>Test Code</h2>

<pre><code>class MealTests: XCTestCase {
var sut: MealController!

lazy var managedObjectModel: NSManagedObjectModel = {
    let managedObjectModel = NSManagedObjectModel.mergedModel(from: [Bundle(for: type(of: self))])!
    return managedObjectModel
}()

lazy var mockPersistentContainer: NSPersistentContainer = {
    let container = NSPersistentContainer(name: ""WeeklyModel"", managedObjectModel: self.managedObjectModel)
    let description = NSPersistentStoreDescription()
    description.type = NSInMemoryStoreType
    description.shouldAddStoreAsynchronously = false

    container.persistentStoreDescriptions = [description]
    container.loadPersistentStores {(description, error) in
        //Double check to confirm that date store is in memory
        precondition(description.type == NSInMemoryStoreType)

        //Check for errors
        if let error = error {
            fatalError(""Creating an in-memory coordinator failed"")
        }
    }
    return container
}()

override func setUp() {
    super.setUp()

    sut = MealController(tense: .all, persistentContainer: mockPersistentContainer)
}


func test_CreatingNewMeal_IsNotNilAndPropertiesSetCorrectly() {
    let mealType = Int16(1)
    let date = NSDate(timeIntervalSinceNow: 0.0)
    let mealDescription = ""Testy McTestFace""
    let servings = Int16(1)
    let image = UIImage(named: ""Recipe"")
    let favorite = false

    let meal = sut.saveLocalMeal(mealType: mealType, date: date, mealDescription: mealDescription, servings: servings, image: image, favorite: favorite)

    //Test meal is not nil
    XCTAssertNotNil(meal, ""Should not be nil"")

    //Testing creating meal sets all properties correctly
    XCTAssertEqual(meal?.meal, mealType)
}
</code></pre>

<h2>Controller Class</h2>

<pre><code>class MealController {

//MARK: - Properties
//&lt;...&gt;

private let persistentContainer: NSPersistentContainer!

private var fetchedResultsController: NSFetchedResultsController&lt;Meal&gt;!

lazy var backgroundMOC: NSManagedObjectContext = {
    return self.persistentContainer.newBackgroundContext()
}()

 //Set to standard persistence container by default
init(tense: Tense, persistentContainer: NSPersistentContainer) {
    self.persistentContainer = persistentContainer
    self.persistentContainer.viewContext.automaticallyMergesChangesFromParent = true

    reloadAllLocalData(for: tense)
}

convenience init(tense: Tense) {
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
        fatalError(""Could not set Managed Object Context"")
    }
    self.init(tense: tense, persistentContainer: appDelegate.persistenceContainer)
}

func getMealCount() -&gt; Int {
    return fetchedResultsController.fetchedObjects?.count ?? 0
}

func getMeal(at indexPath: IndexPath) -&gt; Meal {
    return fetchedResultsController.object(at: indexPath)
}

//The boolean determines whether historical or future data is shown
func reloadAllLocalData(for tense: Tense){
    let fetchRequest: NSFetchRequest&lt;Meal&gt; = Meal.fetchRequest()

    //Setting predicate, etc.
    //&lt;...&gt;

    fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: backgroundMOC, sectionNameKeyPath: nil, cacheName: nil)//Add cache to this?

    do {
        try fetchedResultsController.performFetch()
    } catch let error {
            //&lt;...&gt;
    }
}

//Saving

func saveLocalMeal(mealType: Int16, date: NSDate, mealDescription: String, servings: Int16, image: UIImage?, favorite: Bool, comment: String? = nil, recipeUID: String? = nil) -&gt; Meal? {

    //Make new meal object
    let meal = Meal(entity: Meal.entity(), insertInto: backgroundMOC)

    //Call helper func and result result
    return save(context: backgroundMOC, meal: meal, mealUID: nil, mealType: mealType, date: date, mealDescription: mealDescription, servings: servings, image: image, favorite: favorite, comment: comment, recipeUID: recipeUID)
}

private func save(context: NSManagedObjectContext, meal: Meal, mealUID: String?, mealType: Int16, date: NSDate, mealDescription: String, servings: Int16, image: UIImage?, favorite: Bool, comment: String? = nil, recipeUID: String? = nil) -&gt; Meal? {

    //Setting properties
    //&lt;...&gt;        

    do {
        try backgroundMOC.save()
        return meal
    } catch let error as NSError {
        print(""Could not save. \(error)"")
        return nil
    }
}
</code></pre>
",https://stackoverflow.com/questions/46638091/using-a-mocked-core-data-container-with-background-processes,"['ios', 'swift', 'unit-testing', 'core-data']",556,FALSE,1,0
Encrypting ConnectionString for SQL Unit Tests in Visual Studio 2015,"<p>I have a number of SQL Unit Tests written in Visual Studio 2015. Currently they connect to the database (a SQL Azure Database) using static connection strings in an app.config file.</p>

<p>I would like to protect this information using Azure Key Vault if possible.</p>

<p>I have seen articles such as <a href=""https://kamranicus.com/posts/2016-02-20-azure-key-vault-config-encryption-azure"" rel=""nofollow noreferrer"">this one</a> and <a href=""https://eren.ws/2014/02/04/encrypting-the-web-config-file-of-an-azure-cloud-service/"" rel=""nofollow noreferrer"">this one</a> on encrypting a web.config file but they seem more geared towards azure web apps.</p>

<p>Could anyone provide some implementation recommendations more closely suited to a SQL Unit Testing scenario or confirm that the above approaches would work in my case?</p>

<p>Or is there another solution such as overriding the ExecutionContext which is used by the TestService?</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/41838127/encrypting-connectionstring-for-sql-unit-tests-in-visual-studio-2015,"['unit-testing', 'azure', 'encryption', 'azure-sql-database', 'azure-keyvault']",344,FALSE,1,1
How to unit test flask w/ flask-socket extension,"<p>I'm having trouble figuring out how to write a unit test for a Flask route that's decorated with <code>@Sockets.route</code>. With normal Flask routes, I can set up a test client as a context manager and use that to send requests, but I'm not sure what the analogue is for web sockets.</p>

<p>This is the code I'm trying to write a unit test for:</p>

<pre><code>from flask_sockets import Sockets

sockets = Sockets(app)

@sockets.route('/test')
def echo_socket(ws):
    while not ws.closed:
        message = ws.receive()
        ws.send('success')
</code></pre>

<p>The documentation for Flask-Sockets says I should use the gunicorn worker, but I'm not really clear how to get access to one of those from a unit test (just using the unittest module). I have something like:</p>

<pre><code>def test_echo_socket:
    # this is all incorrect
    with my_app.app.test_client() as context:    
        context.get('/test')
        self.assertEqual(context.response_code, '101')
</code></pre>

<p>Does anyone have any ideas how to get a websocket context for unit testing? Thanks.</p>
",https://stackoverflow.com/questions/43854889/how-to-unit-test-flask-w-flask-socket-extension,"['python', 'unit-testing', 'flask']",140,FALSE,1,0
Moq an interface and setting up a mock,"<p>I have an Interface to check vowel and to return a char as</p>

<pre><code>public interface IVowChecker
{
    bool VowCheck(char a);
    char ReturnChar(int n);
    Student GetStudentById(int n);
}
</code></pre>

<p>It's concrete class implementation</p>

<pre><code>public class VowChecker:IVowChecker
{
    public bool VowCheck(char a)
    {
        if (a == 'a' || a == 'A')
            return true;
        return false;
    }
    public char ReturnChar(int n)
    {
        return (char)n;
    }
    public Student GetStudentById(int n)
    {
        var list = new []
        {
            new Student{RollNo=1,Name=""A""},
            new Student{RollNo=2,Name=""B""},
            new Student{RollNo=3,Name=""C""},
            new Student{RollNo=4,Name=""D""},
            new Student{RollNo=5,Name=""E""},
            new Student{RollNo=6,Name=""F""},
        };

        var student = from i in list
                      where i.RollNo == n
                      select i;
        return student.FirstOrDefault();
    }
}
</code></pre>

<p>And a service using this VowChecker</p>

<pre><code>public class MyCharService
{
    private readonly IVowChecker _checker;

    public MyCharService(IVowChecker checker)
    {
        _checker = checker;
    }
    public bool CheckInput(char a)
    {
        return _checker.VowCheck(a);
    }
    public char ReturnChar(int a)
    {
        return _checker.ReturnChar(a);
    }
    public Student GetStudentById(int n)
    {
        return _checker.GetStudentById(n);
    }
}
</code></pre>

<p>I am using Xunit testing framework for unit testing and Moq library.
My unit test code is </p>

<pre><code>public class MyCharServiceShould
{
    ...

    [Theory]
    [InlineData(65)]
    [InlineData(68)]
    public void BeAbleToReturnChar(int n)
    {
        var service = new Mock&lt;IVowChecker&gt;();

        service.Setup(i =&gt; i.ReturnChar(n)).Returns('A');
        var obj = new MyCharService(service.Object);
        var result = obj.ReturnChar(n);

    }
    [Theory]
    [InlineData(2)]
    public void BeAbleToRetrieveStudent(int n)
    {
        var service = new Mock&lt;IVowChecker&gt;();
        service.Setup&lt;Student&gt;(i =&gt; i.GetStudentById(n)).Returns&lt;Student&gt;(f =&gt; (Student)f);
        var ob = new MyCharService(service.Object);
        var res = ob.GetStudentById(2);
        Assert.Equal(res.Name, ""B"");
    }
}
</code></pre>

<p>My Student class</p>

<pre><code>public class Student
{
    public int RollNo{ get; set; }
    public string Name { get; set; }
}
</code></pre>

<p>I have used a debugger in the last line of my test and checked the values of both the tests. For the 1st test I am expecting 'A' as the result and for the 2nd test I am expecting 'D' as the result. But in both the cases I am getting 'A' as the result. Can anyone kindly help me out where I am missing out the concept. Thank you.</p>
",https://stackoverflow.com/questions/45005941/moq-an-interface-and-setting-up-a-mock,"['unit-testing', 'asp.net-core-mvc', 'moq', 'xunit.net']",2021,TRUE,1,1
"Typeof returns &quot;number&quot;, but logging variable shows string","<p>I'm passing numerical values from a form in an Angular app, to a method in a service. My unit test checks the typeof the values and expects them to be ""number"". It passes.</p>

<p>However, when I console.log the values (both before and after passing to the method) they're shown as strings, e.g. ""10"". Even inside the methods functionality I can see that they're being treated as strings, e.g. 90 + 180 = ""90180"".</p>

<p>Why does typeof return ""number""?</p>

<p>(I've fixed the issue by passing the values as numbers using <code>+variable</code>, I just want to know why typeof returns ""number"" when the type is not number.)</p>

<p>I'm using jasmine for unit testing, here's my test:</p>

<pre><code>it(""coverageParams.heading, .swathWidth, and .impWidth should be typeof 'number'"", () =&gt; {
    // Patching numerical values into the form
    component.fieldCoverageParamsForm.patchValue({
      heading: 30,
      impWidth: 10,
      swathWidth: 20
    });
    fixture.detectChanges();

    // Method in the component snippet below
    component.createCoveragePath();
    expect(typeof component.coverageParams.heading).toBe(""number"");
    expect(typeof component.coverageParams.swathWidth).toBe(""number"");
    expect(typeof component.coverageParams.impWidth).toBe(""number"");
  });
</code></pre>

<p>Here's my component:</p>

<pre><code>export class FieldCoverageParamsComponent {

  public fieldCoverageParamsForm: FormGroup;

  public coverageParams: ICoverageParams;

  constructor(
    private routePlanner: RoutePlanningService,
    private formBuilder: FormBuilder
  ) {
    this.coverageParams = {
      boundary: null,
      heading: 0,
      impWidth: 0,
      startPoint: null,
      swathWidth: 0
    };
    this.createForm();
  }

  public createCoveragePath() {
    const formModel = this.fieldCoverageParamsForm.value;
    this.coverageParams = {
      boundary: formModel.boundary,
      heading: formModel.heading,
      impWidth: formModel.impWidth,
      startPoint: formModel.startPoint,
      swathWidth: formModel.swathWidth
    };

    this.routePlanner.plotRoute(
      this.mapService.mainMapViewer,
      this.coverageParams
    );
  }
}
</code></pre>
",https://stackoverflow.com/questions/47930169/typeof-returns-number-but-logging-variable-shows-string,"['javascript', 'angular', 'typescript', 'jasmine']",153,TRUE,1,3
Spring repository not always throwing DataIntegrityViolationException,"<p>I'm making a REST API with Spring and I have trouble unit testing it.
I wrote an endpoint to update user groups and it does send a 409 conflict when I create a group with a duplicate name in my frontend (unique=true). However when I do the unit test it doesn't. I found out that adding this line <code>groupRepository.findAll().forEach(g -&gt; System.out.println(g.getName()));</code> at the end of the unit test does throw a 409.</p>

<p>Endpoint:</p>

<pre><code>@Override
public ResponseEntity&lt;Object&gt; update(@ApiParam(value = ""form object to add to the store"", required = true) @Valid @RequestBody FormGroupDTO group, @ApiParam(value = ""Id of the form that needs to be updated"", required = true) @PathVariable(""groupId"") Long groupId, @ApiParam(value = ""token to be passed as a header"", required = true) @RequestHeader(value = ""token"", required = true) String token) {
    String name = JWTutils.getEmailInToken(token);

    if(name == null) {
        return new ResponseEntity&lt;&gt;(HttpStatus.FORBIDDEN);
    }

    User user = userRepository.findByEmail(name);

    if(user == null){
        return  new ResponseEntity&lt;&gt;(HttpStatus.FORBIDDEN);
    }

    FormGroup groupModel = groupRepository.findByIdAndAdmin(groupId, user);

    if(groupModel == null){
        return  new ResponseEntity&lt;&gt;(HttpStatus.FORBIDDEN);
    }

    if(group.getMembers().stream().filter(m -&gt; m.getRole() == UserFormGroupRole.ADMIN).toArray().length == 0){
        return new ResponseEntity&lt;&gt;(new ValidationErrorDTO(""noAdmin"", ""MEMBER.NOADMIN""), HttpStatus.BAD_REQUEST);
    }

    // Get users
    groupModel.getUserFormGroups().clear();
    for(MemberDTO member : group.getMembers()){
        User u = userRepository.findByEmail(member.getEmail());
        if(u == null){
            return new ResponseEntity&lt;&gt;(new ValidationErrorDTO(""notexist"", ""ADDUSER.NOTEXIST""), HttpStatus.BAD_REQUEST);
        }
        if(u.getRole() == UserRole.USER){
            return new ResponseEntity&lt;&gt;(new ValidationErrorDTO(""notexist"", ""ADDUSER.NOTPRIVILEGED""), HttpStatus.BAD_REQUEST);
        }
        UserFormGroup ufg = userFormGroupRepository.findByUserAndFormGroup(u, groupModel);
        if(ufg == null){
            groupModel.getUserFormGroups().add(new UserFormGroup(u, groupModel, member.getRole()));
        } else{
            ufg.setRole(member.getRole());
            groupModel.getUserFormGroups().add(ufg);
        }
    }

    groupModel.setName(group.getName());

    try{
        groupRepository.save(groupModel);
        return  new ResponseEntity&lt;&gt;(HttpStatus.NO_CONTENT);
    } catch (DataIntegrityViolationException e){
        System.out.println(e.getMessage());
        System.out.println(e.getClass());
        return  new ResponseEntity&lt;&gt;(HttpStatus.CONFLICT);
    }
}
</code></pre>

<p>My unit test:</p>

<pre><code>@Test
public void updateGroupNameAlreadyInUse() throws Exception {
    groupRepository.save(new FormGroup(""newFormGroup"", user));
    this.mockMvc.perform(put(""/groups/"" + group.getId())
            .header(""token"", token)
            .content(json(new FormGroupDTO(""newFormGroup"", group.getUserFormGroups().stream().map(ufg -&gt; new MemberDTO(ufg.getUser().getEmail(), ufg.getRole())).collect(Collectors.toList()))))
            .contentType(contentType))
            .andExpect(status().isConflict());
}
</code></pre>

<p>The save function of my CrudRepository doesn't always throws DataIntegrityViolationException. I just realised that maybe the first line of my unit test <code>groupRepository.save(new FormGroup(""newFormGroup"", user));</code> might not be executed before the end of my unit test and the <code>findAll</code> function triggers it.</p>
",https://stackoverflow.com/questions/43707774/spring-repository-not-always-throwing-dataintegrityviolationexception,"['java', 'spring', 'junit', 'spring-data', 'spring-restcontroller']",1506,TRUE,1,1
Get the level of a specific logger in python,"<p>For the sake of unit testing, I would like to know the level of a specific logger (<code>logging.Logger</code> instance). The goal is to modify a logger temporarily in the context of a test to log all levels, and then set it back to its previous level. I cannot find a safe way of finding this <em>previous level</em>.</p>

<p>This object has a <code>getEffectiveLevel()</code> that returns the level <strong>if it has been set</strong> or else goes up the tree to return the first non-zero level it encounters. This method is no good to me, because I won't know if the returned value is a parent's level or the actual logger.</p>

<p>I cannot find another method.</p>
",https://stackoverflow.com/questions/45485813/get-the-level-of-a-specific-logger-in-python,"['python', 'logging']",105,TRUE,1,1
Spy on the result of an Observable Subscription with Jasmine,"<p>I am Jasmine unit testing an angular component, which uses Observables. My component has this lifecycle hook that I am testing:</p>
<pre><code>ngOnInit() {
  this.dataService.getCellOEE(this.cell).subscribe(value =&gt; this.updateChart(value));
}
</code></pre>
<p>I have a test that ensures that getCellOEE has been called, but now I want to check that updateChart is called when the observable resolves with a new value. This is what I have so far:</p>
<pre><code>let fakeCellService = {
  getCellOEE: function (value): Observable&lt;Array&lt;IOee&gt;&gt; {
    return Observable.of([{ time: moment(), val: 67 }, { time: moment(), val: 78 }]);
  }
};

describe('Oee24Component', () =&gt; {
  let component: Oee24Component;
  let service: CellService;
  let injector: Injector;
  let fixture: ComponentFixture&lt;Oee24Component&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [Oee24Component],
      providers: [{ provide: CellService, useValue: fakeCellService }]
    })
      .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(Oee24Component);
    component = fixture.componentInstance;
    injector = getTestBed();
    service = injector.get(CellService)
    fixture.detectChanges();
    spyOn(service, 'getCellOEE').and.returnValue({ subscribe: () =&gt; { } });
    spyOn(component, 'updateChart');
  });

  it('should get cell oee on init', () =&gt; {
    component.ngOnInit();
    expect(service.getCellOEE).toHaveBeenCalled();
  });

  it('should update chart on new data', () =&gt; {
    component.ngOnInit();
    expect(component.updateChart).toHaveBeenCalled();
  });
});
</code></pre>
<p>However, I get the error:</p>
<blockquote>
<p>chrome 56.0.2924 (Windows 10 0.0.0) Oee24Component should update chart on new data FAILED</p>
<p>Expected spy updateChart to have been called.</p>
</blockquote>
<p>Presumably this is a timing issue because the observable hasn't necessarily resolved when the test checks? If that is the case, how do I set this up correctly?</p>
<h1>Update:</h1>
<p>Here is my component:</p>
<pre><code>@Component({
  selector: 'app-oee24',
  templateUrl: './oee24.component.html',
  styleUrls: ['./oee24.component.css']
})
export class Oee24Component implements OnInit {
  public barChartData: any[] = [{ data: [], label: 'OEE' }];

  constructor(public dataService: CellService) { }

  ngOnInit() {
    this.dataService.getCellOEE(this.cell).subscribe(value =&gt; this.updateChart(value));
  }

  updateChart(data: Array&lt;IOee&gt;) {
    this.barChartData[0].data = data.map(val =&gt; val.val);
  }
}
 
</code></pre>
",https://stackoverflow.com/questions/43135596/spy-on-the-result-of-an-observable-subscription-with-jasmine,"['unit-testing', 'angular', 'typescript', 'jasmine', 'karma-jasmine']",15634,FALSE,1,4
Sequence contains no matching elements - Entity Framework,"<p>I looked all over Stack Overflow for this exception and found a lot of questions about it, but none that could solve my problem. </p>

<p>I am unit testing my application. All the tests were passing until I put an index on a column of one of my entities. I am using ABP, also. </p>

<p>It's worth noting that the app works fine when I run it, using SQL Server, but my unit tests use an in-memory database.</p>

<p>This works:</p>

<pre><code>[Required]
public string Name
{
   get { return PersonalInformation.Name; }
   set { PersonalInformation.Name = value; }
}
</code></pre>

<p>This doesn't:</p>

<pre><code>[Column(TypeName = ""VARCHAR"")]
[Index]
[Required]
public string Name
{
   get { return PersonalInformation.Name; }
   set { PersonalInformation.Name = value; }
}
</code></pre>

<p>The error ""Sequence contains no elements"" is thrown in a class I created that inherits from <code>AbpIntegratedTestBase</code>, in the first line of this method:</p>

<pre><code>public void UsingDbContext(Action&lt;UnitTestDbContext&gt; action) {
    using (var context = LocalIocManager.Resolve&lt;UnitTestDbContext&gt;())
    {
        action(context);
        context.SaveChanges();
    }
}
</code></pre>

<p>Can anyone help me with this? I'm trying to solve this for 3 days ^^""</p>
",https://stackoverflow.com/questions/47654245/sequence-contains-no-matching-elements-entity-framework,"['c#', 'visual-studio', 'entity-framework-6']",491,FALSE,0,0
Visual Studio 2017 XUnit doesn&#39;t discover tests,"<p>I am following along the examples in the APRESS ""Building Web Applications with Visual Studio 2017"" book.</p>

<p>He has the reader set up a testing project by hand as a C# Console Application.</p>

<p>I pulled down the code and opened up his solution.  I am comparing mine to his side by side:</p>

<p><a href=""https://i.stack.imgur.com/d2XNF.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/d2XNF.png"" alt=""enter image description here""></a></p>

<p>All the Unit Testing Nuget packages are the same.
But when I build both solutions his Tests get discovered and mine do not.</p>

<p><a href=""https://i.stack.imgur.com/G3qeb.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/G3qeb.png"" alt=""enter image description here""></a></p>

<p>All it should be doing at this point is discovering this:</p>

<pre><code>    [Fact]
    public void FirstTest()
    {
        Assert.True(true);
    }
</code></pre>

<p>Everything looks the same.
I created the console project. Added the needed Nuget Packages. Created the needed references. Added the test.</p>

<p>I don't know what else it needs. I followed the directions exactly.</p>
",https://stackoverflow.com/questions/45842160/visual-studio-2017-xunit-doesnt-discover-tests,"['asp.net-core', 'visual-studio-2017', 'xunit']",70,TRUE,0,1
"Testing Typescript with Jest, how do I test an internal function? My import/export is failing me","<p>I am new to Typescript and wanted to implement unit testing with Jest. 
I installed Jest, and when I run it I receive an error, I have simplified the code for this example, and it continues to fail:</p>

<pre><code>FAIL  src\__tests__\validateSender.ts 
https validation
ReferenceError: validateSender is not defined

  at Object.&lt;anonymous&gt;.test (src/__tests__/validateSender.ts:10:10)
  at process._tickCallback (internal/process/next_tick.js:109:7)
</code></pre>

<p>The test which cannot find the function (<code>./src/__tests__/validateSender.js</code>):</p>

<pre><code>import {} from ""jest"";
const connection = {
  encrypted: ""undefined"",
};
const req = {
  connection : (""{connection}""),
};

test(""https validation"", () =&gt; {
  expect(validateSender(req)).toThrow();
});
</code></pre>

<p>the function (<code>./src/validateSender.js</code>):</p>

<pre><code>function validateSender(req) {
  if (typeof req.connection.encrypted === ""undefined"") {
    throw new CustomException(""validateSender"", ""connection must be secured."");
  } else { return; }
}
</code></pre>

<p>my Jest package.json portion (<code>./package.json</code>):</p>

<pre><code>""jest"": {
    ""transform"": {
      ""^.+\\.tsx?$"": ""&lt;rootDir&gt;/node_modules/ts-jest/preprocessor.js""
    },
    ""testRegex"": ""(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$"",
    ""moduleFileExtensions"": [
      ""ts"",
      ""tsx"",
      ""js"",
      ""jsx"",
      ""json""
    ]
  }
</code></pre>

<p>I have attempted adding an import statement for the validateSender file directly, but it fails in the same way (on <code>npm test</code> from the root directory I added <code>import {} from ""./src/validateSender"";</code> to the file and received the error above.)</p>

<p>It was also suggested I try <code>import validateSender from ""./src/validateSender"";</code> but I receive <code>error TS2307: Cannot find module './src/validateSender'.</code></p>

<p>It appears that I am missing some foundational knowledge for this process, but I have failed to find it in the TS handbook.</p>
",https://stackoverflow.com/questions/46874773/testing-typescript-with-jest-how-do-i-test-an-internal-function-my-import-expo,"['javascript', 'node.js', 'unit-testing', 'typescript', 'jestjs']",3038,TRUE,0,1
"Testing System.out.println not working but System,out.print using JUnit","<p>I am learning unit testing with JUnit in Netbeans. But I know how the JUnit works and how to test the System.out.print -
 <a href=""https://stackoverflow.com/questions/1119385/junit-test-for-system-out-println"">JUnit test for System.out.println()</a>. I am a very new to JUnit because I just started JUnit today.</p>

<p>This is my test class</p>

<pre><code>public class CDTest {
    CD cd;
    private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
    private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();

    public CDTest() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {


        System.setOut(new PrintStream(outContent));
        System.setErr(new PrintStream(errContent));
    }

    @After
    public void tearDown() {
        System.setOut(null);
        System.setErr(null);
    }   



    @Test
    public void testSystemOutPrint(){
        System.out.print(""hello"");
        System.out.print(""hello again"");//Please pay attention here. Just System.out.print()
        assertEquals(""hellohello again"", outContent.toString());
    }

}
</code></pre>

<p>When I run the test, it is working successfully. Now I am only testing to the System.out.print. But when I test System.out.println() as below</p>

<pre><code>@Test
public void testSystemOutPrint(){
    System.out.print(""hello"");
    System.out.println(""hello again""); //Please pay attention here for println()
    assertEquals(""hellohello again"", outContent.toString());
}
</code></pre>

<p>The above code give me this error.</p>

<p><a href=""https://i.stack.imgur.com/V8R3O.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/V8R3O.png"" alt=""enter image description here""></a></p>

<p>I tried adding system to fix the error like this.</p>

<pre><code>@Test
public void testSystemOutPrint(){
    System.out.print(""hello"");
    System.out.println(""hello again""); //Please pay attention here for println()
    assertEquals(""hellohello again "", outContent.toString());//Please pay attention to the space after ""again""
}
</code></pre>

<p>As you can see above, I added a space after ""again"". It is still giving me the error when I run. I tried this too</p>

<pre><code>assertEquals(""hellohello again\n"", outContent.toString());
</code></pre>

<p>How can I test System.out.println instead of System.out.print?</p>
",https://stackoverflow.com/questions/47144489/testing-system-out-println-not-working-but-system-out-print-using-junit,"['java', 'unit-testing', 'junit']",2079,TRUE,0,3
"PHPUnit, testing a method that uses class fields set according to current time","<p>I'm building a little Timer class that has a <code>start()</code> and <code>stop()</code> method, each of these will set a <strong>Carbon</strong> object with the current timestamp, then i have the method i'm trying to test, this method will calculate the difference between timestamps to get the total number of seconds elapsed in the Timer.</p>

<p>I'm having a problem unit testing this method, because it depends on the current timestamp, i don't think putting a <code>sleep(1)</code> in the test is a good idea, so, my question is, is there any way i can make the method use two other specific Carbon instances while it's running?</p>

<p>This is my method as it stands, it uses the two <strong>protected</strong> fields <code>endTime</code> and <code>startTime</code> from it's class.</p>

<pre><code>/**
 * Get the total elapsed time as the difference in seconds
 * between startTime and endTime
 *
 * @return int Number of seconds elapsed
 */
public function getElapsedTime()
{
    if(!$this-&gt;endTime)
        return $this-&gt;startTime-&gt;diffInSeconds(Carbon::now('Europe/Lisbon'));

    return $this-&gt;startTime-&gt;diffInSeconds($this-&gt;endTime);
}
</code></pre>
",https://stackoverflow.com/questions/41413073/phpunit-testing-a-method-that-uses-class-fields-set-according-to-current-time,"['php', 'laravel', 'phpunit']",132,FALSE,0,1
Angular component test with viewchild and directive,"<p>I made a plunker with my problem... <a href=""https://embed.plnkr.co/UparfJDomOECGJfWSbqA/"" rel=""nofollow noreferrer"">https://embed.plnkr.co/UparfJDomOECGJfWSbqA/</a>
Short: I am unable to test my component, it seems to fail in <code>container.component.spec.ts:43</code> - but without the <code>fixture.detectChanges()</code>, the <code>ngAfterViewInit</code> won't be started. I am unable to see what I am doing wrong.</p>

<p>I want to dynamically load a component into an ng-template with a directive attribute and the solution does work, but I am unable to write a working test for it.
Since I am pretty new to unit testing... Is that something I should even test - I think yes. (And yes I read the angular.io testing guide, and some others ;-) )
The error is <code>TypeError: Cannot read property 'viewContainerRef' of undefined</code> which seems to point that <code>@ViewChild</code> does not have a ViewChild...</p>
",https://stackoverflow.com/questions/45531089/angular-component-test-with-viewchild-and-directive,"['angular', 'testing']",4581,TRUE,0,1
RestTemplate.getForEntity will remove file extension?,"<p>Hi I am writing an application which enables user to upload a file then later download it. What I found is that the file extension will be removed from restTemplate.getForEntity thus RequestMapping will not get full file name. Can anybody confirm this is correct and how to overcome this?</p>

<p>Controller:</p>

<pre><code>@RequestMapping(value = ""/uploaded/{filename}"", method = RequestMethod.GET)
public ResponseEntity&lt;Resource&gt; getUploaded(@PathVariable String filename) {
    logger.debug(""getUploaded filename="" + filename);

    Resource file = storageService.loadAsResource(filename + "".png"");

    return ResponseEntity.ok().body(file);
}
</code></pre>

<p>Unit Testing:</p>

<pre><code>    System.err.println(""imageUpload = "" + imageUpload);
    ResponseEntity&lt;Resource&gt; responseResource = this.restTemplate.getForEntity(""/uploaded/"" + imageUpload, Resource.class);
    assertNotNull(responseResource);
    System.err.println(""responseResource = "" + responseResource.toString());
    assertEquals(HttpStatus.FOUND, responseResource.getStatusCode());
    assertEquals(resource, responseResource.getBody());
</code></pre>

<p>Logging show:</p>

<pre><code>imageUpload = favicon1.png
getUploaded filename=favicon1
responseResource = &lt;200 OK,Byte array resource [resource loaded from byte array],{Content-Type=[image/png], Content-Length=[8971], Date=[Mon, 02 Oct 2017 01:58:39 GMT]}&gt;
</code></pre>

<p>As you can see, imageUpload is a file name with '.png' extension and is correctly passed to restTemplate.getForEntity() but getUploaded() can only receive filename without extension thus I have to manually add '.png' which is ugly. So I don't know if there is anything wrong with my implementation or how anybody else solve this file extension problem which should be general.</p>
",https://stackoverflow.com/questions/46518663/resttemplate-getforentity-will-remove-file-extension,"['java', 'spring-boot', 'resttemplate']",183,TRUE,0,1
Unit test branch coverage of checked exceptions that should never throw,"<p>I have a situation where I'm fairly certain exceptions will not occur. However, due to the design of the APIs consumed, I must account for them anyway. In the unlikely case these exceptions are thrown, I will be throwing a RuntimeException that will bubble up to the UI. Here's a simple case:</p>

<pre><code>public class SomethingUsingJaxB{
   private JAXBContext jaxbContext;

   public SomethingUsingJaxB(){
      try{
          jaxbContext = JAXBContext.newInstance(Input.class);
      }catch(JAXBException e){
          throw new RuntimeException(e);
      }
   }

   public Output getOutput(Input input){
      //Do stuff with jaxbContext that also throws checked exceptions;
   }
}
</code></pre>

<p>In the full version of this class, I also have a <code>TransformerFactory</code>, <code>Templates</code>, and <code>DocumentBuilderFactory</code> which all throw checked exceptions, AND these factories return objects which themselves throw checked exceptions. I can't think of any situation where these exceptions are actually going to be thrown, but I'd like unit tests to account for them anyway.</p>

<p>Is there a ""clean"" way of unit testing these that doesn't heavily involve mocking frameworks? </p>
",https://stackoverflow.com/questions/42119583/unit-test-branch-coverage-of-checked-exceptions-that-should-never-throw,"['java', 'unit-testing']",342,FALSE,0,0
ReactJS: How to test a component function?,"<p>In my meteor application I'm doing some unit testing by testing all methods I'm using. I'm doing the test (mocha/chai) like this:</p>

<pre><code>describe('postMessage', () =&gt; {
  it('should add message', (done) =&gt; {
    // EXECUTE
    const messageId = postMessage.call({ articleId: 123, content: 'Message text' })
    // VERIFY
    const message = Messenger.findOne(messageId) // get data from mongoDB
    expect(message.content).to.equal('Message text') // check for message
    expect(message.articleId).to.be.equal(123) // check for articleId
    done()
  })
})
</code></pre>

<p>But with this only a part is tested, which is storing the message to DB. But I also have to test if writing a message and submitting it (blur event) will call this method.</p>

<p>This is how my component looks like. I need to know how to do a test for this component. So in this example I need to test if the method <code>postMessage</code> is called on blur event of the textarea element and if the state value for <code>result</code> gets the ID. How do I do that?</p>

<p><strong>Component</strong></p>

<pre><code>class Message extends Component {
  addPost (articleId, event) {
    const content = event.target.value
    postMessage.call(
      { content, articleId },
      (error, result) =&gt; {
        if (error) console.warn(error)
        if (result) this.setState({ result })
      }
    )
  }

  render () {
    return (
      &lt;Form&gt;
        &lt;TextArea onBlur={this.addPost.bind(this, articleId)} /&gt;
      &lt;/Form&gt;
    )
  }
}
</code></pre>

<p><strong>Method</strong></p>

<pre><code>const postMessage = new ValidatedMethod({
  name: 'messenger.insert',
  validate: null,
  run ({ articleId, content }) {
    return Communicator.insert({ content, articleId })
  }
})
</code></pre>
",https://stackoverflow.com/questions/45597172/reactjs-how-to-test-a-component-function,"['javascript', 'reactjs', 'unit-testing', 'meteor', 'chai']",112,TRUE,0,2
Losing class context when chaining promises,"<p>Suggested duplicate does not sufficiently serve as an answer. <a href=""https://stackoverflow.com/questions/38334062/why-do-you-need-to-bind-a-function-in-a-constructor"">link</a> is better answer. And matches @deceze reply</p>

<hr>

<p>I'm a convert to node from .net. Thus I'm loving the syntactic sugar provided by es6. I have run myself into a scoping problem during one of my complexity refactors. </p>

<p>I return my promises from inside classes. I refactored a little of <code>PolicyMapper.mapDao()</code> code into another class function (<code>mapJSONtoDAO</code>). Unit testing has no problem with this. The problem occurs during chaining with other promises. <code>this.mapJSONtoDAO()</code> becomes undefined. </p>

<p>route.js -></p>

<pre><code>const policyService = new PolicyService();
const policyMapper = new PolicyMapper();
const policyMapPromise = policyService.getPolicy(req.body.policyNumber, office)
    .then(policyMapper.mapDao, next);
</code></pre>

<p>PolicyMapper class -></p>

<pre><code>class PolicyMapper {
    mapDao(soapResponse) {
        return new Promise((resolve, reject) =&gt; {

            xml2js.parseString(soapResponse[config.responseProperty], {}, (error, json) =&gt; {
                resolve(this.mapJSONtoDAO(json));
            });
        });
    }

    mapJSONtoDAO(json) {
        let policyDAO = new PolicyDAO();
        policyDAO.givenName = json[""policy-response""][""given-name""]
        return policyDAO;
    }
}
</code></pre>

<hr>

<p>The below refactor of the route.js protects scope association between  class and promise. Is there an simplier way to inplement this. I really want my code to be simple for any engineer maintaining my code.</p>

<pre><code>const policyService = new PolicyService();
const policyMapper = new PolicyMapper();
const policyMapPromise = policyService.getPolicy(req.body.policyNumber, office)
    .then((soapResponse) =&gt; {
        return policyMapper.mapDao(soapResponse)
    }, next);
</code></pre>
",https://stackoverflow.com/questions/41979519/losing-class-context-when-chaining-promises,"['javascript', 'node.js', 'ecmascript-6', 'this', 'es6-promise']",34,FALSE,0,0
Generate html binding template for angular directive from javascript,"<p>I have written several unit tests recenlty and I wonder if there is a way to make html string (binding template) that appeals to directive (or component) from javascript function. Here is an example.</p>

<p>I have some directive and I'm testing it like this </p>

<pre><code>function test($rootScope, $compile) {
    var scope = $rootScope.$new();
    var elem = $compile(angular.element(
        '&lt;app-foo-bar attr1=""val1"" attr2=""val2""&gt;&lt;/app-foo-bar&gt;'
    ))(scope);
    scope.$apply();
}
</code></pre>

<p>Declaring an element string seems to be a little awkward especially if there is a dozen of attributes. It would be very handul for unit-testing if there is a function that generates html string from object like this.</p>

<pre><code>genHtmlString('fooBar', {
    attr1: 'val1',
    attr2: 'val2'
});
</code></pre>

<p>And output would be of course</p>

<pre><code>&lt;app-foo-bar attr1=""val1"" attr2=""val2""&gt;&lt;/app-foo-bar&gt;
</code></pre>

<p>It seems like a common problem to me, but I can't find any angular, karma or jasmine functionality that would be helpful in writing such a function.</p>
",https://stackoverflow.com/questions/43876012/generate-html-binding-template-for-angular-directive-from-javascript,"['javascript', 'angularjs', 'angularjs-directive', 'jasmine', 'karma-runner']",94,TRUE,0,1
No provider for Platform,"<p>So I have come across this issue making a unit test for an Angular 4 application </p>

<p>What happens is that it keeps giving the error stated here in the question title.</p>

<p>I tried to google it, tried to import a whole bunch of different modules and finally found that a close answer to what this ""Platform"" is might be the browserModule from <code>@angular/browser</code> Platform.</p>

<p>So in my unit testing, I tried to import it and declare it but it did not help.</p>

<p>Can anyone please help with this as I'm not even sure what this ""Platform"" is?</p>

<p>Question: what is exactly this ""Platform"" in the error and how to fix it?</p>

<p>Thanks.</p>

<p>I have attached my code as below:</p>

<pre><code>import { ComponentFixture, TestBed, async} from ""@angular/core/testing"";
import { DebugElement, CUSTOM_ELEMENTS_SCHEMA, PlatformRef} from 
""@angular/core"";
import { TeamCreationAssignmentComponent } from ""./team-creation-assignment.component"";
import { OdmService } from ""../../services/odm/odm.service"";
import { UserNotificationService } from ""../../services/user/user-notification.service"";
import { MatSnackBar } from ""@angular/material"";
import { OVERLAY_PROVIDERS, ScrollStrategyOptions, ScrollDispatcher} from ""@angular/cdk/overlay"";

describe('Team creation assignment component', () =&gt; {
let comp: TeamCreationAssignmentComponent;
let fixture: ComponentFixture&lt;TeamCreationAssignmentComponent&gt;;

let odmServiceSub = {};


beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({

        declarations: [TeamCreationAssignmentComponent],
        //imports: [BrowserModule],
        schemas: [CUSTOM_ELEMENTS_SCHEMA],
        providers: [
            {provide: OdmService, useValue: odmServiceSub}, 
            UserNotificationService, 
            MatSnackBar, 
            OVERLAY_PROVIDERS, 
            ScrollStrategyOptions,
            ScrollDispatcher,
        ],
    })
    .compileComponents();
}));

beforeEach(() =&gt; {
    fixture = TestBed.createComponent(TeamCreationAssignmentComponent);
    comp = fixture.componentInstance;
});

it('should have defined component', () =&gt; {
    expect(comp).toBeDefined();
})
</code></pre>

<p>});</p>
",https://stackoverflow.com/questions/47345175/no-provider-for-platform,"['javascript', 'angular', 'angular-material', 'angular-cdk']",2749,TRUE,0,2
How to create `ExpressionType.IsTrue/IsFalse`?,"<h1>TL;DR</h1>

<p>How do you create an <code>Expression</code> where </p>

<pre><code>Expression.NodeType == ExpresionType.IsTrue || ExpresionType.IsFalse
</code></pre>

<h2>Background Info</h2>

<p>I am creating a custom version of EnumerableQuery, where I rewrite all expressions to handle Null checking. So that when unit testing EF Linq2Sql code as Linq2Objects, accessed <code>null</code> navigation properties do not throw an exception, but instead handle it gracefully.</p>

<p>I am trying to implement tests for all <code>ExpressionType</code> members. How can I create a expression syntax to create <code>ExpressionType.IsTrue</code> and <code>ExpressionType.IsFalse</code> node.</p>

<p><a href=""https://github.com/michal-ciechan/Moqqer"" rel=""nofollow noreferrer"">Github Project: Moqqer</a></p>

<h2>Attempt 1. x => x</h2>

<p><code>Where</code> clause:</p>

<pre><code>queryable.Where(x =&gt; x.L1.L2.L3.L4.L5.Boolean);
</code></pre>

<p>returns</p>

<pre><code>ExpressionType.MemberAccess
</code></pre>

<h2>Attempt 2. x => !(x &amp;&amp; y)</h2>

<p>The following <code>Where</code> clause:</p>

<pre><code>queryable.Where(x =&gt; !(x.L1.L2.L3.L4.L5.Boolean &amp;&amp; x.L1.L2.L3.L4.L5.Boolean));
</code></pre>

<p>returns</p>

<pre><code>ExpressionType.Not
     ExpressionType.AndAlso
         Left = ExpressionType.MemberAccess
         Right = ExpressionType.MemberAccess
</code></pre>

<h2>Attempt 3. x => true</h2>

<p><code>Where</code> clause</p>

<pre><code>queryable.Where(x =&gt; true);
</code></pre>

<p>returns</p>

<pre><code>ExpressionType.Constant
</code></pre>

<h1>Comments</h1>

<p>I am guessing these <code>ExpressionType</code>'s are only used when manually creating expression trees, and want to return an expresison similar to <code>ExpressionType.Constant(true)</code> but with less overhead?</p>
",https://stackoverflow.com/questions/42875376/how-to-create-expressiontype-istrue-isfalse,"['c#', '.net', 'compilation', 'expression', 'linq-expressions']",864,TRUE,5,1
Coffeescript create new instance of a class given an object of that class,"<p>In coffeescript, I have an object created from a class.  Later, I no longer have access to that class, but I would like to create a new instance.  For example:</p>

<pre><code># MySingleton.coffee

class MySingleton
module.exports = new MySingleton
</code></pre>

<p>and then:</p>

<pre><code># MySingletonTests.coffee

mySingleton = require './MySingleton'

# testSingleton = ???
# I would like to create a new MySingleton here
</code></pre>

<p>I think I would like to use something like JS's Object.create here, but if I call <code>Object.create(mySingleton)</code> it seems to just make a reference to the old object, and <code>mySingleton.prototype</code> is <code>undefined</code></p>

<p><strong>EDIT</strong>:
I know I could just export the class in this example, but I was hoping not to because it is a singleton in production code and I would like to make sure it doesn't get new'd, but in my unit testing I would like to make new copies of it so state doesn't persist between tests</p>
",https://stackoverflow.com/questions/44850363/coffeescript-create-new-instance-of-a-class-given-an-object-of-that-class,"['javascript', 'coffeescript']",186,TRUE,0,1
Is adding too many stubbed methods a reason for adding special constructor just for tests? (over mocking),"<p>I want to add unit tests for a method in class <code>ClassToBeTested.execute()</code>. <code>ClassToBeTested</code> is a business model class received from REST api. To call that method I have to:</p>

<ul>
<li>create a class <code>AAAclass</code> (which must have 2 inner class mocked and stub 7 methods to put call the method I want to test)</li>
<li>put that mocked <code>AAAclass</code> in <code>ClassToBeTested</code>; <code>ClassToBeTested</code> depends on <code>AAAclass</code></li>
</ul>

<p>The <code>AAAclass</code> looks like:</p>

<pre><code>    public class AAAclass {
        @SerializedName(""BBBclass"")
        private BBBclass BBBclass;

        public class BBBclass {
            @SerializedName(""CCCclass"")
            private CCCclass ccc;

            public DDDclass getDDD() {
                if (ccc != null) {
                    return ccc.getDDD();
                }
                return null;
            }
        }

        private class CCCclass {
            @SerializedName(""DDDclass"")
            private DDDclass ddd;

            public DDDclass getDDD() {
                return ddd;
            }
        }

        public class DDDclass {
        }
    }
</code></pre>

<p>I got the feeling that I'm doing sth wrong and it seems to be <a href=""https://mestachs.wordpress.com/2012/07/09/mockito-best-practices/"" rel=""nofollow noreferrer"">over mocking</a>:</p>

<blockquote>
  <p>Don’t mock your model: Easier to read and you will may be add convenient constructor/factory methods to your production or test codebase.</p>
</blockquote>

<p>So should I really add a special constructor just to use it in unit testing?</p>
",https://stackoverflow.com/questions/42698064/is-adding-too-many-stubbed-methods-a-reason-for-adding-special-constructor-just,"['java', 'android', 'unit-testing', 'mocking', 'mockito']",70,FALSE,0,1
Can not instantiate proxy of class x - Could not find parameterless constructor,"<p>So I'm trying to implement unit testing into my application and I am trying to mock a number of my constructor arguments to pass through. I've read on here that you are not supposed to Mock a class and instead Mock an interface but I've also read that there isn't much point in implementing an <a href=""http://blog.karumi.com/interfaces-for-presenters-in-mvp-are-a-waste-of-time/"" rel=""nofollow noreferrer"">interface</a> for a presenter when implementing the MVP approach.</p>

<p>I've been told that you can pass in the parameters into a constructor by using this line, this is also the line where the error is thrown:</p>

<pre><code>               var p = new ImpositionCalculatorPresenter(mockView.Object, mockImpositionCalculatorManager.Object, mockSystemVariablesManager.Object,
    mockSystemVariablesPresenter.Object, mockPrintingDesignManager.Object);
</code></pre>

<p>Can anyone help me implement a way of passing in the arguments into my constructor when Mocking my presenter?</p>

<pre><code>   [TestMethod]
        public void CalculateFinalImpositionPlates() {
            //Need to pass in the managers for dependency injection.
            //Then I need to find a way which will trigger the event to call the method on the presenter
            //Then do my tests
            var mockView = new Mock&lt;IImpositionFormView&gt;();

            mockView.SetupProperty(r =&gt; r.FinalImpositionOut, 0);

            //These may have to be manually mocked by me so they don't affect JSON file
            var mockImpositionCalculatorManager = new Mock&lt;IImpositionCalculatorManager&gt;();
            var mockSystemVariablesManager = new Mock&lt;ISystemVariablesManager&gt;();
            var mockSystemVariablesPresenter = new Mock&lt;SystemVariablesPresenter&gt;();
            var mockPrintingDesignManager = new Mock&lt;IPrintingDesignManager&gt;();


            //Fix error allowing me to pass in objects to the contstructor
                   var p = new ImpositionCalculatorPresenter(mockView.Object, mockImpositionCalculatorManager.Object, mockSystemVariablesManager.Object,
        mockSystemVariablesPresenter.Object, mockPrintingDesignManager.Object);

    mockView.SetupProperty(r =&gt; r.Presenter == p);

            mockView.Raise(r =&gt; r.CalculateFinalImpositionPlates += null);

            Assert.Equals(mockView.Object.Plates, 0);

        }
</code></pre>

<p>Part of my presenter:</p>

<pre><code>public class ImpositionCalculatorPresenter {
    private readonly IImpositionCalculatorManager _impostionFormManager;
    private readonly ISystemVariablesManager _systemVariablesManager;
    private readonly SystemVariablesPresenter _systemVariablesFormPresenter;
    private readonly IPrintingDesignManager _printingDesignManager;
    private readonly string _pathToAppSettings = $""{AppDomain.CurrentDomain.BaseDirectory}/PrintAppSettings.txt"";
    private PagePrintingDesignParameters _printingAppParameters;
    private readonly IImpositionFormView _view;

    public ImpositionCalculatorPresenter(IImpositionFormView View, IImpositionCalculatorManager impositionFormManager,
        ISystemVariablesManager systemVariablesManager, SystemVariablesPresenter systemVariablesFormPresenter, IPrintingDesignManager printingDesignManager) {
        _view = View;
        _impostionFormManager = impositionFormManager;
        _systemVariablesManager = systemVariablesManager;
        _systemVariablesFormPresenter = systemVariablesFormPresenter;
        _printingDesignManager = printingDesignManager;
        InitialiseEvents();
    }
    private void InitialiseEvents() {

        _view.CalculateFinalImpositionPlates += CalculateFinalImpositionPlates;


    }

    private void CalculateFinalImpositionPlates(object sender, EventArgs e) {
        //if sheet fed checked, and sheetwise not selected in drop down and sheetsize irregular not select in drop down
        try {
            if (_view.FinalImpositionOut != 0) {
                if (_view.OverridePlates != 0) {
                    _view.Plates = _view.OverridePlates;
                }
                else if (_view.PrintingStyleChecked == PrintingStyle.SheetFed &amp;&amp; (_view.CboImposition != ""Sheetwise"" || _view.CboImposition != ""Irregular S\\Wise"")) {
                    _view.Plates = _view.ColourSideOne;
                }
                else if (_view.ColourSideOne != 0 &amp;&amp; _view.ColourSideTwo != 0) {
                    _view.Plates = _view.ColourSideOne + _view.ColourSideTwo;
                }
            }
        }
        catch (Exception ex) {
            LogErrorToView(this, new ErrorEventArgs(ex.Message));
        }
    }
    }
</code></pre>
",https://stackoverflow.com/questions/44231162/can-not-instantiate-proxy-of-class-x-could-not-find-parameterless-constructor,"['c#', 'unit-testing', 'moq', 'mvp']",1505,FALSE,0,0
Return data null when unit test the service using Moq,"<p>I am having a problem when using the Moq for unit testing the a function which accepts number of parameters. I did the bellow steps to moq the service. </p>

<ol>
<li><p>Created a mock object to interface. the relevant method in the interface contains four arguments namely int type, a collection and a object. so i initailized the variable needed for those first,</p></li>
<li><p>Then setup the mock object to return a a predefined type of object.</p></li>
<li><p>After that the relevant method in the service class is called with the required arguments the method does not return the object that it is supposed to return (moq object) but it rather returns a null object.</p></li>
</ol>

<p>Am I missing anything in the code bellow? </p>

<pre><code> Collection&lt;MyDocumentSample spec = new Collection&lt;MyDocumentSample()
 { 
  new MyIdSample() { SampleID = 1234 } };
  int index = 0;
  int maxNoOfRows = 2;
  MyDocumentListSortFields sortFeild = new
  MyDocumentListSortFields() 
  { 
       Descending = false, 
       SortField = MyDocumentListSortFields.SortFields.Date 
  };


var bundleOfObjects = new bundleOfObjects { Entry = new List&lt;bundleOfObjects.EntryComponent() };

MySampleDocument resource_1 = new MySampleDocument();
resource_1.Id = ""1005823"";
resource_1.Description = ""Test 1"";
resource_1.Created = ""11/20/2017 12:59:47 PM"";


bundleOfObjects.AddTobundleOfObjects(resource_1, null);
var m_documentWrapperHelperMock = new Mock&lt;IDocumentSampleHelper();
var m_configMock = new Mock&lt;IConfiguration();

m_documentWrapperHelperMock.Setup(x =&gt; x.GetSampleDocumentsWithOffSets(spec, index, maxNoOfRows, sortFeild)).Returns(bundleOfObjects);


var service = new MySampleDocumentService(m_configMock.Object, m_documentWrapperHelperMock.Object);
</code></pre>
",https://stackoverflow.com/questions/48006259/return-data-null-when-unit-test-the-service-using-moq,"['c#', 'unit-testing', 'testing', 'moq']",2258,TRUE,-1,1
how to use chutzpah in current project,"<p>I am going through setting up chutzpah and Jasmine for unit testing my project in typescript.</p>

<p>I have installed Jasmine using npm but I am quite confused how to include chutzpah in visual studio code.</p>

<p>I went to this GitHub but nothing is clear to me:-</p>

<p><a href=""https://github.com/mmanela/chutzpah"" rel=""nofollow noreferrer"">https://github.com/mmanela/chutzpah</a></p>

<p>Also, I downloaded files for visual studio code from below sources:-</p>

<p><a href=""https://marketplace.visualstudio.com/items?itemName=vs-publisher-2795.ChutzpahTestRunnerContextMenuExtension"" rel=""nofollow noreferrer"">https://marketplace.visualstudio.com/items?itemName=vs-publisher-2795.ChutzpahTestRunnerContextMenuExtension</a></p>

<p><a href=""https://marketplace.visualstudio.com/items?itemName=vs-publisher-2795.ChutzpahTestAdapterfortheTestExplorer"" rel=""nofollow noreferrer"">https://marketplace.visualstudio.com/items?itemName=vs-publisher-2795.ChutzpahTestAdapterfortheTestExplorer</a></p>

<p>When I try to load above-downloaded files as an extension in visual code I get the error:-</p>

<p>extension/package.json not found inside zip.</p>

<p>How to include or install chutzpah in my project and then use the chutzpah.json file?</p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/45959538/how-to-use-chutzpah-in-current-project,"['node.js', 'visual-studio', 'typescript', 'visual-studio-2012']",524,TRUE,0,1
Create Directory For Test Unit C++ [Code::Blocks],"<p>Currently i am about finishing my school project, however the last thing need to be done are documentation. i am getting confuse about unit Testing, basically what i know is, i need a <code>testfile.cpp</code> for every class i created.  but i dont know where to put the file since my tutor told me to have a <code>main()</code> inside the <code>testfile.cpp</code> but isn't a project can only have one <code>main()</code> ?? </p>

<p>Are there any possible way i can create a new folder and name it TestingFolder for example, and then put the <code>testfile.cpp</code> inside but still can be executed to proof.</p>

<p>Please Comment if any of the question are not clear, i am new to C++ and Documentation, apologize.</p>
",https://stackoverflow.com/questions/46992420/create-directory-for-test-unit-c-codeblocks,"['c++', 'codeblocks']",216,FALSE,0,1
Mocking external library in PHP/Codeigniter,"<p>Using the <a href=""https://github.com/kenjis/ci-phpunit-test"" rel=""nofollow noreferrer"">ci-php-unit-test</a> library to do unit tests for PHP/codeigniter, and unit testing controller methods.</p>

<p>Having trouble working out how to mock an external library that is installed using composer.</p>

<p>my SUT method is:</p>

<pre><code>function twitter()
{
    $this-&gt;load-&gt;model('misc/twitter_model');
    $request_token = [];

    $request_token['oauth_token'] = $_SESSION['twitter_oauth_token'];
    $request_token['oauth_token_secret'] = $_SESSION['twitter_oauth_token_secret'];
    if ( (isset($_GET['oauth_token']) 
        &amp;&amp; ($request_token['oauth_token'] !== $_GET['oauth_token'])))
    {
        log_message('info','abort something is wrong!');
    }
    else
    {
        $connection = new Abraham\TwitterOAuth\TwitterOAuth(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, $request_token['oauth_token'], $request_token['oauth_token_secret']);
        $access_token = $connection-&gt;oauth(""oauth/access_token"", array(""oauth_verifier"" =&gt; $_REQUEST['oauth_verifier']));
        $this-&gt;session-&gt;set_userdata('twitter_access_token',$access_token);
        redirect(get_session('twitter_callback1'));
    }
}
</code></pre>

<p>my test method (so far) is:</p>

<pre><code>public function test_twitter()
{
    $_SESSION['twitter_oauth_token'] = 'twitter_oauth_token';
    $_SESSION['twitter_oauth_token_secret'] = 'twitter_oauth_token_secret';

    $this-&gt;request-&gt;setCallable(
        function (&amp; $CI) {
            // Get mock object
            $twitter_oa = $this-&gt;getMockBuilder('TwitterOAuth')
                -&gt;disableOriginalConstructor()
                -&gt;setMethods(['oauth'])
                -&gt;getMock();
            $twitter_oa-&gt;method('oauth')
                 -&gt;willReturn('access_token');
        }
    );
    $output = $this-&gt;request('GET','callbacks/twitter',['oauth_token'=&gt;'twitter_oauth_token']);
    var_export($output);
}
</code></pre>

<p>But the original library is being executed because it isn't being mocked - the <code>$twitter_oa</code> isn't being attached to the CI instance.</p>

<p>This is because the external library has not been instantiated after the codeigniter controller has been instantiated. (this is was the setCallable method does)</p>

<p>My question is, how can I mock TwitterOAuth after the codeigniter controller is instantiated so it can return set testing text?
 (and obviously not instantiate the twitter Oauth library)</p>
",https://stackoverflow.com/questions/44611143/mocking-external-library-in-php-codeigniter,"['php', 'codeigniter', 'unit-testing', 'phpunit']",1100,FALSE,0,1
incompatible return value type,"<p>I am new to unit testing, Recently I used profiler to populate different metrics depending on different conditions using if-else statements. I have written a unit test to check if the right metrics is getting populated. However I m getting a <code>Incompatible return value type</code> error. The code snippet is as follows:</p>

<pre><code>ProfilerObject1 mockObject = ctrl.createMock(ProfilerObject1.class);
EasyMock.expect(ProfilerObject2.func1()).andReturn(mockObject);
PopulateMetric(m1);
EasyMock.expectLastCall().once();
control.replay();
</code></pre>

<p>I m getting the incompatible return value error on line 2(EasyMock.expect call), whereas the function returns the object of type ProfilerObject1. I have no clue on why I m getting this error. </p>

<p>Any help would really be appreciated. TIA</p>

<p>PS: I m using this snippet at 2 separate places and at the 2nd place it gives <code>no last call on mock available</code> error. Which confuses me even more. </p>
",https://stackoverflow.com/questions/42517866/incompatible-return-value-type,"['java', 'unit-testing', 'profiler', 'easymock']",2609,FALSE,0,1
What is the correct way to unit test a function or method that writes to an encrypted wallet file?,"<p>My code looks somewhat like this:</p>

<pre><code>def write_wallet_file_entry(name, value, wallet_file, wallet_password):
    some_code
    some_more_code_to_write_to_the_wallet
    ...
</code></pre>

<p>I am using Python (2.6) and using unittest module for unit  testing this code. Code creates the wallet file, if it does not exist and then writes a bunch of key value pairs to it.</p>

<p>Once I write to the wallet, there is no text parsing I can do to confirm that the write was clean. </p>

<p>CLARIFICATION: Stating the NOT SO obvious: I cannot use ""unittest.mock"" or ""mock"" module which would have made the problem simpler to solve. My environment  is stuck on python 2.6, does not have ""virtualenv"", does not have ""mock"" module and does not allow installation of external modules on the system.</p>

<p>Any suggestions would be really helpful.</p>
",https://stackoverflow.com/questions/44406080/what-is-the-correct-way-to-unit-test-a-function-or-method-that-writes-to-an-encr,"['python', 'unit-testing', 'wallet']",169,TRUE,0,1
Mocking Files In Python Unittest In Imported Modules,"<p>I readily admit to going a bit overboard with unit testing. 
While I have passing tests, I find my solution to be inelegant, and I'm curious if anyone has a cleaner solution.</p>

<p>The class being tested:</p>

<pre><code>class Config():

    def __init__(self):
        config_parser = ConfigParser()
        try:
            self._read_config_file(config_parser)
        except FileNotFoundError as e:
            pass

        self.token = config_parser.get('Tokens', 'Token', )

    @staticmethod
    def _read_config_file(config):
        if not config.read(os.path.abspath(os.path.join(BASE_DIR, ROOT_DIR, CONFIG_FILE))):
            raise FileNotFoundError(f'File {CONFIG_FILE} not found at path {BASE_DIR}{ROOT_DIR}')
</code></pre>

<p>The ugly test:</p>

<pre><code>class TestConfiguration(unittest.TestCase):

    @mock.patch('config.os.path.abspath')
    def test_config_init_sets_token(self, mockFilePath: mock.MagicMock):
        with open('mock_file.ini', 'w') as file: #here's where it gets ugly
            file.write('[Tokens]\nToken: token')
        mockFilePath.return_value = 'mock_file.ini'

        config = Config()

        self.assertEqual(config.token, 'token')
        os.remove('mock_file.ini') #quite ugly
</code></pre>

<p>EDIT: What I mean is I'm creating a file instead of mocking one. 
Does anyone know how to <code>mock</code> a file object, while having its data set so that it reads ascii text? The class is deeply buried.
Other than that, the way <code>ConfigParser</code> sets data with <code>.read()</code> is throwing me off. Granted, the test ""works"", it doesn't do it nicely. </p>

<p>For those asking about other testing behaviors, here's an example of another test in this class:</p>

<pre><code>@mock.patch('config.os.path.abspath')
def test_warning_when_file_not_found(self, mockFilePath: mock.MagicMock):
    mockFilePath.return_value = 'mock_no_file.ini'

    with self.assertRaises(FileNotFoundError):
        config.Config._read_config_file(ConfigParser())
</code></pre>

<p>Thank you for your time.</p>
",https://stackoverflow.com/questions/46104585/mocking-files-in-python-unittest-in-imported-modules,"['python', 'python-unittest', 'configparser', 'python-mock']",2818,TRUE,0,1
Code coverage analysis for controller test classes,"<p>I would like to know if there were any tools that offer a code coverage analysis for tests classes that test controller. I know there is some for unit testing, but thats not quite what I am looking for.</p>

<p>I am working on a Symfony2 project with a lot of controllers in it, and I wrote some tests to check their behaviour, so now I would like to know how complete they are.</p>

<p>Thanks.</p>

<p>P.S. : Here is an example of what one of my of my tests can looks like </p>

<pre><code>public function testSample() {

        $client = $this-&gt;createAuthenticatedClient($this-&gt;getReference('admin-0')) ;
        $client-&gt;followRedirects() ;
        $crawler = $client-&gt;request(""GET"", ""/config/database/"");
        $this-&gt;assertStatusCode(200, $client);

}
</code></pre>

<p>As you can see, I dont really test my User class, but rather its behaviour depending of its creditential (in this case, an admin)</p>
",https://stackoverflow.com/questions/41680532/code-coverage-analysis-for-controller-test-classes,"['php', 'symfony', 'testing']",859,TRUE,0,2
Instrumented Unit Class Test - Can&#39;t create handler inside thread that has not called Looper.prepare(),"<p>Sorry I've looked at tutorials all over the place and not found the answer I'm looking for. I'm following Google's Tutorial at the moment here: <a href=""https://developer.android.com/training/testing/unit-testing/instrumented-unit-tests.html"" rel=""noreferrer"">https://developer.android.com/training/testing/unit-testing/instrumented-unit-tests.html</a></p>

<p>I'm trying to create an Instrumented test and when I run it I'm getting the error : <code>java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()</code></p>

<p>So my test is as follows:</p>

<pre><code>    package testapp.silencertestapp;

import android.support.test.filters.SmallTest;
import android.support.test.runner.AndroidJUnit4;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

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

    private MainActivity testMain;

    @Before
    public void createActivity(){
        testMain = new MainActivity();
    }

    @Test
    public void checkFancyStuff(){
        String time = testMain.createFancyTime(735);

        assertThat(time, is(""07:35""));
    }
}
</code></pre>

<p>And I'm trying to run a method inside the main activity is as follows (this is an extract):</p>

<pre><code>public class MainActivity extends AppCompatActivity {

    private TimePicker start;
    private TimePicker end;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        start = (TimePicker) findViewById(R.id.startPicker);
        end = (TimePicker) findViewById(R.id.endPicker);
}

 String createFancyTime(int combinedTime) {

        StringBuilder tempString = new StringBuilder(Integer.toString(combinedTime));
        if(tempString.length()==4){
            tempString = tempString.insert(2, "":"");
        }
        else if (tempString.length()==3){
            tempString = tempString.insert(1, "":"");
            tempString = tempString.insert(0, ""0"");
        }
        else if(tempString.length()==2){
            tempString = tempString.insert(0, ""00:"");
        }
        else if(tempString.length()==1){
            tempString = tempString.insert(0, ""00:0"");
        }
        return tempString.toString();
    }
</code></pre>

<p>I presume that this is an issue because I'm not starting the service up correctly or something - I've tried using several ways, but I just get errors everywhere. Searching on here and this error is popular, but not in relation to testing, so wondered if anyone could kindly point me in the right direction so I can test the methods in this class?</p>
",https://stackoverflow.com/questions/46458735/instrumented-unit-class-test-cant-create-handler-inside-thread-that-has-not-c,"['java', 'android', 'testing', 'junit']",8743,TRUE,14,2
Unit test is failing because mock data created in constructors differs from raw mock data,"<p>I'm just starting to learn unit testing and I have written the following test</p>

<pre><code>const EXEPECTED: MergedFood = {
    id: '1',
    name: 'test mergedFood',
    ingredients: {
        '2': {
            foodID: '2'
        }
    }
}
describe('addIngredientToMergedFood()', () =&gt; {
    it('should add an ingredient to a mergedFood', () =&gt; {
        const mergedFood: MergedFood = new MergedFood('1', 'test mergedFood');
        const ingredient: Ingredient = new Ingredient('2')
        const result: MergedFood = addIngredientToMergedFood(ingredient, mergedFood);
        expect(result).toEqual(EXEPECTED);
    })
})
</code></pre>

<p>This is failing and I'm getting the following failure error:</p>

<blockquote>
  <p>Expected MergedFood({ id: '1', name: 'test mergedFood', ingredients: Object({ 2: Ingredient({ foodID: '2' }) }) }) to equal Object({ id: '1', name: 'test mergedFood', ingredients: Object({ 2: Object({ foodID: '2' }) }) })</p>
</blockquote>

<p>As I hope you can easily see, the values and structure are equal, but the <code>result</code> has a <code>MergedFood</code> and <code>Ingredient</code> wrapper (I assume because they were created via constructor).</p>

<p>So my question is, <strong>how is this situation typically handled?</strong> Is it common to mock out all data rather than by using constructors (seems like a lot of work) OR is there a way to strip the wrappers?</p>
",https://stackoverflow.com/questions/42170833/unit-test-is-failing-because-mock-data-created-in-constructors-differs-from-raw,"['unit-testing', 'typescript', 'jasmine']",30,FALSE,0,1
Which way I should use to do unit test in Intellij IDEA?,"<p>I had read <a href=""https://stackoverflow.com/questions/4757800/configuring-intellij-idea-for-unit-testing-with-junit"">Configuring IntelliJ IDEA for unit testing with JUnit</a>, but it can't solve my problem.Here is my problem.</p>

<p>I use IntelliJ IDEA for Spring Boot Project,now I want to do some unit tests.So firstly I add junit dependency in my pom file.</p>

<pre><code>&lt;dependency&gt;
        &lt;groupId&gt;junit&lt;/groupId&gt;
        &lt;artifactId&gt;junit&lt;/artifactId&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
</code></pre>

<p>And next step, I install the JunitGenerator V2.0 plugin.
And then,it seems that there are two ways that I can choose to generate test file.One of them is using Alt + Insert in class file and choosing Junit Test to generate test file.And the other is using Ctrl + Shift + T or Alt + Enter to generate test file.</p>

<p>My problem is, what's different between them?And which way I should choose?</p>
",https://stackoverflow.com/questions/43778788/which-way-i-should-use-to-do-unit-test-in-intellij-idea,"['java', 'unit-testing', 'intellij-idea', 'junit']",325,FALSE,0,0
How to use Saxon with Wildfly properly?,"<p>I have an issue with Saxon and WildFly 10.0.0.Final. I wrote some XSLTs and they work properly when I'm running unit tests but I get the issue when I run the same code on Wildfly.</p>

<p>In my pom.xml I have dependency like this:</p>

<pre><code> &lt;dependency&gt;
    &lt;groupId&gt;net.sf.saxon&lt;/groupId&gt;
    &lt;artifactId&gt;Saxon-HE&lt;/artifactId&gt;
    &lt;version&gt;9.8.0-4&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>

<p>I tried few version of Saxon and even I exchanged it for Xalan but still I'm getting the same issue. It works in unit testing but never with Wildfly. The problem is that ""Wildfly case"" simply ignore some parts of XSLT. For example this part is ignored:</p>

<pre><code>&lt;xsl:for-each select=""$var33_Tracking/ns0:PartyIdentification/ns0:Location""&gt;
   &lt;xsl:variable name=""var13_LatLong"" as=""node()"" select=""ns0:LatLong""/&gt;
   &lt;xsl:variable name=""var12_cur_as_string"" as=""xs:string"" select=""fn:string($var13_LatLong)""/&gt;
   &lt;xsl:variable name=""var14_result"" as=""xs:string?""&gt;
      &lt;xsl:choose&gt;
         &lt;xsl:when test=""(fn:string(fn:string-length($var12_cur_as_string)) &amp;gt; '0')""&gt;
            &lt;xsl:sequence select=""$var12_cur_as_string""/&gt;
         &lt;/xsl:when&gt;
         &lt;xsl:otherwise&gt;
            &lt;xsl:for-each select=""ns0:GeoLoc""&gt;
               &lt;xsl:sequence select=""fn:string(.)""/&gt;
            &lt;/xsl:for-each&gt;
         &lt;/xsl:otherwise&gt;
      &lt;/xsl:choose&gt;
   &lt;/xsl:variable&gt;
   &lt;xsl:for-each select=""$var14_result""&gt;
      &lt;LatitudinalHemisphere&gt;
         &lt;xsl:choose&gt;
            &lt;xsl:when test=""(fn:substring-before(., ',') &amp;lt; '0')""&gt;
               &lt;xsl:sequence select=""'S'""/&gt;
            &lt;/xsl:when&gt;
            &lt;xsl:otherwise&gt;
               &lt;xsl:sequence select=""'N'""/&gt;
            &lt;/xsl:otherwise&gt;
         &lt;/xsl:choose&gt;
      &lt;/LatitudinalHemisphere&gt;
   &lt;/xsl:for-each&gt;
&lt;/xsl:for-each&gt;
</code></pre>

<p>It looks like some functions:
<code>fn:string-length</code> or <code>fn:substring-before</code> can cause this problem but I cannot figure out how to solve that issue. Any ideas or tips?</p>
",https://stackoverflow.com/questions/46673235/how-to-use-saxon-with-wildfly-properly,"['xslt', 'wildfly', 'saxon']",356,TRUE,0,1
".NET Core 1.1, xUnit integration with Jenkins Test Result","<p>I have a Jenkins job that runs a unit test step on a .net core project (.net core 1.1) using the following dotnet CLI command: <code>dotnet test -l trx</code>.
The Unit Testing framework used is xUnit.</p>

<p>The problem is that the output trx file format is not fully compatible with Jenkins Test Results viewer as the All Tests table has at Package level one row only called ""(root)"" but beneath it, at ""Class"" level there is also one row but it has no name making impossible the navigation to the actual test methods beneath it.</p>

<p>I am using XUnitPublisher with MSTestJunitHudsonTestType for publishing the test results:</p>

<p><code>step([$class: 'XUnitPublisher', testTimeMargin: '3000', thresholdMode: 1, thresholds: [[$class: 'FailedThreshold', failureNewThreshold: '', failureThreshold: '', unstableNewThreshold: '', unstableThreshold: ''], [$class: 'SkippedThreshold', failureNewThreshold: '', failureThreshold: '', unstableNewThreshold: '', unstableThreshold: '']], tools: [[$class: 'MSTestJunitHudsonTestType', deleteOutputFiles: true, failIfNotNew: true, pattern: /TestResults/*.trx', skipNoTestFiles: false, stopProcessingIfError: true]]])</code></p>

<p>Is there a solution to correctly integrate the trx output result with the Jenkins Test Result view? </p>
",https://stackoverflow.com/questions/43071973/net-core-1-1-xunit-integration-with-jenkins-test-result,"['jenkins', '.net-core', 'xunit']",660,FALSE,0,1
Java annotation processor - Annotated Kotlin classes unit tests,"<p>I have an annotation processor <a href=""https://github.com/LachlanMcKee/gsonpath"" rel=""noreferrer"">library</a> that I would like to get working for Kotlin, however I have hit a snag in terms of my unit testing. I would really appreciate if someone could give me some advice.</p>

<p>My current unit testing implementation uses Google's <a href=""https://github.com/google/compile-testing"" rel=""noreferrer"">compile-testing</a> library. I create input and output classes and store them in the resources directory. Then during the unit test, the compile-testing library compiles the input java class, executes the annotation processor and then compares the generated classes against the expected output class from the resources directory.</p>

<p>Here is an example (from my project) of what I am referring to:
<a href=""https://github.com/LachlanMcKee/gsonpath/blob/feature/updated-compiler-to-use-kotlin/gsonpath-compiler/src/test/java/gsonpath/generator/adapter/auto/FieldTypesTest.kt"" rel=""noreferrer"">Unit test class</a>
<a href=""https://github.com/LachlanMcKee/gsonpath/tree/feature/updated-compiler-to-use-kotlin/gsonpath-compiler/src/test/resources/adapter/auto/field_types/primitives/valid"" rel=""noreferrer"">Resources (Input and expected output classes</a></p>

<p>This is working great for all my current java based unit tests. However when I attempt to write some tests using Kotlin classes, my test fails to load the class.</p>

<p>I believe this is due to the compile-testing library being first and foremost a Java specific library (I don't see any mention of Kotlin on their project)</p>

<p>At the moment I get the following issue:</p>

<pre><code>java.lang.IllegalArgumentException: Compilation unit is not of SOURCE kind: ""/C:/dev/gsonpath/gsonpath-compiler/build/resources/test/adapter/auto/field_types/primitives/valid/TestValidPrimitives.kt""

at com.sun.tools.javac.api.JavacTool.getTask(JavacTool.java:137)
at com.sun.tools.javac.api.JavacTool.getTask(JavacTool.java:107)
at com.sun.tools.javac.api.JavacTool.getTask(JavacTool.java:64)
at com.google.testing.compile.Compilation.compile(Compilation.java:69)
at com.google.testing.compile.JavaSourcesSubject$CompilationClause.compilesWithoutError(JavaSourcesSubject.java:281)
</code></pre>

<p>The problem is fairly obvious that the incorrect compiler is being used. The exception itself is thrown when my file extension is not '.java'. If I attempt to load a Kotlin class with the '.java' file extension, it doesn't work since it is not correct Java syntax.</p>

<p>Has anyone come across this issue before and solved it? I have had a look at a few other annotation processors (such as <a href=""https://github.com/Raizlabs/DBFlow/tree/master/dbflow-processor/src/test/java/com/raizlabs/android/dbflow/processor/test"" rel=""noreferrer"">DBFlow</a>), and they do not write unit tests in this manner.</p>

<p>Since Kotlin is only recently dabbling in annotation processing, perhaps I am the first to have this problem?</p>
",https://stackoverflow.com/questions/41528471/java-annotation-processor-annotated-kotlin-classes-unit-tests,"['java', 'unit-testing', 'junit', 'kotlin', 'annotation-processing']",890,TRUE,5,2
Perl Unit Test for Connection to Perforce -- Connect to Server Failed; check $P4PORT,"<p>I am writing a P4Perl script to make connection to a Perforce server and to automate execution of Perforce commands. Along with the development of the subroutines to access Perforce, I am also developing unit tests to verify the them. I am new to both Perl and unit testing.</p>

<p>This is my subroutine to establish a connection to Perforce. Filename is <code>p4_connect.pl</code></p>

<pre><code>use warnings;
use strict;

use P4;

my $clientname = ""johndoe""
my $p4port = ""icmanage:1667""

main();

sub main {
    my $status;
    $status = connect_perforce($clientname, $p4port);
};

sub connect_perforce {

    my ($clientname, $p4port) = @_;
    my $status;
    my $p4 = new P4;

    $p4-&gt;SetClient( $clientname );
    $p4-&gt;SetPort( $p4port );
    $status = $p4-&gt;Connect() or die( ""Failed to connect to Perforce Server"" );

    return $status;
}
</code></pre>

<p>The Perl script executes fine when I run <code>""perl p4_connect.pl""</code>, no errors are thrown.</p>

<p>However, when I moved the <code>connect_perforce</code> subroutine to a package module <code>(Perforce.pm)</code> and wrote a unit test <code>(perforce.t)</code> for it, I encountered these errors:</p>

<pre><code>username@hostname% perl -Ilib t/perforce.t
ok 1 - use Perforce;
ok 2 - Perforce-&gt;can('connect_perforce')
Connect to server failed; check $P4PORT.
TCP connect to johndoe failed.
Servname not supported for ai_socktype
Failed to connect to Perforce Server at lib/Perforce.pm line 16.
</code></pre>

<p>This is how the unit test <code>(perforce.t)</code> looks like:</p>

<pre><code>use Perforce;

use warnings;
use strict;
use Test::More qw(no_plan);

use P4;

BEGIN { use_ok('Perforce'); } #package can be loaded

can_ok('Perforce', 'connect_perforce'); #subroutine connect_perforce exists

my $p4port = ""icmanage:1667"";
my $p4 = Perforce-&gt;connect_perforce(qw(johndoe $p4port)); #accessing the connect_perforce() subroutine
</code></pre>

<p>And this is how the my package <code>(Perforce.pm)</code> looks like:</p>

<pre><code>package Perforce;

use warnings;
use strict;

use P4;

   sub connect_perforce {

   my ($clientname, $p4port) = @_;
   my $status;
   my $p4 = new P4;

   $p4-&gt;SetClient( $clientname );
   $p4-&gt;SetPort( $p4port );
   $status = $p4-&gt;Connect() or die( ""Failed to connect to Perforce Server"" );

   return $status;
}
</code></pre>

<p>Where did I go wrong regarding my unit test? Any suggestions are helpful.</p>
",https://stackoverflow.com/questions/43600239/perl-unit-test-for-connection-to-perforce-connect-to-server-failed-check-p4,"['perl', 'unit-testing', 'perforce']",1036,TRUE,4,1
java.lang.NoClassDefFoundError: org/apache/logging/log4j/Logger,"<p>I want to perform unit testing in Elasticsearch for that I am using <code>Java-test-framework</code><br>
I am using <code>Elasticsearch-1.6.0</code>
and referring to these link for help 
<a href=""https://www.elastic.co/guide/en/elasticsearch/reference/1.6/using-elasticsearch-test-classes.html"" rel=""nofollow noreferrer"">https://www.elastic.co/guide/en/elasticsearch/reference/1.6/using-elasticsearch-test-classes.html</a>
<a href=""https://github.com/elastic/elasticsearch/blob/master/core/src/test/java/org/elasticsearch/action/search/SearchRequestBuilderTests.java"" rel=""nofollow noreferrer"">https://github.com/elastic/elasticsearch/blob/master/core/src/test/java/org/elasticsearch/action/search/SearchRequestBuilderTests.java</a></p>

<p>here is the code </p>

<pre><code>class CampaignESTest extends ESTestCase {

  def getCLient():MockTransportClient={
     val settings = Settings.builder()
                .put(Environment.PATH_HOME_SETTING.getKey(), Files.createTempDir().toString())
                .build();
     val client = new MockTransportClient(settings);  
     client
  }
 }

class CampaignTestSearch extends PlaySpec{
  val client=new CampaignESTest

val response = client.prepareSearch(""dbtest"")
      .setTypes(CAMPAIGN_COLLECTION_NAME)
      .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
      .addFields(""uuid"",""campaignName"",""artworkID"",""activationDate"",""_source"")
      .setQuery(query)
      .execute()
      .actionGet()
  }
</code></pre>

<p>I am getting this exception </p>

<pre><code>  DeferredAbortedSuite:
[info] Exception encountered when attempting to run a suite with class name: org.scalatest.DeferredAbortedSuite *** ABORTED ***
[info]   java.lang.NoClassDefFoundError: org/apache/logging/log4j/Logger
[info]   at org.elasticsearch.common.logging.Loggers.getLogger(Loggers.java:101)
[info]   at org.elasticsearch.bootstrap.Bootstrap.initializeNatives(Bootstrap.java:92)
[info]   at org.elasticsearch.bootstrap.BootstrapForTesting.&lt;clinit&gt;(BootstrapForTesting.java:78)
[info]   at org.elasticsearch.test.ESTestCase.&lt;clinit&gt;(ESTestCase.java:138)
[info]   at testcontrollers.campaign.CampaignTestSerach.&lt;init&gt;(CampaignTestSerach.scala:40)
[info]   at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
[info]   at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
[info]   at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
[info]   at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
[info]   at java.lang.Class.newInstance(Class.java:442)
[info]   ...
[info]   Cause: java.lang.ClassNotFoundException: org.apache.logging.log4j.Logger
[info]   at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
[info]   at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
[info]   at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
[info]   at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
[info]   at org.elasticsearch.common.logging.Loggers.getLogger(Loggers.java:101)
[info]   at org.elasticsearch.bootstrap.Bootstrap.initializeNatives(Bootstrap.java:92)
[info]   at org.elasticsearch.bootstrap.BootstrapForTesting.&lt;clinit&gt;(BootstrapForTesting.java:78)
[info]   at org.elasticsearch.test.ESTestCase.&lt;clinit&gt;(ESTestCase.java:138)
[info]   at testcontrollers.campaign.CampaignTestSerach.&lt;init&gt;(CampaignTestSerach.scala:40)
[info]   at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
[info]   ...
[error] Uncaught exception when running testcontrollers.campaign.CampaignTestSerach: java.lang.NoClassDefFoundError: org/apache/logging/log4j/Logger
</code></pre>

<p>getting an exception on this line </p>

<pre><code>val client=new CampaignESTest
</code></pre>

<p>in class <code>CampaignTestSearch</code></p>

<p>here are the dependencies in <code>build.sbt</code> file </p>

<pre><code>   ""org.slf4j"" % ""slf4j-api"" % ""1.6.4"",
                ""org.elasticsearch"" % ""elasticsearch"" % ""1.6.0"",
                ""org.elasticsearch.test"" % ""framework"" % ""5.0.0"" % ""test"",
                ""org.apache.lucene"" % ""lucene-test-framework"" % ""4.10.4"" % ""test"",
                ""com.carrotsearch.randomizedtesting"" % ""randomizedtesting-runner"" % ""1.6.0"" % ""test"",
                ""org.apache.lucene"" % ""lucene-codecs"" % ""4.10.4"" % ""test"",
                ""org.apache.logging.log4j"" % ""log4j-core"" % ""2.8.2"" ,
""org.apache.lucene"" % ""lucene-expressions"" % ""4.10.4"",
</code></pre>

<p>i suspect the cause of the exception maybe due to some versions of the dependencies can anyone please help with the correct library dependency version to make it to work or is there something else which i am missing  </p>

<p><strong>Edit</strong>
removed ""test"" from ""org.apache.logging.log4j"" % ""log4j-core"" % ""2.8.2""
<strong>Update <code>build.sbt</code></strong></p>

<pre><code>""org.slf4j"" % ""slf4j-api"" % ""1.6.4"",
                ""org.elasticsearch"" % ""elasticsearch"" % ""1.6.0"",
                ""org.elasticsearch.test"" % ""framework"" % ""5.0.0"" % ""test"",
                ""org.apache.lucene"" % ""lucene-test-framework"" % ""4.10.4"" % ""test"",
                ""com.carrotsearch.randomizedtesting"" % ""randomizedtesting-runner"" % ""1.6.0"" % ""test"",
                ""org.apache.lucene"" % ""lucene-codecs"" % ""4.10.4"" % ""test"",
                ""org.apache.logging.log4j"" % ""log4j-core"" % ""2.8.2"",
                ""org.apache.logging.log4j"" % ""log4j-slf4j-impl"" % ""2.8.2"" ,
                ""org.apache.lucene"" % ""lucene-expressions"" % ""4.10.4"",
</code></pre>
",https://stackoverflow.com/questions/45768480/java-lang-noclassdeffounderror-org-apache-logging-log4j-logger,"['java', 'scala', 'unit-testing', 'elasticsearch']",40953,TRUE,3,2
How can I unit test uwp app with NUnit Test,"<p>I have no idea on NUnit Test Framework , I have searched for uwp app with nunit test but cant find any example, this is a related article: <a href=""https://stackoverflow.com/questions/33246626/how-to-run-uwp-nunit-tests-in-with-visual-studio-2015"">How to run UWP NUnit tests in with Visual Studio 2015?</a> , but this doesnt make sense to me , what do i need on unit testing uwp app with nunit test framework, packages needed to be install?</p>

<p>Let's Just say I want to unit test a simple method Like Add and Sub:</p>

<pre><code>public int Add(int num1, int num2){
 return num1 + num2;
}

public int Sub(int num1, int num2){
 return num1 - num2;
}
</code></pre>

<p><strong>UPDATE: What I did so far is create a unit test app(universal window)
then on project.json or reference remove MSTest and replace it with <em>NUnit</em> and <em>NUnit3TestAdapter</em> and here is my UnitTest.cs :</strong></p>

<pre><code>using System;
using NUnit.Framework;

namespace UnitTestProject1
{
    [TestFixture]
    public class UnitTest1
    {
        [Test]
        public void TestMethod1()
        {
            Assert.AreEqual(4, 4);
        }
    }
} 
</code></pre>

<p>But it seems to be not reading my Test as a test, what am I missing?</p>
",https://stackoverflow.com/questions/46379761/how-can-i-unit-test-uwp-app-with-nunit-test,"['c#', 'unit-testing', 'uwp', 'nunit']",1329,TRUE,3,1
Angular 4 unit test error &quot;TypeError: Cannot read property &#39;subscribe&#39; of undefined&quot;,"<p>I am stuck and keep getting error while unit testing an Angular 4 component.</p>

<p>Here's my component:</p>

<p><strong>order-detail.component.ts</strong></p>

<pre><code>@Component({
  selector: 'order-detail',
  templateUrl: 'order-detail.component.html',
  providers: [OrderService]
})
export class OrderDetailComponent implements OnInit {
  private order: Order;

  constructor(
    private orderService: OrderService,
    private route: ActivatedRoute,
    private router: Router
  ) {}

  ngOnInit() {
    this.getOrder();
  }

  private getOrder(): void {
    this.route.paramMap
      .map((params: ParamMap) =&gt; {
        if (+params.get('id') === 0) {
          this.router.navigateByUrl('/404', {skipLocationChange: true});
        }

        return params;
      })
      .switchMap((params: ParamMap) =&gt; this.orderService.getOrder(+params.get('id')))
      .subscribe((order: Order) =&gt; this.order = order);
  }
}
</code></pre>

<p>And here is a service:</p>

<p><strong>order.service.ts</strong></p>

<pre><code>@Injectable()
export class OrderService {
  private ordersUrl = `${environment.apiUrl}/orders/`;

  constructor(private http: HttpClient) {}

  getOrder(id: number): Observable&lt;Order&gt; {
    return this.http.get(`${this.ordersUrl}${id}/`)
      .map(response =&gt; response as Order);
  }
}
</code></pre>

<p>And I want to set a spy on <code>OrderServive</code> and unit test it with such test:</p>

<p><strong>order-detail.component.spec.ts</strong></p>

<pre><code>describe('Order detail component', () =&gt; {
  let fixture: ComponentFixture&lt;OrderDetailComponent&gt;;
  let page: Page;
  let activatedRoute: ActivatedRouteStub;
  const fakeOrder: Order = {
    id: 1,
    title: 'Test 1',
    contractor: {title: 'Contractor 1'} as Contractor,
  } as Order;

  class Page {
    orderSpy: jasmine.Spy;
    routerSpy: jasmine.Spy;
    title: HTMLElement;

    constructor() {
      const orderService = fixture.debugElement.injector.get(OrderService);
      this.orderSpy = spyOn(orderService, 'getOrder').and.returnValue(Observable.of(fakeOrder));
    }
  }

  function createComponent() {
    fixture = TestBed.createComponent(OrderDetailComponent);
    page = new Page();

    fixture.detectChanges();

    return fixture.whenStable().then(() =&gt; {
      fixture.detectChanges();
    });
  }

  beforeEach(() =&gt; {
    activatedRoute = new ActivatedRouteStub();
  });

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [OrderDetailComponent],
      imports: [RouterTestingModule, HttpClientTestingModule],
      providers: [
        OrderService,
        {provide: ActivatedRoute, useValue: activatedRoute},
        {provide: Router, useClass: RouterStub},
      ],
      schemas: [NO_ERRORS_SCHEMA],
    }).compileComponents();
  }));

  describe('when navigate with existing id', () =&gt; {
    beforeEach(async(() =&gt; {
      activatedRoute.testParamMap = {id: fakeOrder.id};
      createComponent();
    }));

    it('should show title', () =&gt; {
      expect(page.orderSpy).toHaveBeenCalledWith(fakeOrder.id);
    });
  });

});
</code></pre>

<p>But I keep getting this error: <code>TypeError: Cannot read property 'subscribe' of undefined</code></p>

<p>I took <code>ActivatedRouteStub</code> and test structure from Agular documentation: <a href=""https://angular.io/guide/testing"" rel=""nofollow noreferrer"">https://angular.io/guide/testing</a></p>

<p>Component's code works fine with real data from backend and shows me order.</p>

<p>Also my codebase contains similar test which successfully does the same thing on another component with similar service, so this test is the only place which fails.</p>

<p>Using Angular 4.3.6, Karma 1.7.1 and Jasmine 2.6.4.</p>

<p>What could go wrong and how to get rid of this error?</p>
",https://stackoverflow.com/questions/46062481/angular-4-unit-test-error-typeerror-cannot-read-property-subscribe-of-undefi,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",11341,TRUE,2,1
Having trouble mocking System.getenv calls in junit,"<p>I'm trying to write a unit test with junit and mockito (very new to this) for a Spring Boot application. Basically in my code, I have specified an environment variable for a specific URL in a manifest.yml file (for deployment) that I can access through <code>String URL = System.getenv(""VARIABLE"")</code> in my code. I'm having a lot of trouble with my unit testing however, since the <code>URL</code> variable is obviously undefined. I tried the solution <a href=""https://stackoverflow.com/questions/8168884/how-to-test-code-dependent-on-environment-variables-using-junit/8169008"">here</a>, but realized this is only for mocking an environment variable if you're calling it from the actual test itself, not if you're relying on the environment variable being accessible from the code.</p>

<p>Is there any way to set it up so that when the test is run, I can set environment variables that can be accessed within the code?</p>
",https://stackoverflow.com/questions/46290503/having-trouble-mocking-system-getenv-calls-in-junit,"['java', 'unit-testing', 'junit']",26177,TRUE,7,3
Mock dependency classes per tested instance,"<p>I have a module which instantiates imported classes and asynchronously calls methods of those instances. </p>

<p>How can I mock those methods independently per test case so these mocks only make sense for instance, which is created inside a test case, given that I cannot reliably restore mocks at the end of the test? </p>

<p>Example:</p>

<pre><code>// tested class 
import B from './b';
import C from './c';

export default class A {
  someFunction() {
    let instanceB = new B();
    return instanceB.doSomething()
      .then(() =&gt; this.doSomethingElse())
      .then((data) =&gt; {
        // async context, other tests will start before this.
        let instanceC = new C(data);
      });
  }
}

// test
import A from './a';
describe('test', () =&gt; {
  it('case1', () =&gt; {
    a = new A();
    // Mock B, C with config1
    return a.someFunction().then(() =&gt; {/* asserts1 */ });
  })
  it('case2', () =&gt; {
    a = new A();
    // Mock B, C with config2
    return a.someFunction().then(() =&gt; {/* asserts2 */ });
  })
})
</code></pre>

<p>If I mock B and C in case1 and restore them synchronously, C's config will be overwritten because case2 runs before C's instantiation in the async context.
For the same reason I cannot restore mocks asynchronously after asserts1. </p>

<p>There are similar questions: <a href=""https://stackoverflow.com/questions/21072016/stubbing-a-class-method-with-sinon-js"">Stubbing a class method with Sinon.js</a>, <a href=""https://stackoverflow.com/questions/32695244/how-to-mock-dependency-classes-for-unit-testing-with-mocha-js"">How to mock dependency classes for unit testing with mocha.js?</a>
but they don't cover the problem of async mocks.</p>
",https://stackoverflow.com/questions/46827797/mock-dependency-classes-per-tested-instance,"['javascript', 'asynchronous', 'mocha.js', 'sinon']",208,FALSE,2,1
Stub a CSV file in Ruby Test::Unit,"<p>So I have a Ruby script which parses a CSV file as a list of rules and does some processing and returns an array of hashes as processed data. </p>

<p>CSV looks like this:</p>

<pre><code>id_number,rule,notes
1,""dummy_rule"",""necessary""
2,""sample_rule"",""optional""
</code></pre>

<p>The parsing of CSV looks like this:</p>

<pre><code>def parse_csv(file_name)
  filtered_data = []
  CSV.foreach(file_name, headers: true) do |row|
    filtered_data &lt;&lt; row # some processing
  end
  filtered_data
end
</code></pre>

<p>Now I am wondering if it is possible to stub/mock an actual CSV file for unit testing in such a way that I could pass a ""filename"" into this function. I could make a CSV object and use the generate function but then the actual filename would not be possible.</p>

<pre><code>def test_parse_csv
   expected_result = [""id_number""=&gt;1, ""rule""=&gt;""dummy_rule"", ""notes""=&gt;""optional""}]
   # stub/mock csv with filename: say ""rules.csv""
   assert.equal(expected_result, parse_csv(file_name))
end
</code></pre>

<p>I use Test::Ruby</p>

<p>I also found a ruby gem library called mocha but I don't know how this works for CSVs</p>

<p><a href=""https://github.com/freerange/mocha"" rel=""nofollow noreferrer"">https://github.com/freerange/mocha</a></p>

<p>Any thoughts are welcome!</p>
",https://stackoverflow.com/questions/43586951/stub-a-csv-file-in-ruby-testunit,"['ruby', 'unit-testing', 'csv', 'testunit']",2660,TRUE,2,2
Best way to intercept a network call and providing mock response while UI testing,"<p>I am testing a login page on an android project and would like to intercept when the call is being called (When a button is clicked) and provide with a mock response (200 or 401 for ex) to prevent actually calling the network every time and to make automated unit testing faster. I usually just provide correct username/pass and Thread.sleep for a few until the request is done and I know this is not the correct way.</p>

<p>I am using retrofit 2 for my network calls and Espresso for UI testing. </p>

<p>I know how to mock a retrofit call but I want to mock exactly when the call is being executed in the login activity and send that activity a mock response.</p>
",https://stackoverflow.com/questions/45096321/best-way-to-intercept-a-network-call-and-providing-mock-response-while-ui-testin,"['android', 'unit-testing', 'retrofit2', 'android-espresso']",383,FALSE,2,0
MOQ&#39;d object returning null despite specifying .Returns,"<p>I am currently working with Moq to do some unit testing. I am running into an issue where I am specifying what my mocked object returns, but the actual call is returning null instead of what I am specifying in <code>.Returns(...)</code>. I've reviewed other posts and one of the suggestions was to create the mock with <code>MockBehavior.Strict</code>- after doing this, I get a fairly verbose error as follows:</p>

<p><code>IMyRepository.Save(MvcIndividualAuth.Data.Models.DTO.MyTableDTO) invocation failed with mock behavior Strict.
All invocations on the mock must have a corresponding setup.</code></p>

<p>However, I am calling setup on the only method that my mocked object calls already. Please see code below:</p>

<p>My test:</p>

<pre><code>    MyService _myService;
    Mock&lt;IMyRepository&gt; _myRepoMock;

    [TestInitialize]
    public void Setup()
    {
      _myRepoMock = new Mock&lt;IMyRepository&gt;();
      _myService = new MyService(_myRepoMock.Object);
    }

[TestMethod]
    public void MyServiceSave()
    {
      //Arrange
      var myDto = new MyTableDTO { Id = 1, Bar = 5, Foo = ""Test"" };
      _myRepoMock.Setup(x =&gt; x.Save(myDto)).Returns(myDto);

      //Act
      var vm = _myService.Save(new MyTableViewModel(myDto));

      //Assert
      Assert.AreEqual(vm.Id, 1);
      Assert.AreEqual(vm.Foo, ""Test"");
      Assert.AreEqual(vm.Bar, 5);
      Assert.AreEqual(vm.BarPlusFoo, ""5 Test"");
    }
</code></pre>

<p>MyService.Save method:</p>

<pre><code>    public MyTableViewModel Save(MyTableViewModel viewModel)
    {
      var dto = MyTableViewModel.GetDto(viewModel);
      var dbDto = _myRepo.Save(dto);    //_myRepo is of type IMyRepository, 
                                        // this _myRepo.Save call is returning null

      var vm = new MyTableViewModel(dbDto);

      return vm;
    }
</code></pre>

<p>Why is the mocked repo in my test not returning the value I specify in my <code>.Returns(..)</code> call? All help is appreciated.</p>

<p>EDIT: as requested, here is MyRepository.Save method and MyTableViewModel.GetDto():</p>

<p>MyRepository.Save:</p>

<pre><code>public MyTableDTO Save(MyTableDTO dto)
    {
      try
      {
        var entity = new MyTable();

        if (String.IsNullOrEmpty(dto.Foo))
        {
          throw new ArgumentException(""MyTable requires Foo"");
        }

        if (dto.Id == 0)
        {
          //added
          entity.Update(dto);
          _db.MyTables.Add(entity);
        }
        else
        {
          //modified
          entity = _db.MyTables.Single(x =&gt; x.Id == dto.Id);

          entity.Update(dto);
        }

        _db.SaveChanges();

        return new MyTableDTO(entity);
      }
      catch (Exception)
      {
        throw;
      }
    }
</code></pre>

<p>MyTableViewModel.GetDto(..);</p>

<pre><code>public static MyTableDTO GetDto(MyTableViewModel vm)
    {
      var dto =  new MyTableDTO
      {
        Bar = vm.Bar,
        Foo = vm.Foo,
        Id = vm.Id
      };

      return dto;
    }
</code></pre>
",https://stackoverflow.com/questions/45485636/moqd-object-returning-null-despite-specifying-returns,"['c#', 'asp.net', '.net', 'unit-testing', 'moq']",2528,TRUE,2,2
Gtest RecordProperty() for testsuite attribute,"<p>Using Google test framework for unit testing, is it possible to configure the output XML file attributes? I know it's possible for <code>'test case'</code> attribute. Is it possible to configure the top level attributes(<code>'testsuite'</code> or <code>'testsuites'</code>) of the XML file?</p>

<p>This is what I got from the documentation: <em>Calling <code>RecordProperty()</code> outside of the lifespan of a test is allowed. If it's called outside of a test but between a test case's <code>SetUpTestCase()</code> and <code>TearDownTestCase()</code> methods, it will be attributed to the XML element for the test case. If it's called outside of all test cases (e.g. in a test environment), it will be attributed to the top-level XML element.</em></p>

<p>It says it's possible, but couldn't get how to make it work. Where exactly is the <code>RecordProperty</code> to be used?</p>
",https://stackoverflow.com/questions/47411104/gtest-recordproperty-for-testsuite-attribute,"['xml', 'googletest', 'test-suite']",3812,TRUE,2,2
Best way to test IIFE (Immediately Invoked Function Expression),"<p>So I have an existing application which uses IIFEs extensively in the browser.   I'm trying to introduce some unit testing into the code and keep with the pattern of IIFE for new updates to the code base.   Except, I'm having trouble even writing a test which gives me a handle to the code.   For example I see this type of logic all over the code base:</p>

<pre><code>var Router = (function (router) {

   router.routeUser = function(user) {
      console.log(""I'm in! --&gt; "" + user)
   };

   return router;
})(Router || {});
</code></pre>

<p>Then the JS file is included in a script tag in the markup:</p>

<pre><code>&lt;script src=""js/RouteUser.js""&gt;&lt;/script&gt;
</code></pre>

<p>and called like this in the production code:</p>

<pre><code>Router.routeUser(myUser)
</code></pre>

<p>So my question is, how do I write a test which tests the method <strong><em>routeUser</em></strong>?   I've tried this in my Mocha Test:</p>

<pre><code>var router = require('../../main/resources/public/js/RouteUser');

suite('Route User Tests', function () {
    test('Route The User', function () {
        if (!router)
            throw new Error(""failed!"");
        else{
            router.routeUser(""Me"")
        }
    });
});
</code></pre>

<p>But I get an exception:</p>

<pre><code>TypeError: router.routeUser is not a function
at Context.&lt;anonymous&gt; (src\test\js\RouteUser.test.js:8:20)
</code></pre>

<p>Then I tried returning the method, which gives the same error:</p>

<pre><code>var Router = (function (router) {
    return {
        routeUser: function (user) {
            console.log(""I'm in! --&gt; "" + user)
        } 
    }
}
)(Router || {});
</code></pre>

<p>Can anyone point me the right direction here?   </p>
",https://stackoverflow.com/questions/47204623/best-way-to-test-iife-immediately-invoked-function-expression,"['javascript', 'unit-testing', 'mocha.js', 'iife']",5269,TRUE,6,2
CI/CD Pipeline to multiple environments,"<p>I am learning CI/CD concepts and trying to set up a pipe line in Azure to deploy my sample api to dev, int,qa and prod environments. I was able to deployment the build successfully to all environments. But what is the correct way of doing CI/CD in the companies? We cannot have build on every check-in to all environments even though we have the unit testing run in the build. The usual flow should be Unit test then deploy to Stage/QA and once QA signs off then we promote the build to PROD right? How does this fit into the CI/CD pipeline? Also we can have multiple builds in Dev, can we select which build to deploy to stg and prod?</p>
",https://stackoverflow.com/questions/46588290/ci-cd-pipeline-to-multiple-environments,"['azure', 'continuous-integration']",634,FALSE,1,1
How best to test class that depends on constants in another file?,"<p>I'm writing a Ruby library - call it <code>module MyLibrary</code> - which depends upon a data parser. The parser is specific to the library, but may need to be swapped out for a different parser at a later date, so it makes sense to have it be a class nested in <code>MyLibrary</code> - <code>class MyLibrary::Parser</code>.</p>

<p><code>MyLibrary</code> exposes a few exception types to the client, and the <code>Parser</code> may hit situations where it wants to raise these exceptions (and <code>MyLibrary</code> is happy to pass them through). So I have the following arrangement:</p>

<p>my_library.rb:</p>

<pre><code>require 'parser'
module MyLibrary
  class SomeException &lt; RuntimeError
  end

  def self.do_it
    parser = Parser.new
    parser.parse_it
  end
end
</code></pre>

<p>parser.rb</p>

<pre><code>module MyLibrary
 class Parser
   def parse_it
     if bad_stuff
       raise SomeException, ""Argh""
     end
   end
 end
end
</code></pre>

<p>Now, I want to unit-test <code>Parser</code> using rspec.</p>

<p>parser_spec.rb</p>

<pre><code>require 'parser'

RSpec.describe Parser do
  it 'raises when bad stuff happens' do
    expect { Parser.new.parse_it }.to raise_error(MyLibrary::SomeException)
  end
end
</code></pre>

<p>But because I'm unit-testing the <code>Parser</code> and my_library.rb hasn't been required in, <code>SomeException</code> isn't defined.</p>

<p>What's my best method for providing <code>SomeException</code> within <code>Parser</code>'s spec? Or am I going about this in completely the wrong way?</p>
",https://stackoverflow.com/questions/42631191/how-best-to-test-class-that-depends-on-constants-in-another-file,"['ruby', 'rspec', 'dependencies']",59,TRUE,1,2
Unit Test d3v4 zoom behavior in React with Chai,"<p>Using d3v4, react and chai (chai-enzyme, chai-jquery) for unit testing.</p>

<p>So I have a zoom behavior attached to my graph.</p>

<pre><code>const zoom = d3
  .zoom()
  .scaleExtent([1, Infinity])
  .on('zoom', () =&gt; {
    this.zoomed()
  })
</code></pre>

<p>And the zoom behavior is attached to the svg element.</p>

<pre><code>const svg = d3
  .select(this.node)
  .select('svg')
  .attr('preserveAspectRatio', 'xMinYMin meet')
  .attr('viewBox', `0 0 ${svgWidth} ${svgHeight}`)
  .classed('svg-content-responsive', true)
  .select('g')
  .attr('transform', `translate(${margin.left},${margin.top})`)
  .attr('height', height + margin.top + margin.bottom)
  .attr('width', width + margin.left + margin.right)
  .call(zoom)
</code></pre>

<p>The on('zoom') callback is defined as</p>

<pre><code>zoomed () {
 const {gXAxis, plotPlanText, plotZones, width, xAxis, xScale} = this.graphObjects
 const transform = d3.event.transform

 // get xMin and xMax in the viewable world
 const [xMin, xMax] = xScale.domain().map(d =&gt; xScale(d))

 // Get reverse transform for xMin and xMax.
 if (transform.invertX(xMin) &lt; 0) {
   transform.x = -xMin * transform.k
 }
 if (transform.invertX(xMax) &gt; width) {
   transform.x = xMax - width * transform.k
 }

 // transform the bars for zones

 if (!isNaN(transform.x) &amp;&amp; !isNaN(transform.y) &amp;&amp; !isNaN(transform.k)) {
   // rescale the x linear scale so that we can draw the x axis
   const xNewScale = transform.rescaleX(xScale)
   xAxis.scale(xNewScale)

   // rescale xaxis
   gXAxis.call(xAxis)

   plotZones
     .selectAll('rect')
     .attr('x', (d, i) =&gt; transform.applyX(xScale(d.maxFrequency)))
     .attr('width', (d) =&gt; -(transform.applyX(xScale(d.maxFrequency)) - transform.applyX(xScale(d.minFrequency))))

   // transform  the flow text
   plotPlanText
     .selectAll('.plan-text-src')
     .attr('x', d =&gt; (transform.applyX(xScale(d.maxFrequency)) + transform.applyX(xScale(d.minFrequency))) / 2)
   plotPlanText
     .selectAll('.plan-text-dest')
     .attr('x', d =&gt; (transform.applyX(xScale(d.maxFrequency)) + transform.applyX(xScale(d.minFrequency))) / 2)
 }}
</code></pre>

<p>My unit test for firing up the ""zoom"" event is</p>

<pre><code>describe('d3 Event handling', function () {
  beforeEach(function () {
    $.fn.triggerSVGEvent = function (eventName, delta) {
      let event = new Event(eventName, {'bubbles': true, 'cancelable': false})
      if (delta) {
        event.deltaX = delta.x
        event.deltaY = delta.y
      }
      this[0].dispatchEvent(event)
      return $(this)
    }
  })

  describe('When the chart is zoomed', function () {
    let initialX
    beforeEach(function () {
      $('.flow-zone-container &gt; svg &gt; g').triggerSVGEvent('wheel')
    })
    it('should update elements when zoomed', function () {
      ...
    })
  })
})
</code></pre>

<p>When I use chai-jquery to trigger the ""wheel"" event, the zoom event is fired but the d3.event.tranform in the zoomed() method gives NaN for x, y and k. I want to test the zoomed() callback such that I have the d3.event.transform values to test the logic in the zoomed() method.</p>

<p>How can I fire the zoomEvent using ""wheel"" event or any other event such that d3.event is fired with some values?</p>
",https://stackoverflow.com/questions/46168548/unit-test-d3v4-zoom-behavior-in-react-with-chai,"['reactjs', 'unit-testing', 'd3.js', 'svg', 'chai']",375,FALSE,1,1
Mocking Angular 2 component dependencies in unit tests,"<p>I'm having some difficulty accessing the methods of a mocked service in Angular 2 when unit testing a component.  I'm looking for a boilerplate for how to do this and my use case is fairly standard. Having read and tried to follow the Angular docs i'm still getting an issue accessing the methods of my mocked service.</p>

<p>At this stage I just want to give the component access to the mocked service's API and ultimately spy on the services login method to ensure it was called</p>

<p>login.page.ts</p>

<pre><code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { DBService } from '../../services/db/db.service';
import { TabsPage } from '../tabs/tabs.page';

@Component({
  templateUrl: 'login.page.html',
})
export class LoginPage {
  constructor(public navCtrl: NavController, public dbService: DBService) {}

  login() {
   this.dbService.login();
  }
}
</code></pre>

<p>db.service.mock.ts</p>

<pre><code>export class MockDBService {

  public login(): string {
    return 'login service';
  }
}
</code></pre>

<p>login.page.spec.ts</p>

<pre><code>import { LoginPage } from './login.page';
import { TestBed, inject, ComponentFixture } from '@angular/core/testing';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { NavController } from 'ionic-angular';
import { mockNavController } from 'ionic-angular/util/mock-providers';
import { DBService } from '../../services/db/db.service';
import { MockDBService } from '../../services/db/db.service.mock';

describe('Login Page:', () =&gt; {

  let fixture: ComponentFixture&lt;LoginPage&gt;;
  let component: LoginPage;
  let mockDBServiceInstance: MockDBService;

  beforeEach(() =&gt; {

    TestBed.configureTestingModule({
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      declarations: [
        LoginPage,
      ],
      providers: [
        {provide: NavController, useValue: mockNavController},
        {provide: DBService, useValue: MockDBService},
        LoginPage,
      ],
    });

    fixture = TestBed.createComponent(LoginPage);
    component = fixture.componentInstance;
    mockDBServiceInstance = TestBed.get(DBService);

  });

  describe('testing the login functionality', () =&gt; {
    it('should call the login method on the DBService', () =&gt; {
      spyOn(mockDBServiceInstance, 'login');
      component.login();
      expect(mockDBServiceInstance.login).toHaveBeenCalled();
    });
  });
});
</code></pre>

<p>This throws</p>

<p><code>Error: &lt;spyOn&gt; : login() method does not exist</code></p>

<p>to stdout</p>

<p>I've been at this for ages with no real joy so any tips on how to do this in an idiomatic way would be greatly appreciated.</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/41941685/mocking-angular-2-component-dependencies-in-unit-tests,"['javascript', 'unit-testing', 'angular', 'typescript']",1932,TRUE,1,1
Issues with Intellisense and class library,"<p>I am using Visual Studio 2013. I am trying to start unit testing by using <a href=""http://www.dotnetcurry.com/aspnet-mvc/981/unit-testing-aspnet-mvc-nunit-visual-studio"" rel=""nofollow noreferrer"">this tutorial</a>.</p>

<p>I have added a class library and a reference to MVC. However, the Intellisense/Autocompletion is not working properly within my class library. Currently, this is all the code I have in my test class:</p>

<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using System.Web.Mvc;
using System.Web;
using Application_Portal;
using Application_Portal.Controllers;

namespace ApplicationPortalTests
{
    [TestFixture]
    public class HomeControllerTest
    {
        HomeController home = new HomeController();
    }
}
</code></pre>

<p>The Intellisense does not seem to recognize the home variable (no suggested properties, etc.) Typing home.Index() gives the following error:</p>

<pre><code>ApplicationPortalTests.HomeControllerTest.home' is a 'field' but is used like a 'type'  
</code></pre>

<p>Furthermore, it does not even seem to recognize ""var"" (as in var result = ...). Instead, when I type var and hit space, it autocompletes it as         EnvironmentVariableTarget.</p>

<p>I have tried cleaning and rebuilding the project, and closing and reopening Visual Studio, but with no success.</p>

<p>What might the issue be? I appreciate any advice.</p>
",https://stackoverflow.com/questions/43720281/issues-with-intellisense-and-class-library,['c#'],65,TRUE,1,1
Phpunit tries to test all Symfony console commands,"<p>I'm working on a Symfony project. As I need to do unit testing, I downloaded and installed Phpunit 6.2.4 from its website.
However, when I tried to update my database, I got this output </p>

<pre><code>php bin/console doctrine:schema:update --dump-sql
PHPUnit 6.2.4 by Sebastian Bergmann and contributors.

unrecognized option --dump-sql

bin/console doctrine:schema:update
Cannot open file ""doctrine:schema:update.php"".
</code></pre>

<p>I tried other console commands, but the result is the same. Basically, my guess was that somehow Phpunit tries to test every single file, so I edited the phpunit.xml file like this, using a previous one that worked in other project.</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;

&lt;!-- http://phpunit.de/manual/4.1/en/appendixes.configuration.html --&gt;
&lt;phpunit xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
         xsi:noNamespaceSchemaLocation=""http://schema.phpunit.de/4.1/phpunit.xsd""
         backupGlobals=""false""
         colors=""true""
         bootstrap=""app/autoload.php""
&gt;
    &lt;php&gt;
        &lt;ini name=""error_reporting"" value=""-1"" /&gt;
        &lt;server name=""KERNEL_DIR"" value=""app/"" /&gt;
    &lt;/php&gt;

    &lt;testsuites&gt;
        &lt;testsuite name=""Project Test Suite""&gt;
            &lt;directory suffix="".php""&gt;tests&lt;/directory&gt;
        &lt;/testsuite&gt;
    &lt;/testsuites&gt;

    &lt;filter&gt;
        &lt;whitelist&gt;
            &lt;directory suffix="".php""&gt;src&lt;/directory&gt;
            &lt;exclude&gt;
                &lt;directory&gt;src/*Bundle/Resources&lt;/directory&gt;
                &lt;directory&gt;src/*/*Bundle/Resources&lt;/directory&gt;
                &lt;directory&gt;src/*/Bundle/*Bundle/Resources&lt;/directory&gt;
            &lt;/exclude&gt;
        &lt;/whitelist&gt;
        &lt;blacklist&gt;
            &lt;directory&gt;bin&lt;/directory&gt;
            &lt;directory&gt;docker&lt;/directory&gt;
        &lt;/blacklist&gt;
    &lt;/filter&gt;
&lt;/phpunit&gt;
</code></pre>

<p>As far as I know, blacklisting both bin and docker directories should result in phpunit not running anything inside them, but it still doesn't work.</p>

<p>Then I checked my composer.json for the symfony/phpunit-bridge, removed it and tried again, but the problem continues.</p>

<p>Has anyone ever faced this?</p>
",https://stackoverflow.com/questions/46593516/phpunit-tries-to-test-all-symfony-console-commands,"['symfony', 'phpunit']",158,FALSE,1,1
Invalid column name. The name was never implemented in the code,"<p>I have a simple program which I'm setting up to be used with unit testing. For some reason, Entity Framework is yelling at me with the following error: <code>Invalid column name 'Author_Id'.</code></p>

<p>The problem is I do not have a column named Author_Id, not in the project, not in the Models and not in the tables on the database. For some reason, it's adding the <code>_Id</code> part to the end of what I search for.</p>

<p>Example: If I set it to search for <code>Author</code> I get <code>Author_Id</code>. <code>AuthorId</code> becomes <code>AuthorId_Id</code> and <code>Author_Id</code> turns into <code>Author_Id_Id</code>.</p>

<p>I have no idea what I'm doing wrong here. I did a search through the entire solution and nothing was found.</p>

<p>It tells me that my error is here:</p>

<pre><code>public ViewResult Index()
{
    var books = db.Books.Include(b=&gt;b.AuthorId);
    ViewBag.AlbumCount = books.Count();
    return View(books.OrderBy(b =&gt; b.Author.Id).ToList());
    //^^^^ Return is supposed to be doing the error. Fetching Name or 
}
</code></pre>

<p>My Author Model is this:</p>

<pre><code>public class Author
{
    [Key]
    public int Id { get; set; }

    [Display(Name = ""Author"")]
    public string Name { get; set; }

    [Display(Name = ""Date of birth"")]
    public DateTime? DateOfBirth { get; set; }

    [Display(Name = ""Date of death"")]
    public DateTime? DateOfDeath { get; set; }

    public ICollection&lt;Book&gt; Books { get; set; }
}
</code></pre>

<p>My Book model is this:</p>

<pre><code>public class Book
{
    [Key]
    public int Id { get; set; }

    [Display(Name = ""Select author"")]
    public Author AuthorId { get; set; }

    [Required]
    public string Title { get; set; }

    [Display(Name = ""Publication date"")]
    public DateTime? PublicationDate { get; set; }

    public float? Edition { get; set; }

    public Author Author { get; set; }
}
</code></pre>
",https://stackoverflow.com/questions/47911484/invalid-column-name-the-name-was-never-implemented-in-the-code,"['c#', 'asp.net', 'asp.net-mvc', 'entity-framework', 'linq']",451,TRUE,1,3
Receiving an unknown provider error while trying to unit test angular 1.5 components,"<p>So I'm unit testing a component I made with Angular 1.5. For security purposes, I can't copy and paste that code here, but I can give some mocks. </p>

<p>It's a simple component that has some basic selection action, with an binding event when something is selected. </p>

<p>So the code would look like this: </p>

<pre><code>angular
      .module( ""myModule"" )
      .component( ""myComponent"", { 
       template: ""Some random HTML Template"",
       bindings: { 
         onSelect: ""&amp;"" 
       },
       controller: function () {
        var ctrl = this;
        ctrl.$onInit = init;
        ctrl.selection = selection; 
        function init() {}  function selection() { 
             ctrl.onSelect(ctrl.selected) } 
       } } ); 
</code></pre>

<p>That's the basic component. I'm trying to unit test it, with a format such as this: </p>

<pre><code>describe( ""Component Test"", function() { 
    beforeEach (module( ""myModule"") ); 
    var ctrl, onSelectSpy;
    beforeEach (inject( function( _$componentController_) { 
    ctrl = {}
    onSelectSpy = jasmine.createSpy(""onSelect"");
    var $componentController = _$componentController_;
    ctrl = $componentController(""myComponent"", null, { onSelect: 
onSelectSpy}); 
    } ) ); 

    it (""Controller defined"", function() { 
    ctrl.$onInit(); 
   expect ( ctrl ).toBeDefined(); 
  }); 
} ); 
</code></pre>

<p>When I try running a test that looks very similar to this, I get this error: </p>

<p>Unknown provider: myComponentDirectiveProvider &lt;- myComponentDirective
And it gives an angular url about the line where it fails. </p>

<p>Not sure why it's not getting defined and why this isn't working. I thought components were directives. </p>

<p>Using Angular 1.5.8 and Angular-mocks 1.5.8</p>
",https://stackoverflow.com/questions/45240146/receiving-an-unknown-provider-error-while-trying-to-unit-test-angular-1-5-compon,"['angularjs', 'unit-testing', 'jasmine', 'angular-components', 'grunt-contrib-jasmine']",460,FALSE,1,0
Running Xamarin unit tests on the target device,"<p>We are creating some unit tests to test our Xamarin C# code, and would like to run those unit tests automatically (Jenkins) on an actual target device (Android or iOS) connected to the Jenkins server, not an emulator.  There are various unit test frameworks (Touch.Unit, XUnit, NUnit) to help generate a unit test application, but then I can't find a way to run those unit tests on the actual device without using Xamarin's Test Cloud (which we will use for our UI testing, but we'd rather do unit testing in-house).</p>

<p>Is there a command-line option to Xamarin Studio (Mac) to say ""run this application on the specified device, and store the unit test output in the specified file""?</p>
",https://stackoverflow.com/questions/42356593/running-xamarin-unit-tests-on-the-target-device,"['unit-testing', 'jenkins', 'xamarin', 'xamarin-studio']",581,FALSE,1,1
Initialization within Unit Tests,"<p>I'm new to Java and working my way through unit testing with JUnit. I was curious if it is bad practice to initialize objects inside each particular test vice just once at the beginning of the test class if only to save ones self from repeating code. For instance:</p>

<pre><code>public class MyTest {
    @Test
    public void defaultObj() {
        Obj d = new Obj();
        String name = """";
        assertEquals(name, d.getName());
    }
</code></pre>

<p>vs</p>

<pre><code>public class MyTest {
    Obj d = new Obj();
    String name = """";    

    @Test
    public void defaultObj() {
        assertEquals(name, d.getName());
    }
</code></pre>

<p>Again, assuming I have more than one unit test, and I would be calling <code>Obj d = new Obj();</code> in every single one of them. I feel as though the latter is more appropriate. However, I thought the former to be more explicit as each intiailizaton is localize (right?) and should I have more than one constructor for <code>Obj</code>, my intializations in the beginning will start to stack.</p>

<p>Is there a best practices idiom here? Or is either acceptable?</p>
",https://stackoverflow.com/questions/46881371/initialization-within-unit-tests,"['java', 'unit-testing', 'junit']",1184,TRUE,1,2
Android instrumentation tests - best practice for package structure,"<p>I am using espresso for instrumentation test cases.  I have structure similar to the image below for my production source code:</p>

<p><a href=""https://i.stack.imgur.com/6MtsK.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/6MtsK.png"" alt=""enter image description here""></a></p>

<p>What i would like to know is should the androidTest (instrumentation tests packages) follow the same hierarchy ? What would be the benefits ?  if i dont follow the same hierachy for instrumentation tests will it lead to any scalability issues or issues in general ?  Right now i have created instrumentation tests folder that is nothing like the production source code and everything works but i saw blogs where developers keep the packages aligned, why ?  and to be clear, for unit testing i would keep them to same as it makes sense to match packages but im not so sure about for instrumentation tests . </p>
",https://stackoverflow.com/questions/47809805/android-instrumentation-tests-best-practice-for-package-structure,"['android', 'android-espresso']",1205,TRUE,1,1
Getting Percentage coverage from Karma.js with Jenkins,"<p>I am running karma.js for unit testing and integrating with jenkins pipeline. My goal is to read the type of error thrown from Karma, if it is error related to percentage i want to terminate the job, otherwise continue even if there are other errors like unit test failures etc. (this is a requirement and there are reasons for it.)</p>

<p>I didn't find a way to do this. Any thoughts are appreciated!    </p>

<pre><code>karma start ibx-test/olb/karma.conf.js --browsers PhantomJS --log-level warn --single-run


coverageReporter: {
        type: 'lcov',
        dir: 'unit-tests/coverage/',
            check: {
                global: {
                lines: 100 //This is just for testing
                }
            }
    }
</code></pre>

<blockquote>
  <p>16:17:43 [Unit Test] 09 03 2017 21:17:43.024:<strong>ERROR [coverage]:</strong>
  PhantomJS 2.1.1 (Linux 0.0.0): <strong><em>Coverage for lines (90.33%) does not
  meet global threshold (100%)</em></strong></p>
</blockquote>

<p>EDIT: I found ""Process xUnit test result report"" in pipeline syntax under ""Build step"", can i use this somehow? Is there correlation between karma reports and xUnit?</p>
",https://stackoverflow.com/questions/42705784/getting-percentage-coverage-from-karma-js-with-jenkins,"['jenkins', 'karma-runner', 'xunit', 'karma-coverage']",914,TRUE,1,1
Require external modules as ES6 class instance variables,"<p>I have an ES6 class which depends on some external modules to work. As this is a node application I use CommonJS to require and load the modules.</p>

<p>However it is no secret that this kind of module loading makes unit testing complicated. I could of course dependency inject all required modules via the constructor, however this feels cumbersome in a dynamically typed language. I also don't like using libraries like <a href=""https://www.npmjs.com/package/proxyquire"" rel=""nofollow noreferrer"">proxyquire</a> as it bloats up my test code.</p>

<p>So I came up with the idea to store required modules as instance variables. For example:</p>

<pre><code>const someModule = require('some-module');

class MyClass {

    constructor() {
        this.someModule = someModule;
    }

    someFunction(value) {
        return this.someModule.someFunction(value);
    }

}
</code></pre>

<p>This way I can load the dependencies using module loaders and still spy/stub/mock them in my unit tests.</p>

<p><strong>Is this considered bad practice or can you see any major disadvantages?</strong></p>
",https://stackoverflow.com/questions/45146716/require-external-modules-as-es6-class-instance-variables,"['javascript', 'node.js', 'unit-testing', 'ecmascript-6', 'es6-class']",310,TRUE,1,1
global name &#39;mock&#39; is not defined,"<p>I am trying to do unit testing in Python. I keep running into problems with mock, which <em>should</em> be back ported to Python 2.7, but I can't get it to work.</p>

<p>At the top of the code I have: <code>from mock import MagicMock, call</code>, but I still get errors when I run the unittests where it complains <code>global name 'mock' is not defined</code>. </p>

<p>Frustrated, I went to see if it really was installed (pip install mock and pip install unittest have all been run).</p>

<p>mock.py <em>only</em> exists in <code>/usr/lib/python3.4/unittest/mock.py</code>, which leads me to believe that only Python3 on Debian Jessie really, actually supports mocking objects.</p>

<p>So, here's the question: how do I get the actual backport for 2.7 <strong>or</strong> in the alternative, how do I configure Debian 8 to use Python3 by default for running applications?</p>
",https://stackoverflow.com/questions/42763506/global-name-mock-is-not-defined,"['python', 'python-2.7', 'unit-testing', 'mocking']",5946,TRUE,1,1
How to test a $uibModal instance controller?,"<p>I'm trying to test a certain controller functionality with Jasmine unit testing.</p>

<p>I have a function which opens a modal instance with a <strong>new controller</strong>:</p>

<pre><code>function openFilterModal(data) {
    var modalInstance = $uibModal.open({
        controller: FilterModalController,
        controllerAs: 'vm',
        templateUrl: 'modal.html',
        resolve: {
            data: function () {
                return data;
            }
        }
    });
    return modalInstance.result;
}
</code></pre>

<p>The controller is defined below:</p>

<pre><code>FilterModalController.$inject = ['alertsModalService', '$uibModalInstance', 'data', '$scope', 'logger', '$timeout'];

    function FilterModalController(alertsModalService, $uibModalInstance, data, $scope, logger, $timeout) { 
// code goes here }
</code></pre>

<p>When I try to call 'openFilterModal', I'm unable to get the controller instance, just getting the promise from it.
I've tried to used the $controller(FilterModalController) function in Jasmine, but it couldn't find the controller.</p>

<p>What is the best practice in that case?
Should I add the controller definition to my module? right now it defined like anonymous controller... not sure if that's good behavior or not.</p>

<p>like that:</p>

<pre><code>app.controller('FilterModalController', FilterModalController);
</code></pre>

<p>Is it ok to define 2 controllers on the same module?
Or there is another way to get test the controller?</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/43168250/how-to-test-a-uibmodal-instance-controller,"['angularjs', 'unit-testing', 'bootstrap-modal', 'angular-controller']",481,FALSE,1,0
Assert Equal two list of objects UnitTesting c#,"<p>I'm currently doing some unit testing of a copy function and I need to compare the elements of the objects between the old list, and the newly copied list.
It works fine, but I was wondering if I can do it in a way that doesn't involve a for loop.
Here is my object:</p>

<pre><code>new NaturePointObject
            {
                SId = 1,
                Name = ""Test"",
                Category = NaturePointCategory.Category1,
                CreatorType = CreatorTypeEnum.1,
                NaturR = NaturR.Bn,
                Description = ""Test"",
                Kumulation = Kumulation.EnEjendom,
                Id = 1
            }
</code></pre>

<p>My old list contains ""NaturePointObject"" and is called naturPointList, and it will be copied to a list called newNaturePointList.
Here is how I Assert to know if it copied succesfully:</p>

<pre><code>Assert.AreEqual(naturPointList.Count,newNaturePointList.Count);
        for (var i = 0; i &lt; newNatureList.Count; i++)
        {
            Assert.AreEqual(naturPointList[i].Category, newNaturePointList[i].Category);
            Assert.AreEqual(naturPointList[i].Description, newNaturePointList[i].Description);
            Assert.AreEqual(naturPointList[i].Kumulation, newNaturePointList[i].Kumulation);
            Assert.AreEqual(naturPointList[i].Name, newNaturePointList[i].Name);
            Assert.AreEqual(naturPointList[i].CreatorType, newNaturePointList[i].CreatorType);
            Assert.AreEqual(naturPointList[i].NaturR, newNaturePointList[i].NaturR);
            Assert.AreNotEqual(naturPointList[i].SId, newNaturePointList[i].SId);
        }
</code></pre>

<p>As you can see not all elements of the object must be equal. And I don't care about the ""Id"" of the object.</p>

<p>Is there a shorter way to do this, than run a for loop?</p>
",https://stackoverflow.com/questions/46911251/assert-equal-two-list-of-objects-unittesting-c,"['c#', 'vs-unit-testing-framework']",3672,TRUE,1,2
Find how many connections from a particular user to ActionCable channel there currently are,"<p>I need to track how many connections a user has to an ActionCable channel, so that I know that he, for instance, has two or three browser tabs open, or none at all. This is necessary to understand whether a particular user is offline or online. Is there a way to count number of connections from a particular user to a particular channel?</p>

<p>I've actually implemented a custom solution, where I basically have a counter in Redis which I increment/decrement upon each connect/disconnect. However as of right now it remains rather buggy and it's hard to debug it due to absence of unit testing mechanism for ActionCable. So, I was wondering if there's a ""native"" reliable way to count user connections.</p>
",https://stackoverflow.com/questions/41688048/find-how-many-connections-from-a-particular-user-to-actioncable-channel-there-cu,"['ruby-on-rails-5', 'actioncable']",971,FALSE,1,1
How DI Instantiate Transition(ui-router-ng2)?,"<p>I'm playing with ui-router-ng2. And encountered a couple of problems when unit testing components having dependency of Transition for obtaining query strings.</p>

<p>And then I went though the code of this module to see how's the appropriate way to inject this utility inside my test suites with Jasmine. </p>

<p>So far, I haven't found any factory classes exposed by ui-router-ng2 that's responsible for creating Transitions.
 There's a transitionService providing a factory method but I'm not sure if that's what I'm look for and how to leverage this in my test module setup.</p>

<p>Asking this because I got error of 'No provider for Transition' when running my test suites and here's the pseudo code:</p>

<pre><code> import {APP_BASE_HREF} from ""@angular/common"";
import {TestBed, async, inject} from ""@angular/core/testing"";
import {AppModule} from ""../index"";
import {Observable} from ""rxjs"";
import {StateService, Transition} from ""ui-router-ng2"";
import {XXComponent} from ""./XXX.component"";
describe('XXComponent', () =&gt; {
beforeEach(async(() =&gt; {
TestBed.configureTestingModule({
providers: [
{provide: APP_BASE_HREF, useValue: '/'}
],
imports: [
AppModule
]
});
TestBed.compileComponents();
}));

it('should complete XXX', async(inject(
[StateService, Transition, XXComponent], (service, transition, component) =&gt; {
let oId=""823"";
let aId =""123"";
spyOn(transition, 'params').and.returnValue({'oId': '823', 'aId': '123'});
spyOn(stateService, 'go').and.stub();
... })));
})
</code></pre>

<p>Any comments will be appreciated.</p>
",https://stackoverflow.com/questions/43601108/how-di-instantiate-transitionui-router-ng2,"['angular', 'angular-ui-router', 'angular-ui-router-extras']",576,FALSE,1,0
Jasmine Unit Test: should I test the logic or the actual mocked data?,"<p>when performing unit testing is it better to test the literal result that I expect hard-coding it into the test (<code>expect(x).toBe(17)</code>), or is it better to test the logic and not the specific mock data that I am using (<code>expect(x).toBe(mockedData.value)</code>)</p>

<p>The first approach seems safer because I am sure that the test is actually testing the literal result that I expect, however the second approach is more flexible since it allows me to test the logic rather than worry about the mock data (which I can also change later without having to rewrite the test itself)</p>

<p>What are the advantages/disadvantages of either approach? What is the best practice in these cases?</p>

<p>Following is a quick example:</p>

<pre><code>// MockedData is a very long array of complex objects 
// each of them has a property 'value' of type number 
import mockedData from 'data.mock';

class ClassToTest {
    private data;
    constructor(data) {
        this.data = data;
    }
    plusOne(): number {
        return this.data.value + 1;
    } 
}

describe('test', () =&gt; {
    let instance: ClassToTest;
    beforeEach(() =&gt; {
        instance = new ClassToTest(mockedData[0]);
    })
    it('plusOne() should return the property ""value"" plus one', () =&gt; {
        // Should I write this...
        expect(instance.plusOne()).toBe(mockedData[0] + 1);
        // ...or this?
        expect(instance.plusOne()).toBe(17); // Because I know that mockedData[0].value is 16
    }) 
});
</code></pre>

<p>Thank you very much!! :)</p>
",https://stackoverflow.com/questions/46177956/jasmine-unit-test-should-i-test-the-logic-or-the-actual-mocked-data,"['javascript', 'angular', 'unit-testing', 'jasmine', 'karma-jasmine']",432,TRUE,1,1
Sinon stub a function within a function,"<p>I'm bringing tests to our javascript files at my place of employment. I have decided to use Mocha, Chai and Sinon libraries to help with testing. I am starting out by writing unit tests for functions that don't need too much refactoring and ran into this interesting case that I don't really understand.</p>

<pre><code>function getQueries() {
  code that returns queries in an array -&gt; ['one', 'two', 'three']    
}

function sort(col, type) {
  var queries = getQueries();
  some code that sorts these queries
  return sorted array
}
</code></pre>

<p>Because I am unit testing the sort function I wanted to stub getQueries() to return a dummy list. </p>

<pre><code>var queries = ['one', 'two', 'three'];
sinon.stub(getQueries).returns(queries);
</code></pre>

<p>The above code did not work error msg:</p>

<pre><code>TypeError: Attempted to wrap undefined property undefined as function
at Object.wrapMethod (file://node_modules/sinon/pkg/sinon-1.17.7.js:1359:29)
at Object.stub (file://node_modules/sinon/pkg/sinon-1.17.7.js:3459:26)
at F.stub (file://node_modules/sinon/pkg/sinon-1.17.7.js:4200:44)
at Context.obj.stub (file://node_modules/sinon/pkg/sinon-1.17.7.js:4215:37)
at Context.&lt;anonymous&gt; (unit_tests/unit_test.js:154:10)
at Context.sinonSandboxedTest (file:/node_modules/sinon/pkg/sinon-1.17.7.js:6069:39)
</code></pre>

<p>However, the code below did work properly.</p>

<pre><code>var queries = ['one', 'two', 'three'];
getQueries = sinon.stub();
getQueries.returns(queries); 
</code></pre>

<p>I do not fully understand why this code works while the one above it doesn't. I know the syntax of sinon.stub(obj, method, function) but the getQueries is a function without an object. Any insight is greatly appreciated. </p>
",https://stackoverflow.com/questions/41685467/sinon-stub-a-function-within-a-function,"['javascript', 'unit-testing', 'sinon']",5450,TRUE,1,1
Defining BOOST_TEST_DYN_LINK causes application to crash in Visual Studio,"<p>In the boost unit testing documentation it specifically states that you need to define <a href=""http://www.boost.org/doc/libs/1_63_0/libs/test/doc/html/boost_test/utf_reference/link_references/link_boost_test_dyn_link.html"" rel=""nofollow noreferrer"">BOOST_TEST_DYN_LINK</a> in order to link with the boost unit test library.</p>

<p>I am using this basic example:</p>

<pre><code>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE test_module1

// This header is for the dynamic library, not the header only one
#include &lt;boost/test/unit_test.hpp&gt;

BOOST_AUTO_TEST_CASE(test1) {
    BOOST_CHECK(true);
}
</code></pre>

<p>I have added boost to my include/library paths and the code compiles fine, but when I compile boost unit tests using Visual Studio and try to run them I get the following error:</p>

<blockquote>
  <p>The application was unable to start correctly (0xc000003b).</p>
</blockquote>

<p><em>I feel like I just need to point out how vague and not helpful this error message is at all...</em></p>

<p>For some reason if I remove the line <code>#define BOOST_TEST_DYN_LINK</code> the code will compile and run successfully, but this goes directly against what the boost documentation says.</p>

<p>Why is this happening?</p>

<hr>

<p><strong>Additional info:</strong></p>

<p>This is what I am using:</p>

<p>boost v1_63_0</p>

<p><a href=""https://i.stack.imgur.com/SFwTW.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/SFwTW.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/45880224/defining-boost-test-dyn-link-causes-application-to-crash-in-visual-studio,"['c++', 'boost', 'visual-studio-2015', 'dynamic-linking', 'boost-test']",1585,TRUE,5,3
How to perform nodeJS integration tests with Jasmine?,"<p>I have a server app written in nodeJS that serve as a REST Api. For unit testing I use Jasmine and I would like to perform some integration tests as well with some mock data. Tests like this one:</p>

<p>import ApiTestClient from ""../support/api-test-client"";</p>

<pre><code>import User from ""../../src/model/user"";

describe(""GET /users"", () =&gt; {

    it(""returns an array with all users"", done =&gt; {
        ApiTestClient
            .getUsers()
            .then(users =&gt; {
                expect(users).toEqual(jasmine.any(Array));
                done();
            })
            .catch(err =&gt; fail(err));
    });

});
</code></pre>

<p>With normal unit tests I simply can mock the API calls but in this case I must first run the server app, opening 2 terminals, one for <code>npm start</code> and then another for <code>npm test</code>.</p>

<p>So far I've tried adding this pretest script to the <code>package.json</code>:</p>

<pre><code>""pretest"": ""node dist/src/server.js &amp;""
</code></pre>

<p>So the process runs in the background, but it doesn't feel right since it will be running after the test suite ends.</p>

<p>How can I start/stop the server application automatically in order to run this integration tests?</p>
",https://stackoverflow.com/questions/45131676/how-to-perform-nodejs-integration-tests-with-jasmine,"['node.js', 'jasmine', 'automated-tests']",1476,TRUE,0,1
Mocking a static class method in a swift unit test in a swifty way?,"<p>I'm a seasoned Objective-c programmer but I can't say the same for Swift, I'm having a hard time unit testing a class in swift without using frameworks like OCMock.   </p>

<p><strong>The Problem</strong>: I'm integrating Firebase into a mixed Objective-C/Swift project, and I need to configure it based on the build configuration of the app.</p>

<p>I've written a Swift class for that (that will be used by the obj-c app delegate), however since the firebase framework is configured trough a static class method, precisely <code>FIRApp.configure(with: FIROptions)</code>, I need to mock this method somehow in order to unit test it.</p>

<p>My code, without any handle for Dependency Injection, looks like that:</p>

<pre><code>@objc class FirebaseConfigurator: NSObject{

    func configureFirebase(){

        let config = configManager.buildConfiguration

        var optionsPlistBaseName = getPlistName()

        let optionsFile = Bundle.main.path(forResource: optionsPlistBaseName, ofType: ""plist"")

        guard let opts = FIROptions(contentsOfFile: optionsFile) else{
            assert(false, ""fatal: unable to load \(optionsFile)"")
            return
        }

        FIRApp.configure(with: opts)

    }

    func getPlistName() -&gt; String{
        // retrieves correct plist name and returns it
    }

}
</code></pre>

<p>I've done some research but so far I didn't find nothing that fits my solution, however I was thinking of one of the following:</p>

<ul>
<li>I could pass a function that defaults to <code>FIRApp.configure(with:)</code> however I should do this from objective-c and the function also accepts a parameter, I was struggling with the syntax</li>
<li>I could use a wrapper around FIRApp, but I wanted to avoid it unless the only viable clean solution.</li>
<li>I could keep on playing with protocols and do dependency inversion, however being the method static I was struggling with the syntax again, I can't find an easy way to do DI with a mock class with a static method.</li>
</ul>

<p>As a reference (both personal and for who might need it) these are some of the resources I found useful and upon which I will keep on digging:</p>

<ul>
<li><a href=""http://codica.pl/2016/02/11/dealing-with-a-static-cling-in-swift/"" rel=""noreferrer"">Dealing with static cling in Swift</a></li>
<li><a href=""https://stackoverflow.com/questions/28115991/inject-mock-class-into-method-to-unit-test-method"">This Question</a></li>
<li><a href=""http://masilotti.com/better-swift-unit-testing/"" rel=""noreferrer"">This article about generic unit testing</a></li>
</ul>

<p>In the meanwhile, every help would be really appreciated.</p>

<p>As a sidenote, there are many ways I can solve this problem without struggling with mocking a static class method, but my aim here is to find out a way of mocking it in order to have a better understanding of the best practices when testing more complex situations.</p>
",https://stackoverflow.com/questions/42170690/mocking-a-static-class-method-in-a-swift-unit-test-in-a-swifty-way,"['swift', 'unit-testing', 'dependency-injection', 'xctest', 'swift-protocols']",3354,TRUE,10,1
How do I insert a demo user for testing?,"<p>I'm working through a unit testing tutorial in order to test user access.  Here's my test class</p>

<pre><code>class TestTodo(TransactionCase):

    def setUp(self, *args, **kwargs):
        result = super(TestTodo, self).setUp(*args, **kwargs)
        user_demo = self.env.ref('base.user_demo')
        self.env = self.env(user = user_demo)
        return result

    def test_record_rule(self):
        ""Test per user record rules""
        Todo = self.env['todo.task']
        task = Todo.sudo().create({'name': 'Admin Task'})
        with self.assertRaises(AccessError):
            Todo.browse([task.id]).name
</code></pre>

<p>When I run the test, I'm getting this error</p>

<pre><code>2017-08-20 17:02:19,861 25460 ERROR todo odoo.addons.todo_app.tests.test_todo: ERROR: test_record_rule (odoo.addons.todo_app.tests.test_todo.TestTodo)
2017-08-20 17:02:19,861 25460 ERROR todo odoo.addons.todo_app.tests.test_todo:  Test per user record rules
2017-08-20 17:02:19,861 25460 ERROR todo odoo.addons.todo_app.tests.test_todo: Traceback (most recent call last):
2017-08-20 17:02:19,861 25460 ERROR todo odoo.addons.todo_app.tests.test_todo:    File ""c:\users\brubin\documents\odoo-dev\custom-addons\todo_app\tests\test_todo.py"", line 9, in setUp
2017-08-20 17:02:19,861 25460 ERROR todo odoo.addons.todo_app.tests.test_todo:    File ""C:\Program Files (x86)\Odoo 10.0\server\odoo\api.py"", line 785, in ref
2017-08-20 17:02:19,861 25460 ERROR todo odoo.addons.todo_app.tests.test_todo:    File ""C:\Program Files (x86)\Odoo 10.0\server\odoo\addons\base\ir\ir_model.py"", line 1091, in xmlid_to_object
2017-08-20 17:02:19,861 25460 ERROR todo odoo.addons.todo_app.tests.test_todo:    File ""C:\Program Files (x86)\Odoo 10.0\server\odoo\addons\base\ir\ir_model.py"", line 1075, in xmlid_to_res_model_res_id
2017-08-20 17:02:19,861 25460 ERROR todo odoo.addons.todo_app.tests.test_todo:    File ""&lt;decorator-gen-5&gt;"", line 2, in xmlid_lookup
2017-08-20 17:02:19,861 25460 ERROR todo odoo.addons.todo_app.tests.test_todo:    File ""C:\Program Files (x86)\Odoo 10.0\server\odoo\tools\cache.py"", line 87, in lookup
2017-08-20 17:02:19,861 25460 ERROR todo odoo.addons.todo_app.tests.test_todo:    File ""C:\Program Files (x86)\Odoo 10.0\server\odoo\addons\base\ir\ir_model.py"", line 1064, in xmlid_lookup
2017-08-20 17:02:19,861 25460 ERROR todo odoo.addons.todo_app.tests.test_todo:  ValueError: External ID not found in the system: base.user_demo
</code></pre>

<p>I assume this is because I don't have the demo user in my database (I created this database with the <code>-d</code> flag to <code>odoo-bin</code> rather than creating it through the database manager).  Is there a way that I can add the demo user without having to delete and recreate my database?  I tried going to Users in Odoo and creating a new user named demo, but the test still errors.  I can see the demo user in the <code>res_users</code> table and it looks identical in that table to the demo user in <code>res_users</code> that's in a database where I did install demo data.</p>
",https://stackoverflow.com/questions/45784792/how-do-i-insert-a-demo-user-for-testing,"['python', 'odoo', 'odoo-10']",483,FALSE,0,2
How to list annotations (custom java ones and others) on field members of Scala case class,"<p>So I'm trying to list fields with specific annotation in a Scala case class and I'm not able to get it working... Let's see come code right away</p>

<p>The case class (it's a simplified version of it, mine extends another class and is also nested in my test class where I use it for unit testing only):</p>

<pre><code>case class Foo(@Unique var str: String) {}
</code></pre>

<p>The custom Java annotation:</p>

<pre><code>@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
public @interface Unique {}
</code></pre>

<p>And my class (simplified again) where I'm trying to do some stuffs with fields marked as unique</p>

<pre><code>class SomeClass[T] (implicit typeTag: TypeTag[T]) {
    val fields: Iterable[universe.TermSymbol] = typeOf(typeTag).members.collect { case s: TermSymbol =&gt; s }.
                                                filter(s =&gt; s.isVal || s.isVar)
    val list = fields.flatMap(f =&gt; f.annotations.find(_.tpe =:= TypeOf[Unique]).((f, _))).toList
}
</code></pre>

<p>But the val list in the last peace of code is always empty... <code>fields</code> has <code>str</code> listed in but without the annotation.</p>

<p>What am I missing?</p>

<p>The code listing the annotations is from the following answer:
<a href=""https://stackoverflow.com/questions/17792383/how-to-list-all-fields-with-a-custom-annotation-using-scalas-reflection-at-runt"">How to list all fields with a custom annotation using Scala&#39;s reflection at runtime?</a></p>
",https://stackoverflow.com/questions/45851926/how-to-list-annotations-custom-java-ones-and-others-on-field-members-of-scala,"['scala', 'annotations']",377,TRUE,0,1
How would you unit test a method whose only purpose to make a database call?,"<p>I have method something like this:</p>
<pre><code>func (alert *Alert) CreateAlert(db *mgo.Database) error {
    return db.C(&quot;alerts&quot;).Insert(&amp;alert)
}
</code></pre>
<p>How should I unit test this?
If I just call this method for uni test, then I will have to create test DB to which the call is made. I somehow feel that this would be part of integration test as we are making a call to DB.</p>
<p>If I mock the db object, then it will never test the actual implementation.</p>
<p>Should I test this at all? as the major goal for writing unit test if the data is inserted to DB or not, and such functionality are already tested in the library itself, in my case mgo library.</p>
<p>Please share your thoughts on what would be the best approach for unit testing the above scenario.</p>
",https://stackoverflow.com/questions/47976784/how-would-you-unit-test-a-method-whose-only-purpose-to-make-a-database-call,"['unit-testing', 'go', 'database-testing']",285,TRUE,0,1
"How to create unit test cases with Vue, Karma, browserify","<p>I am trying to build some unit test cases to my existing Vue project.
I found some documents there but not useful especially for testing on functions such as Watch, Promise and Then.
Is there any specific and detailed guide line on unit testing with Vue and these plugins?</p>

<p>The target vue has defined a function named test.</p>

<pre><code>const vm = new Vue(target).$mount();
vm.test(""message"");
</code></pre>

<p>But the error message is vm.test is not a function<br>
I do not know why I could not use the function defined in the target.vue.<br>
Meanwhile once I use the test function to change some data, the target vue will update the data automatically.<br>
But it seems that Vue.nextTick does not work on this situation.
Could someone help me on this point?
Thank you very much for your help.</p>
",https://stackoverflow.com/questions/43974994/how-to-create-unit-test-cases-with-vue-karma-browserify,"['vue.js', 'karma-jasmine']",245,TRUE,0,1
Providing a mock to another mocks constructor?,"<p>I'm curious about whether I'm doing things right here, as I'm new to testing.</p>

<p>I have two services (so far), <code>AuthService</code> and <code>CommentService</code>. <code>CommentService</code> depends on <code>AuthService</code>, and <code>AuthService</code> depends on a 3rd party class (<code>\SlimSession\Helper</code>).</p>

<p>In my unit test for <code>AuthService</code> I simply mock <code>\SlimSession\Helper</code> and provide the mock to the constructor.</p>

<p>Now, in my test for <code>CommentService</code> I mock the <code>AuthService</code> and provide it to the constructor of the <code>CommentService</code>. But I must also create a mock of the <code>\SlimSession\Helper</code> again to provide it to the constructor of my mocked <code>AuthService</code>.</p>

<pre><code>$session = $this-&gt;getMockBuilder('\SlimSession\Helper')
  -&gt;getMock();

$auth = $this-&gt;getMockBuilder('\App\Service\AuthService')
  -&gt;setConstructorArgs([$session])
  -&gt;getMock();

$auth-&gt;expects($this-&gt;any())-&gt;method('isLoggedIn')-&gt;willReturn(false);
$auth-&gt;expects($this-&gt;any())-&gt;method('getLoggedInUserId')-&gt;willReturn(0);
</code></pre>

<p>Is this right? It seems a bit silly to have to provide a (mock) dependency to a mock object, since it won't use that dependency anyway.</p>

<p>My question regards <code>PHPUnit</code> in particular, but I guess it could be made generally for unit testing. </p>
",https://stackoverflow.com/questions/41867424/providing-a-mock-to-another-mocks-constructor,"['unit-testing', 'testing', 'mocking', 'phpunit', 'tdd']",54,FALSE,0,0
Pouchdb Angular2 webpack issue,"<p>I am unit-testing my Angular 2 provider using Jasmine 2.5, Webpack 2.2.1, and karma 1.3.0 ...</p>

<p>I have already use my provider within ionic project and build it with ionic app-scripts all works fine.</p>

<p>However when I tried to build it with angular webpack process something goes wrong</p>

<p>I use Pouchdb and its constructor is badly translated and an error happened.</p>

<blockquote>
  <p>Unhandled Promise rejection: pouchdb_browser_1.default is not a constructor ; Zone: ProxyZone ; Task: Promise.then ; Value: TypeError: pouchdb_browser_1.default is not a constructor</p>
</blockquote>

<p>If I build it then change pouchdb_browser_1.default to pouchdb_browser using postbuild process code works fine.</p>

<p>Unfortunately I'm not able to change code that will be executed during test.</p>

<p>Please see below my <strong>webpack.test.js</strong></p>

<pre><code>const helpers = require('./helpers'),
webpack = require('webpack'),
LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin'); `module.exports = {

devtool: 'inline-source-map',



resolve: {
    extensions: ['.ts', '.js'],
    modules: [helpers.root('src'), 'node_modules']
},

module: {
    rules: [{
        enforce: 'pre',
        test: /\.ts$/,
        loader: 'tslint-loader',
        exclude: [helpers.root('node_modules')]
    }, {
        enforce: 'pre',
        test: /\.js$/,
        loader: 'source-map-loader',
        exclude: [
            // these packages have problems with their sourcemaps
            helpers.root('node_modules/rxjs'),
            helpers.root('node_modules/@angular')
        ]
    }, {
        test: /\.ts$/,
        loader: 'awesome-typescript-loader',
        query: {
            // use inline sourcemaps for ""karma-remap-coverage"" reporter
            sourceMap: false,
            inlineSourceMap: true,
            module: ""commonjs"",
            removeComments: true
        },
        exclude: [/\.e2e\.ts$/]
    }, {
        enforce: 'post',
        test: /\.(js|ts)$/,
        loader: 'istanbul-instrumenter-loader',
        include: helpers.root('src'),
        exclude: [/\.spec\.ts$/, /\.e2e\.ts$/, /node_modules/]
    }],
},

plugins: [
    // fix the warning in ./~/@angular/core/src/linker/system_js_ng_module_factory_loader.js
    new webpack.ContextReplacementPlugin(
        /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
        helpers.root('./src')
    ),

    new LoaderOptionsPlugin({
        debug: true,
        options: {

            /**
             * Static analysis linter for TypeScript advanced options configuration
             * Description: An extensible linter for the TypeScript language.
             *
             * See: https://github.com/wbuchwalter/tslint-loader
             */
            tslint: {
                emitErrors: false,
                failOnHint: false,
                resourcePath: 'src'
            },

        }
    })
]};
</code></pre>

<p>Any ideas ? </p>

<p>Thanks !</p>
",https://stackoverflow.com/questions/42514631/pouchdb-angular2-webpack-issue,"['javascript', 'angular', 'typescript', 'webpack', 'karma-jasmine']",389,TRUE,0,1
Can I run a test in a loop in Ceedling?,"<p>I'm pretty new to using Ceedling/Unity. I have a module I'm testing by giving it different input test points and checking the output value. But I need to do this many times. This is something like what I tried (using 'for' loop):</p>

<pre><code>/*Example Code*/
void test_whenInputIsThis_thenOutputIsThat(void)
{
    for(i=0;i&lt;ITERATIONS;i++)
    {
    /*Everything is declared &amp; initialized as required*/
    inputA = inputA_array[i];
    inputB = inputB_array[i];
    expected = expectedValues_array[i];
    ModuleUnderTest(inputA, inputB);
    TEST_ASSERT_FLOAT_WITHIN(delta, expected, actual);
    }
}
</code></pre>

<p>And although I see the tests passed (expected and actual are within delta), in the Overall Test Summary I see this</p>

<pre><code>--------------------
OVERALL TEST SUMMARY
--------------------
TESTED:  1
PASSED:  1
FAILED:  0
IGNORED: 0
</code></pre>

<p>This suggests to me that one test function = 1 test. Interestingly, I can print all values for expected and actual through the loop (so the loop is executing fully). So, is there a way to put a test in a loop? Or iterate it some other way? Or am I breaking some rule of unit testing? </p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/43325160/can-i-run-a-test-in-a-loop-in-ceedling,"['c', 'unit-testing', 'unity-test-framework']",749,FALSE,0,1
.NET Web API Unit Test for model with DbGeography System.DllNotFoundException: Unable to load DLL &#39;SqlServerSpatial110.dll&#39;,"<p>I have a working ASP NET Web APIs, some of which are using Spatial Data Types using DbGeography. I added this line to the startup code to make it work here.
<code>SqlServerTypes.Utilities.LoadNativeAssemblies(Server.MapPath(""~/bin""));</code></p>

<p>I have a unit testing project, which is referencing the project mentioned above. When trying to run a test that calls a method that uses DbGeograohy, I get the error ""System.DllNotFoundException: Unable to load DLL 'SqlServerSpatial110.dll'"".</p>

<p>This error appeared previously in the Web API project, and I solved by adding the line above to the startup class, which basically loads the native Windows library.</p>

<p>I want to learn if it's possible to have a ""Startup"" class for the tests, where the library would be loaded before executing them.</p>

<p>Cheers :)</p>
",https://stackoverflow.com/questions/47967617/net-web-api-unit-test-for-model-with-dbgeography-system-dllnotfoundexception-u,"['asp.net-web-api2', 'visual-studio-2017', 'vs-unit-testing-framework']",118,FALSE,0,0
Changing innodb_page_size in my.cnf file does not restart mysql database,"<p>Hope you have a great day. I have a table with 470 columns to be exact. I am working on Django unit testing and the tests won't execute giving the error when I run command python manage.py test: </p>

<blockquote>
  <p><strong>Row size too large (> 8126). Changing some columns to TEXT or BLOB or using ROW_FORMAT=DYNAMIC or ROW_FORMAT=COMPRESSED may help. In
  current row format, BLOB prefix of 768 bytes is stored inline</strong></p>
</blockquote>

<p>To resolve this issue I am trying to increase the <code>innodb_page_size</code> in MySQL my.cnf file. When I restart MySQL server after changing value in my.cnf file, MySQL won't restart.</p>

<p>I have tried almost every available solution on stackoverflow but no success.</p>

<p>MYSQL version=5.5.57
Ubuntu version = 16.04</p>

<p>Any help would be greatly appreciated. Thank you</p>
",https://stackoverflow.com/questions/45964972/changing-innodb-page-size-in-my-cnf-file-does-not-restart-mysql-database,"['python', 'mysql', 'django', 'unit-testing', 'innodb']",1080,FALSE,0,1
unit tests in multi module maven project are skipped,"<p><strong>Scenario</strong>: Multi-module Maven project</p>

<p><strong>Issue</strong>: Unit tests are only running for a single module.</p>

<p><strong>Background</strong>:
I'm attempting to separate my integration testing from unit testing.  To do this I've created two properties in my parent pom, <strong>Root-module</strong>, that disable unit tests and integration tests by default.</p>

<pre><code>&lt;maven.test.skip&gt;true&lt;/maven.test.skip&gt;
&lt;maven.integration.test.skip&gt;true&lt;/maven.integration.test.skip&gt;
</code></pre>

<p>In my top-most module, <strong>UI-module</strong>, I've created two profiles, <em>dev</em> and <em>integration-test</em>.  <em>Dev</em> has unit tests enabled and <em>integration-test</em> has integrations enabled:</p>

<pre><code>&lt;profile&gt;
....
&lt;maven.test.skip&gt;false&lt;/maven.test.skip&gt;
&lt;/profile&gt;
</code></pre>

<p><em>Integration-test</em> works correctly.  The <em>dev</em> profile only runs the unit-tests for the <strong>UI-module</strong>, which is where the pom.xml is located that contains these profiles.  </p>

<p>How can I enable unit tests for all modules?  Is the profile approach correct?  If so, why isn't the value applied to other modules?</p>
",https://stackoverflow.com/questions/42989646/unit-tests-in-multi-module-maven-project-are-skipped,"['java', 'maven', 'unit-testing', 'integration-testing', 'maven-module']",402,FALSE,0,0
Why use explicit schema prefix in Postgres functions?,"<p>I am using Postgres for microservice backends and the databases are designed to be small(ish) and simple.</p>

<p>We have four schemas in our databases:</p>

<ol>
<li>live: all the functions, tables, etc used by the application</li>
<li>utest:unit tests </li>
<li>testframe: unit testing functions/framework</li>
<li>testdata: functions that create common test data</li>
</ol>

<p>When the database is shipped to production <strong>ONLY</strong> the 'live' schema is retained, all the testing schema's are dropped.  </p>

<p>So my question is: Is there any reason for functions in the 'live' schema to  explicitly using the 'live.' schema prefix when referring to tables and calling other functions?</p>

<p>After much googling I am having a hard time making an argument for explicitly using the schema prefix.</p>

<p>Thanks, any comments are appreciated.</p>
",https://stackoverflow.com/questions/47913322/why-use-explicit-schema-prefix-in-postgres-functions,"['postgresql', 'function', 'schema']",446,TRUE,0,1
Camel - No component found with scheme:mybatis,"<p>I've got a Spring Boot app that makes use of Camel and Mybatis. I've got the following mybatis dependencies in pom.xml:</p>

<p><b>pom.xml</b></p>

<pre><code>....
&lt;dependency&gt;
    &lt;groupId&gt;org.apache.camel&lt;/groupId&gt;
    &lt;artifactId&gt;camel-mybatis&lt;/artifactId&gt;
    &lt;version&gt;${camel.version}&lt;/version&gt;
&lt;/dependency&gt;
....
&lt;dependency&gt;
    &lt;groupId&gt;org.mybatis.spring.boot&lt;/groupId&gt;
    &lt;artifactId&gt;mybatis-spring-boot-starter&lt;/artifactId&gt;
    &lt;version&gt;1.0.1&lt;/version&gt;
&lt;/dependency&gt;
....
</code></pre>

<p>I've got the following route:</p>

<p><b>MyRoute.java</b></p>

<pre><code>@Component
public class MyRoute extends SpringRouteBuilder{

    @Autowired
    MQConnectionProperties mqConnectionProperties;

    @Override
    public void configure() throws Exception {
        from(mqConnectionProperties.getResponseQueue())
        .to(""mybatis:selectLogByPrimaryKey?statementType=SelectOne"")
        .process(new TargetSystemProcessor())
        .end()
    }
}
</code></pre>

<p>and the test for the route:</p>

<p><b>MyRouteUnitTest.java</b></p>

<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {MyRouteTestConfiguration.class})
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
public class MyRouteUnitTest extends CamelTestSupport{

    @Mock
    MyBatisComponent mybatis;
    @Autowired
    MQConnectionProperties mqProps;
    @Autowired
    MyRouteBuilder route;

    @Before
    public void setup() throws Exception {
        super.setUp();
        context.addComponent(""mybatis"", mybatis);
    }

    @Test
    public void test() throws Exception {
        startCamelContext();

        assertTrue(true);

        stopCamelContext();
    }
}
</code></pre>

<p>When I try to start the test without adding mybatis as a component to the context, I get this error:</p>

<pre><code>org.apache.camel.FailedToCreateRouteException: Failed to create route My_Route at: &gt;&gt;&gt; To[mybatis:selectAuditLogByPrimaryKey?statementType=SelectOne] &lt;&lt;&lt; in route: Route(My_Route)[[From[seda:inpu... because of Failed to resolve endpoint: mybatis://selectAuditLogByPrimaryKey?statementType=SelectOne due to: Cannot auto create component: mybatis
....
Caused by: org.apache.camel.ResolveEndpointFailedException: Failed to resolve endpoint: mybatis://selectAuditLogByPrimaryKey?statementType=SelectOne due to: Cannot auto create component: mybatis
....
Caused by: java.io.FileNotFoundException: Cannot find resource: SqlMapConfig.xml in classpath for URI: SqlMapConfig.xml
</code></pre>

<p>Whenever I add the component to the context as shown i nthe test above, I get this error:</p>

<pre><code>org.apache.camel.FailedToCreateRouteException: Failed to create route My_Route at: &gt;&gt;&gt; To[mybatis:selectAuditLogByPrimaryKey?statementType=SelectOne] &lt;&lt;&lt; in route: Route(My_Route)[[From[seda:inpu... because of Failed to resolve endpoint: mybatis://selectAuditLogByPrimaryKey?statementType=SelectOne due to: No component found with scheme: mybatis
</code></pre>

<p>As far as I can tell, I've got the right dependencies i nthe pom file to hook all of this together, and mybatis works fine in the source code. For unit testing I can work around it by replacing the endpoint, but I can't write any integration tests for my route</p>
",https://stackoverflow.com/questions/43128775/camel-no-component-found-with-schememybatis,"['java', 'spring-boot', 'apache-camel', 'mybatis']",690,FALSE,0,0
How to exclude printf messages from Catch reporter,"<p>I am testing a library that monitors USB stick and allows listening to plugin/plugout events. The target system runs a custom Linux version and debugging is a pain on this system</p>

<p>So, for quick analysis of what is going, I very often use <code>printf</code> messages. </p>

<p>For unit testing of the library, I have started using <code>Catch</code> and I generate test reports using JUint reporter. </p>

<p><strong>Problem:</strong> If I insert a<code>printf</code> message for analysis, it gets added to the <code>xml</code> report generated by <code>Catch</code>.</p>

<p><strong>My question</strong>: Is there a way to separate <code>printf</code> messages and the report generated by <code>Catch</code>?</p>

<p>Thanks.</p>

<p>UPDATE: I want to avoid writing to a file, because I've had problems with it when there are errors and the program crashes before the file is completely written to.</p>
",https://stackoverflow.com/questions/46490302/how-to-exclude-printf-messages-from-catch-reporter,"['c++', 'linux', 'cross-platform', 'catch-unit-test']",224,TRUE,0,3
"Added JUnit, but Android Studio wants me to add testng","<p>Referring to <a href=""https://developer.android.com/training/testing/unit-testing/local-unit-tests.html"" rel=""nofollow noreferrer"">https://developer.android.com/training/testing/unit-testing/local-unit-tests.html</a> and <a href=""https://medium.com/@ali.muzaffar/the-basics-of-unit-and-instrumentation-testing-on-android-7f3790e77bd"" rel=""nofollow noreferrer"">https://medium.com/@ali.muzaffar/the-basics-of-unit-and-instrumentation-testing-on-android-7f3790e77bd</a>, I added</p>

<pre><code>testCompile 'junit:junit:4.12'
</code></pre>

<p>in my gradle. Then I created a new test class, but apparently </p>

<blockquote>
  <p>@Test</p>
</blockquote>

<p>throws 'Cannot resolve symbol'. On pressing ALT + Enter, Android Studio suggested me to 'Add testng to classpath'.</p>

<p>I don't quite understand what's going on here. I thought I don't need testng for what I'm trying to do here, nor the 2 articles above also didn't mention anything about testng.</p>

<p>Furthermore if I followed the Android Studio suggestion to 'Add testng to classpath', Android Studio will automatically add </p>

<pre><code>androidTestCompile 'org.testng:testng:6.9.6'
</code></pre>

<p>in my gradle. And when I try to run the test, I will get the error</p>

<pre><code>Error:Error converting bytecode to dex:
Cause: com.android.dex.DexException: Multiple dex files define Lorg/hamcrest/Description;
</code></pre>
",https://stackoverflow.com/questions/43993007/added-junit-but-android-studio-wants-me-to-add-testng,"['android', 'unit-testing']",237,FALSE,0,1
Making modular login function with selenium-webdriver and mocha,"<p>I am trying to create a login function that I can use with mocha testing and selenium-webdriver for unit testing, since I have a bunch of things to do that start with ""user logs in and...""</p>

<p>Below is my best shot, but when I run it, the console just logs</p>

<pre><code>Already registered user logs in and sees homepage
  1) should work (it's red text)

Login an existing user
</code></pre>

<p>and then nothing happens and I have to control-C out of the process. My code was working <em>before</em> I went for this modular login implementation, so I'm sure that's where my problem is. Is there something I am missing here? I am also open to general critiques of how I went about making the <code>login</code> function, since I don't have that much experience with webdriver.</p>

<p>Below is my code. It's in one js file.</p>

<pre><code>var test = require('selenium-webdriver/testing'),
chai = require('chai');
chai.use(require('chai-string'));
chai.use(require('chai-as-promised'));
var expect = chai.expect,
webdriver = require('selenium-webdriver'),
By = webdriver.By;

// I want this to be a modular login function I can use multiple places
function login(driver) {
    test.describe('Login an existing user', function() {
        test.it('should work', function() {
            this.timeout(0);

            var email = 'myemail@test.com';
            var password = 'password';

            driver.get('http://localhost:9000');

            driver.getTitle().then(function(title) {
                expect(title).to.equal('my title');
            })
            .then(function() {
                // do login stuff and click login button
            });
            .then(function() {
                return driver;
            });
        });
    });
}

//an example of when I would use the login function
test.describe('Already registered user logs in and sees homepage', function() {
  test.it('should work', function() {

    this.timeout(0);
    var driver = new webdriver.Builder().
    withCapabilities(webdriver.Capabilities.chrome()).
    build();

    driver = login(driver)
    .then(function() {
        driver.findElement(By.xpath(""relevant xpath"")).click();
    })
  })
})
</code></pre>
",https://stackoverflow.com/questions/45449685/making-modular-login-function-with-selenium-webdriver-and-mocha,"['javascript', 'unit-testing', 'selenium-webdriver', 'mocha.js']",567,TRUE,0,1
"NodeJS: How to verify a function call inside promise resolution while testing using Mocha, Chai, Sinon?","<p>I'm new to unit testing in NodeJS using Mocha, Chai and Sinon. I have been trying to write a unit test case for an API end-point and am struggling with testing if <code>res.status(200).send();</code> is called from the API inside a Promise resolution. Below is the code:</p>

<p><strong>controller.js</strong> - Has the function to be unit tested</p>

<pre><code>const User = require(""./user_model"");

module.exports = {
    getUserById(req, res) {
        const { params: reqParams } = req,
            { userId } = reqParams;

        User.findOne({ _id: userId })
            .exec()
            .then(function(userFromDb) {
                res.status(200).send();    // unable to test if this is getting called.
            })
            .catch((err) =&gt; res.status(500).send());
    }
};
</code></pre>

<p><strong>test.js</strong> - Has the unit test</p>

<pre><code>const sinon = require(""sinon""),
    User = require(""./user_model""),
    controller = require(""../controller"");

require(""sinon-mongoose"");

describe('users', function() {
    it('getUserById', function() {
        const validReqObj = {
            params: {
                userId: ""123""
            }
        };

        const mock = sinon.mock(User);
        mock.expects(""findOne"").withArgs({ _id: validReqObj.params.userId })
            .chain(""exec"")
            .resolves({ _id: validReqObj.params.userId });

        const validRes = {
            status: function(statusCode) {
                sinon.assert.match(statusCode, 200);

                return {
                    send: function() {

                    }
                };
            }
        };

        controller.getUserById(validReqObj, validRes);

        mock.restore();
        mock.verify();
    });
});
</code></pre>

<p>As you can see, my test does 2 things: </p>

<ol>
<li>mocks the mongoose <code>findOne</code> function and tests if the promise resolution of <code>findOne</code> is fine or not.</li>
<li>Asserts that <code>res.status()</code> gets called with a 200 status code.</li>
</ol>

<p>It doesn't test if <code>res.status()</code> even gets called. For example, if I remove the line <code>res.status(200).send();</code> from <em>controller.js</em>, the test still passes.</p>

<p>I tried creating <a href=""http://sinonjs.org/releases/v3.3.0/spies/"" rel=""nofollow noreferrer"">spy</a> on <code>res.status</code>. It doesn't work as expected.</p>
",https://stackoverflow.com/questions/46389816/nodejs-how-to-verify-a-function-call-inside-promise-resolution-while-testing-us,"['node.js', 'unit-testing', 'mocha.js', 'sinon', 'chai']",849,TRUE,-1,2
Angular2 - Call function from a tested component,"<p>I'm currently writing unit tests for Angular2 with Karma and Jasmine, but I'm pretty new in the unit testing and I'm facing some difficulties. When it comes to testing hardcoded properties or properties that don't involve async functions, it's all okay, but I need to be able to call the component's functions in order for some variables to get their values. What I'm doing is the following: </p>

<p>My component:</p>

<pre><code>export class LoginComponent implements OnInit {

formLoginId: string;
loginUrl: string;
email: string;
password: string;

constructor(private googleAuthService: GoogleAuthService,
            private authService: AuthenticationService,
            private validationService: ValidationService,
            private router: Router,
            private titleService: Title) {
    this.titleService.setTitle(""Login"");
    this.formLoginId = ""#form-login"";
}

ngOnInit() {

    this.googleAuthService.getLink((response) =&gt; {
        this.loginUrl= response.json().url;
    });       
}

login() {
    if (this.validationService.isValid(this.formLoginId)) {
        this.authService.login(this.email, this.password);
    }
}
</code></pre>

<p>Now I want to write a unit test which can check if the loginUrl has taken any value. My test is bellow: </p>

<pre><code>describe('Login Component', ()=&gt; {
    let component:LoginComponent;
    let fixture:any;

    beforeEach(async(()=&gt; {
        TestBed.configureTestingModule({
            //declarations,imports and providers
        }).compileComponents();
    }));

    beforeEach(() =&gt; {
        fixture = TestBed.createComponent(LoginComponent);
        component = fixture.componentInstance;
    });   /some-other-tests/

    it('should have login url', fakeAsync(()=&gt; {
        component.ngOnInit();
        tick(1000);
        expect(component.loginUrl).toBeDefined();
    }));
});
</code></pre>

<p>But it seems that its not working. I'm still getting undefined for the mentioned variable. How can I call a method from a component and check the variables after its result? </p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/41939609/angular2-call-function-from-a-tested-component,"['unit-testing', 'angular', 'typescript', 'karma-jasmine']",2129,TRUE,0,1
Generic comparer using reflection,"<p>I am putting together simple generic comparer for unit testing.<br>
I don't want to use IComparable interface because there is just too much classes that would need to implement it, and it will be only used in Unit tests so performance of reflection is not an issue.</p>

<p>So far I have this:  </p>

<pre><code> public IEnumerable&lt;NonEqualProperty&gt; Compare&lt;T&gt;(T first, T second) where T : class
        {
            var list = new List&lt;NonEqualProperty&gt;();
            var type = first.GetType();
            var properties = type.GetProperties();

            var basicTypes = properties.Where(p =&gt; !p.PropertyType.IsClass &amp;&amp; !p.PropertyType.IsInterface
                                                   || p.PropertyType == typeof(string));


            foreach (var prop in basicTypes)
            {
                var value1 = prop.GetValue(first, null);
                var value2 = prop.GetValue(second, null);

                if (value1 != null &amp;&amp; value2 != null &amp;&amp; value1.Equals(value2) || value1 == null &amp;&amp; value2 == null )
                    continue;

                list.Add(new NonEqualProperty(prop.Name, value1, value2));
            }

            var enumerableTypes =
                from prop in properties
                from interfaceType in prop.PropertyType.GetInterfaces()
                where interfaceType.IsGenericType
                let baseInterface = interfaceType.GetGenericTypeDefinition()
                where prop.PropertyType != typeof(string) &amp;&amp; baseInterface == typeof(IEnumerable&lt;&gt;) || baseInterface == typeof(IEnumerable)
                select prop;

            foreach (var prop in enumerableTypes)
            {
                var collection = prop.GetValue(first, null);
            }


            return list;
        }
</code></pre>

<p>So comparison of all simple types + string works.  </p>

<p>Now I would like to iterate through IEnumerable (it's always enumerable of a class, though it would be great to take care of the case when it's not) on both sides and compare values using recursion. Something like this:  </p>

<pre><code>foreach (var prop in enumerableTypes)
{
    var typeOfItemsInList= ...;
    var collection1 = (IEnumerable&lt;typeOfItemsInList&gt;) prop.GetValue(first, null);
    var collection2 = (IEnumerable&lt;typeOfItemsInList&gt;) prop.GetValue(second, null);

    for (int i = 0; i &lt; collection1.Count; i++)
    {
        var item1 = collection1[i];
        var item2 = collection2[i];

        Compare&lt;typeOfItemsInList&gt;(item1, item2, list);
    }

}
</code></pre>

<p>How would I achieve that?</p>

<p>Unequal count, or order of items in lists are not taken into account here - I would fix it later.</p>
",https://stackoverflow.com/questions/42481371/generic-comparer-using-reflection,"['c#', 'generics', 'reflection', 'comparison']",283,TRUE,0,1
angularjs code coverage using blackbox testing (running the functional automation test scripts written in protractor) and without unit testing,"<p>My requirement is, I should not do the unit testing to know the code coverage of angularjs code. simply to say, when I do black-box testing, I should get the code coverage report of angular js code. </p>

<p>we have automation test scripts for functional testing written in protractor.
Now, when I run these automation test scripts, code coverage report should be generated. </p>

<p>We have NCover tool. But we should use the tool other than this.</p>

<p>I am searching for this but unable to find the exact answer as I am new to protractor and other tools like karma/istanbul/grunt etc. </p>

<p>Please help me on this how I can do this and the setup to do. It will be very helpful to me.</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/46634905/angularjs-code-coverage-using-blackbox-testing-running-the-functional-automatio,"['angularjs', 'code-coverage']",244,FALSE,0,0
Unit and Integration Testing for Google Drive API using C# (Client Library v3)?,"<p>I am writing a small library which uses Google Drive API v3 Client Library for C#.
And for me it involves a lot of pain because I can't use TDD-style for that purpose.</p>

<p>The regular method for doing the job looks something like:</p>

<pre><code>internal async Task&lt;Google.Apis.Drive.v3.Data.FileList&gt; ReadFileList(string parentId, string pageToken, int pageSize)
{
    // Define parameters of request.
    var listRequest = this.driveService.Files.List();
    listRequest.PageSize = pageSize;
    listRequest.Q = ""mimeType='application/vnd.google-apps.folder' and ('"" + parentId + ""' in parents)"";
    listRequest.Fields = ""nextPageToken, files(id, name)"";
    listRequest.PageToken = pageToken;

    // List files.
    return await listRequest.ExecuteAsync();
}
</code></pre>

<p>For Unit Testing it contains a couple of dependencies (probably it might be refactored using factory method pattern):</p>

<ol>
<li>ListRequest</li>
<li>FileList</li>
</ol>

<p>For Integrating Tests there are much more problems:</p>

<ol>
<li>How should I authenticate such service?</li>
<li>Even after authentication it will pollute real Authenticated Drive Account.</li>
<li>How to share the tests between other people?</li>
<li>Test couldn't pass without an internet connection.</li>
</ol>

<p>Is there something like ""In-Memory"" provider for Entity Framework Core?
What can be done to make Google Drives Unit and Integration Tests manageable?</p>
",https://stackoverflow.com/questions/43002553/unit-and-integration-testing-for-google-drive-api-using-c-client-library-v3,"['c#', 'unit-testing', 'google-drive-api', 'integration-testing']",1453,TRUE,0,1
MSBuild 15 - The type or namespace &#39;Fakes&#39; does not exist in the namespace,"<p>I'm trying to set up automated builds and unit testing for a project which uses the Fakes library for it's unit tests. The project builds and tests fine on my Windows 10 PC (VS 2017 Enterprise installed), however using the same command to compile the project on the build server (also windows 10 with VS 2017 Enterprise) gives several errors about the Fakes not existing. The exact errors look like this:</p>

<p><code>XControllerTests.cs(10,20): error CS0234: The type or namespace 'Fakes' does not exist in the namespace 'System.Data.Common' (are you missing an assembly reference?) [C:\Runner\builds\xxx\XTests.csproj]</code></p>

<p>From my research, this is caused by using an old version of MSBuild, however I have checked the server, and confirmed it has the latest version &amp; updates for visual studio installed. I also confirmed that the build script is using the correct version of MSBuild.exe, which is <code>c:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\MSBuild.exe</code>. Using this version on my desktop correctly compiles the project.</p>

<p>Why does the build not work on the (identical setup) build server?</p>
",https://stackoverflow.com/questions/44156571/msbuild-15-the-type-or-namespace-fakes-does-not-exist-in-the-namespace,"['c#', 'msbuild', 'microsoft-fakes']",9162,TRUE,8,3
Recognize namespaced symbol in a Clojure macro,"<p>I am working on a macro, <code>either</code> which does some code transformations, defined in the file <code>epicea.antivalue.core</code>. Among other things, it should recognize the use of the symbol <code>make</code> as if that symbol was bound in the namespace <code>epicea.antivalue.core</code>. But ideally, the symbol <code>make</code> should be unbound. My code is available here: <a href=""https://github.com/jonasseglare/epicea-antivalue/tree/stackoverlow-question"" rel=""nofollow noreferrer"">https://github.com/jonasseglare/epicea-antivalue/tree/stackoverlow-question</a></p>

<p>To identify the symbol <code>make</code>, I here is some code from <code>epicea.antivalue.core</code>:</p>

<pre><code>(def make ::make)

(defn evals-to-keyword [kwd]
  (fn [x]
    (try
      (and (symbol? x)
           (= kwd (eval x)))
      (catch Throwable e
        false))))

;; Function to test if we are referring to a symbol 'make' in the namespace of this file.
(def make-sym? (evals-to-keyword ::make))
</code></pre>

<p>but unfortunately, I need the line 
    (def make ::make)
in order for it to work.</p>

<p>My problem is reflected by the unit testing code in 
    epicea.antivalue.core-test.clj
which <em>currently fails</em>:</p>

<pre><code>(ns epicea.antivalue.core-test
  (:import [epicea.antivalue AntivalueException])
  (:require [clojure.test :refer :all]
            [epicea.tag.core :as tag]
            [epicea.antivalue.core :as av]))

(deftest contextual-make
  ;; The call to 'av/make' should only work inside the 'av/either' macro
  ;; These tests PASS
  (is (= 4 (av/either (av/make false 9 3) 4)))
  (is (= 9 (av/either (av/make true 9 3) 4)))

  ;; This test PASSES, as we would expect.
  (is (try
        (eval '(println epicea.antivalue.core/some-unbound-symbol))
        false
        (catch Throwable e
          true)))

  ;; But outside the 'av/either' macro, 'av/make' should be unbound.
  ;; This test FAILS, but I don't want it to fail. How can we achieve that?
  (is (try
        (eval '(println epicea.antivalue.core/make))
        false
        (catch Throwable e
          true))))
</code></pre>

<p><strong>So my question is</strong>: How can I implement the function <code>make-sym?</code> without having the the symbol <code>make</code> defined in the <code>epicea.antivalue.core</code> namespace? In other words, how can I make the unit test pass, by only editing the source file <code>epicea.antivalue.core</code>?</p>
",https://stackoverflow.com/questions/41921292/recognize-namespaced-symbol-in-a-clojure-macro,['clojure'],92,FALSE,3,0
Cassandra&#39;s EmbeddedCassandraService throws InvalidRequestException: unconfigured table schema_keyspaces,"<p>Our application uses EmbeddedCassandraService for unit testing. We're using Cassandra 3.11 and the java driver from Datastax 3.3.0.</p>

<pre><code>EmbeddedCassandraService cassandraService = new EmbeddedCassandraService();
cassandraService.start();
</code></pre>

<p>We are able to use embedded cassandra perfectly fine when testing our domain classes. However, when using it with our API tests (which have a different set of dependencies) it throws the following exception:</p>

<pre><code>Caused by: org.apache.cassandra.exceptions.InvalidRequestException: unconfigured table schema_keyspaces
    at org.apache.cassandra.thrift.ThriftValidation.validateColumnFamily(ThriftValidation.java:115)
    at org.apache.cassandra.cql3.statements.SelectStatement$RawStatement.prepare(SelectStatement.java:920)
    at org.apache.cassandra.cql3.statements.SelectStatement$RawStatement.prepare(SelectStatement.java:915)
    at org.apache.cassandra.cql3.QueryProcessor.getStatement(QueryProcessor.java:557)
    at org.apache.cassandra.cql3.QueryProcessor.parseStatement(QueryProcessor.java:253)
    at org.apache.cassandra.cql3.QueryProcessor.executeOnceInternal(QueryProcessor.java:354)
    at org.apache.cassandra.schema.LegacySchemaMigrator.query(LegacySchemaMigrator.java:1044)
    at org.apache.cassandra.schema.LegacySchemaMigrator.readSchema(LegacySchemaMigrator.java:173)
    at org.apache.cassandra.schema.LegacySchemaMigrator.migrate(LegacySchemaMigrator.java:77)
    at org.apache.cassandra.service.CassandraDaemon.setup(CassandraDaemon.java:256)
    at org.apache.cassandra.service.CassandraDaemon.init(CassandraDaemon.java:503)
    at org.apache.cassandra.service.EmbeddedCassandraService.start(EmbeddedCassandraService.java:51)
    at com.company.project.schema.cassandra.config.EmbeddedCassandraConfiguration.session(EmbeddedCassandraConfiguration.java:24)
</code></pre>

<p>We're not sure why one module works but the other does not as the cassandra dependencies are identical. Additionally, neither module depends on <a href=""https://stackoverflow.com/questions/34117374/com-datastax-driver-core-exceptions-invalidqueryexception-unconfigured-table-sc"">spring-data-cassandra</a> and both modules are using <a href=""https://stackoverflow.com/questions/31824537/error-unable-to-connect-to-cassandra-server-unconfigured-table"">datastax's 3.3.0 driver</a>. I'm confused as to why the issue occurs in the LegacySchemaMigrator as this EmbeddedCassandraService should be creating the system tables from scratch every time it is started (and there shouldn't be any schema to, well, migrate). Does anyone have any insight as to what may be causing this issue?</p>
",https://stackoverflow.com/questions/45289071/cassandras-embeddedcassandraservice-throws-invalidrequestexception-unconfigure,"['java', 'cassandra', 'datastax-java-driver', 'cassandra-3.0']",558,TRUE,3,1
C# - How to mock this.GetType().Assembly,"<p>In the code I'm working on, I'm forced to test one method where there is a call like this:</p>

<pre><code>this.GetType().Assembly.GetTypes().Where(x =&gt; ...);
</code></pre>

<p>I would like to mock this call so that when the call is made an assembly of my choice is retrieved from <code>this.GetType().Assembly</code>.<br>
In the assembly there will be fake types that I will use for my assertions</p>

<p>The approach I'm trying (still without success) is using shims, as described <a href=""https://msdn.microsoft.com/en-us/library/hh549176.aspx"" rel=""nofollow noreferrer"">here</a>.</p>

<p>Is there a way to achieve my goal?</p>

<p>Finally, note that I know this is not the right approach to do unit testing. Usually the classes I test are made using dependency I can easily mock. This is an exception as this is an implementation of <a href=""https://martinfowler.com/articles/consumerDrivenContracts.html"" rel=""nofollow noreferrer"">Cunsomer-Driven Contracts</a> that is solution-wide and I'm not allowed to change it.</p>
",https://stackoverflow.com/questions/46773835/c-how-to-mock-this-gettype-assembly,"['c#', '.net', 'unit-testing']",1632,TRUE,3,1
F# UnitTesting function with side effect,"<p>I am C# dev that has just starting to learn F# and I have a few questions about unit testing. Let's say I want to the following code:</p>

<pre><code>let input () = Console.In.ReadLine()

type MyType= {Name:string; Coordinate:Coordinate}

let readMyType = 
   input().Split(';') 
   |&gt; fun x -&gt; {Name=x.[1]; Coordinate = {
   Longitude = float(x.[4].Replace("","",""."")) 
   Latitude =float(x.[5].Replace("","","".""))
   }}
</code></pre>

<p>As you can notice, there are a few points to take in consideration:</p>

<ul>
<li>readMyType is calling input() with has a side effect.</li>
<li>readMyType assume many thing on the string read (contains ';' at least 6 columns, some columns are float with ',')</li>
</ul>

<p>I think the way of doing this would be to:</p>

<ul>
<li>inject the input() func as parameter</li>
<li>try to test what we are getting (pattern matching?)</li>
<li>Using NUnit as explained <a href=""https://fsharpforfunandprofit.com/posts/low-risk-ways-to-use-fsharp-at-work-3/#test-other"" rel=""noreferrer"">here</a></li>
</ul>

<p>To be honest I'm just struggling to find an example that is showing me this, in order to learn the syntax and other best practices in F#. So if you could show me the path that would be very great.</p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/45400243/f-unittesting-function-with-side-effect,"['unit-testing', 'f#', 'side-effects', 'purely-functional']",365,TRUE,7,2
Android studio code coverage not showing any Kotlin classes,"<p>I have 2 Kotlin based AS projects. One works fine, the other doesn't. Both have an identical structure and gradle config. I'm using Kotlin 1.1.4-2 with AS 3.0b2. </p>

<p>The problem is that when I run code coverage, the classes I'm testing do not even show up under the coverage report. The only thing I see is R.java and BuildConfig.java, but none of my source files are being found.</p>

<p>All source files are Kotlin based. I'm using Spek for my unit testing. Same setup and versions as my other functional project. I tried using both JaCoCo and Jetbrains code coverage and neither works.</p>

<p>I apologize, I'm not able to embed pictures yet.</p>

<p>This is the problem:</p>

<p><img src=""https://i.stack.imgur.com/ej1IF.png"" alt=""coverage report""></p>

<p>Here's my project structure:</p>

<p><img src=""https://i.stack.imgur.com/gGp9I.png"" alt=""file structure""></p>

<p>And here's my gradle android block:</p>

<pre><code>compileSdkVersion 26
buildToolsVersion ""26.0.1""

defaultConfig {
    minSdkVersion 16
    targetSdkVersion 26
    versionCode 1
    versionName libraryVersion
}

buildTypes {
    debug {
        testCoverageEnabled = true
    }
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
</code></pre>

<p>and my dependencies:</p>

<pre><code>implementation fileTree(dir: 'libs', include: ['*.jar'])

implementation ""org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version""
implementation ""io.reactivex.rxjava2:rxkotlin:2.1.0""

testImplementation 'junit:junit:4.12'
testImplementation ""org.jetbrains.kotlin:kotlin-test:$kotlin_version""
testImplementation 'org.jetbrains.spek:spek-api:1.1.2'
testImplementation 'org.jetbrains.spek:spek-junit-platform-engine:1.1.2'
testImplementation 'org.junit.platform:junit-platform-runner:1.0.0-M4'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.0.0-M4'

implementation 'com.android.support:appcompat-v7:26.0.1'

implementation 'com.squareup.okhttp3:okhttp-ws:3.3.1'
implementation 'com.google.protobuf:protobuf-java:2.6.1'
</code></pre>

<p>I've tried running </p>

<pre><code>task copyTestClasses(type: Copy) {
  from ""build/tmp/kotlin-classes/debugUnitTest""
  into ""build/intermediates/classes/debug""
}

task copySdkClasses(type: Copy) {
  from ""build/tmp/kotlin-classes/debug""
  into ""build/intermediates/classes/debug""
}
</code></pre>

<p>before my testing and that doesn't work either.</p>

<p>What's strange is my other project, using the same AS version, Kotlin version, and project structure, is working fine and generating proper code coverage. </p>

<p>Any help would be appreciated.</p>
",https://stackoverflow.com/questions/45825130/android-studio-code-coverage-not-showing-any-kotlin-classes,"['android', 'android-studio', 'unit-testing', 'kotlin', 'code-coverage']",11088,TRUE,24,2
is laravel cloning my mock object?,"<p>Im testing a Soap web service with <code>getMockFromWsdl</code> from phpunit, for unit testing within laravel works fine, but when I try to replace the SoapClient in a feature test, it always fails, like the web service never called, but actually the mock is called. </p>

<p>I suspect that laravel is cloning somewhere my <code>$this-&gt;soapClient</code> because if I debug the code, it calls the soap mock and gets what is faked in the mock but always receive the error:</p>

<pre><code>Expectation failed for method name is equal to &lt;string:GetToken&gt; when invoked at least once.
Expected invocation at least once but it never occurred.
</code></pre>

<p>My code is like:
</p>

<pre><code>public function test_soap_call()
{
    $this-&gt;soapClient = $this-&gt;getMockFromWsdl(dirname(__FILE__).'/../Mocks/service.wsdl');

    $this-&gt;soapClient-&gt;expects($this-&gt;atLeastOnce())
        -&gt;method('GetToken')
        -&gt;with(['Code' =&gt; '03600', 'User' =&gt; 'username'])
        -&gt;willReturn(unserialize('O:8:""stdClass"":1:{s:26:""GetTokenResult"";s:36:""5aae60ec-2bcd-459d-a135-a20eb7c10007"";}'));

    $this-&gt;app-&gt;instance('MySoapClient', $this-&gt;soapClient);

    $this-&gt;postJson('/api/order', $this-&gt;getValidRequest());

}
</code></pre>

<p>and in my controller (<code>/api/order</code>) I have
</p>

<pre><code>$soap = $this-&gt;app-&gt;make('MySoapClient');
$soap-&gt;GetToken(['Code' =&gt; '03600', 'User' =&gt; 'username']);
</code></pre>

<p>Am I using correctly the Laravel Service Container?</p>

<p>PD: Something similar happened to me, when doing a Spy and using <code>$app-&gt;instance</code>, where I was trying to get what was passed to an object, but always got null. I solved it declaring the field of the spy static.</p>
",https://stackoverflow.com/questions/43121198/is-laravel-cloning-my-mock-object,"['laravel', 'unit-testing', 'testing', 'laravel-5', 'phpunit']",214,TRUE,2,1
How to correctly setup my post-build script in visual studio,"<p>So I'm currently trying to build a .lib file out of my exe utilizing visual studio build scripts as suggested by the accepted answer to this post: <a href=""https://stackoverflow.com/questions/19496305/linking-to-multiple-obj-for-unit-testing-a-console-application/19710979#19710979"">Linking to multiple .obj for unit testing a console application</a>. Basically, the post-build script they recommend to place within my project's post-build event is: </p>

<pre><code>lib /NOLOGO /OUT:""$(TargetPath).lib"" ""$(ProjectDir)\$(Configuration)\*.obj""
</code></pre>

<p>Here's what my current directory structure looks like:</p>

<pre><code>-Solution
   - Project 
      -Source
         .cpp files
   - ProjectTester
   - Solution.sln
</code></pre>

<p>So my command looks like this: </p>

<pre><code>lib /NOLOGO /OUT:""$(TargetPath).lib"" ""$(ProjectDir)\Source\*.obj""
</code></pre>

<p>This currently does nothing, as though visual studio is ignoring this build script completely. My quesitons are:</p>

<p>What exactly does $(TargetPath).lib resolve to? </p>

<p>and</p>

<p>Is my current understanding of this build script correct? If so, how do I change this script to do what I want?</p>

<p>Update: </p>

<p>I've changed a few spaces in the target path and now I get an <code>LNK1146 no argument specified with option /OUT:</code> error. </p>
",https://stackoverflow.com/questions/43035979/how-to-correctly-setup-my-post-build-script-in-visual-studio,"['c++', 'visual-studio', 'build-script']",2924,TRUE,2,1
How to develop an external reusable Symfony 3 Bundle,"<p>I'd like to develop a reusable external Symfony 3 bundle installable with composer. I understood how to use composer to install a ""private"" vendor through a personal git repository, but I can't figure it out how to setup the environment for the development of the library/bundle.</p>

<p>Should I create an empty Symfony project to reproduce the environment and developing my library/bundle with only it under git versioning?
'Couse it doesn't sound like a good idea to me.
Or should I develop the library/bundle as it is and relay only on Unit Testing? Or, worse, should I develop the library/bundle, pushing to the develop branch and pulling it in my current project under develop?</p>

<p>I think that I'm too far way from the right answer.
Please, show me the right way.
Thanks.</p>
",https://stackoverflow.com/questions/41917165/how-to-develop-an-external-reusable-symfony-3-bundle,"['php', 'composer-php', 'bundle', 'symfony']",1172,FALSE,2,2
When do I need to use beforeEach block in Jasmine?,"<p>I just started learning unit testing using Jasmine. I have gone through the <a href=""https://jasmine.github.io/2.0/introduction.html?"" rel=""nofollow noreferrer"">official documentation</a> of jasmine and searched a lot over stackoverflow. Please see the below code.  </p>

<pre><code>describe('calculator', function () {
  var calculator;
  beforeEach( function(){
    calculator = new myApp.Calculator();
  });

  describe('sum', function () {
    it('1 + 1 should equal 2', function () {
        expect(calculator.add(1, 1)).toBe(2);
    }); 
  });

  describe('subtract', function () {
    it('3 - 2 should equal 1', function () {
        expect(calculator.subtract(3, 2)).toBe(1);
    });
  });

});
</code></pre>

<p>Here I have initialized/created the instance of Calculator in the <code>beforeEach</code> block. It also works fine if I write it directly inside the first <code>describe</code> block without using the <code>beforeEach</code> block.  </p>

<p>I understand the user of <code>beforeEach</code> and <code>afterEach</code>. But here in this case(or for any such cases) do I really need to use <code>beforeEach</code> where no one is updating the <code>Calculator</code> instance, in each spec we are just using the methods of <code>calculator</code>? If I use <code>beforeEach</code>, it will create new instance everytime before each test. But why do I need a new instance always where none of my testcase is not going to change/ update my instance?</p>
",https://stackoverflow.com/questions/43581483/when-do-i-need-to-use-beforeeach-block-in-jasmine,"['javascript', 'unit-testing', 'jasmine']",1135,TRUE,2,1
Using App.config in unit Test,"<p>We are developing a c# web application in which we are using some third party libs which are referencing different versions of Newtonsoft. 
In the web.config we have the same config section as in the example below. It works as expected.</p>

<p>But when we try to execute the unit test we get following error:</p>

<p><strong>System.IO.FileLoadException : Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)</strong></p>

<p>In our Visual Studio solution we have multiple projects for unit testing. I have created a app.config file (content below). This file is renamed and copied to the output folder during build.</p>

<p>Do I have to do this for every test project?</p>

<p>App.config</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""utf-8"" ?&gt;
&lt;configuration&gt;
  &lt;runtime&gt;
    &lt;assemblyBinding&gt;
      &lt;dependentAssembly&gt;
        &lt;assemblyIdentity name=""Newtonsoft.Json"" publicKeyToken=""30ad4fe6b2a6aeed""/&gt;
        &lt;bindingRedirect oldVersion=""1.0.0.0-9.0.0.0"" newVersion=""9.0.0.0""/&gt;
      &lt;/dependentAssembly&gt;
    &lt;/assemblyBinding&gt;
  &lt;/runtime&gt;
&lt;/configuration&gt;
</code></pre>
",https://stackoverflow.com/questions/41956723/using-app-config-in-unit-test,"['c#', '.net', 'unit-testing', 'nunit']",2496,FALSE,2,0
Java support for json testing?,"<p>I am using <code>morphia</code> (ODM for <code>mongodb</code>) in my project and write its annotations on my models.<br>
I want to write unit tests to validate the mapping.<br>
I can call the mapper, using <code>morphia.getMapper().toDBObject(input)</code> and run a test on the output.<br>
For example, for the model</p>

<p>Car:</p>

<pre><code>@Property(""COLOR"")
String color;
@Property(""PlaTE"")
int plate;
@Property(""seats"")
int seats;
</code></pre>

<p>I expect to receive the output:</p>

<pre><code>{ ""COLOR"" : ""value"", ""PlaTE"" : 111, ""seats"" : 4 }
</code></pre>

<p>In order to test it, I need to create a string that represent this output, and in java it's a nightmare...</p>

<pre><code>String expected = ""{ \""COLOR\"": \""value\"", \""PlaTE\"": 111, \""seats\"" }"";
</code></pre>

<p>And you can see how ugly this can get with embedded objects and arrays...  </p>

<p>I was thinking of writing the output in a <code>json</code> file and read it during the test, but it kinda breaks the rules of unit testing...<br>
Is there any convenient way of representing json objects in java to achieve a neat and clean unit tests?</p>
",https://stackoverflow.com/questions/42374231/java-support-for-json-testing,"['java', 'json', 'unit-testing']",894,FALSE,2,1
When does Angular4 HttpClient.get() return undefined?,"<p>I am trying to test an HttpInterceptor in Angular 4. I find that when I call HttpClient.get(), it errors</p>

<p>TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.</p>

<p>When does http.get('/data') return undefined?</p>

<p><a href=""http://plnkr.co/edit/AkivQzoJeJbDbv3J0Rsh?p=preview"" rel=""nofollow noreferrer"">Plunkr here</a></p>

<pre><code>import { Injectable } from '@angular/core';
import { TestBed, async, inject } from '@angular/core/testing';
import { HttpClient, HttpClientModule, HttpHandler } from '@angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import 'rxjs/add/operator/toPromise';


describe('AppComponent', () =&gt; {
    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            imports: [HttpClientTestingModule, HttpClientModule],
            providers: [ HttpClient, HttpHandler,
              // {
              //     provide: HTTP_INTERCEPTORS,
              //     useClass: AuthErrorHttpInterceptorService,
              //     multi: true
              // }
            ]
        }).compileComponents();
    }));



    it('adding header test', inject([HttpClient], (http: HttpClient) =&gt; {
        debugger;
        const httpMock = TestBed.get(HttpTestingController);

        // Make an HTTP GET request, and expect that it return an object
        // of the form {name: 'Test Data'}.
        http.get('/data')
            .subscribe(data =&gt; expect(data['name']).toEqual('Test Data'));

        // At this point, the request is pending, and no response has been
        // sent. The next step is to expect that the request happened.
        const req = httpMock.expectOne('/data');

        // If no request with that URL was made, or if multiple requests match,
        // expectOne() would throw. However this test makes only one request to
        // this URL, so it will match and return a mock request. The mock request
        // can be used to deliver a response or make assertions against the
        // request. In this case, the test asserts that the request is a GET.
        expect(req.request.method).toEqual('GET');

        // Next, fulfill the request by transmitting a response.
        req.flush({name: 'Test Data'});

        // Finally, assert that there are no outstanding requests.
        httpMock.verify();
    }));
});
</code></pre>

<p>TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.</p>

<p>Edit: I have seen question <a href=""https://stackoverflow.com/questions/45326952/error-while-unit-testing-httpclientmodule-angular-4-3/45331211#45331211"">Error while unit testing HttpClientModule (Angular 4.3+)</a> and imported HttpClientModule but i still get the error. Also I am not including my interceptor component until i fix this error so there issue can't be there.</p>

<p>Edit: <code>const req = httpMock.expectOne('/data');</code> this line never executes because the error is thrown from the line above</p>

<p>Edit: solution was to remove 'HttpClient, HttpHandler' from the providers array</p>
",https://stackoverflow.com/questions/46402991/when-does-angular4-httpclient-get-return-undefined,"['angular', 'typescript', 'angular-http-interceptors']",2202,TRUE,2,1
HTML Code Coverage Report with Visual C++ and Catch,"<p>I have a C++ project which uses cmake to build for Unix with gcc and Windows with Visual Studio. The project uses the Catch unit testing framework (<a href=""https://github.com/philsquared/Catch"" rel=""nofollow noreferrer"">https://github.com/philsquared/Catch</a>)</p>

<p>Now for Unix I can create a HTML code coverage report with gcov/lcov.</p>

<p>Does anyone know a similar tool like gcov and lcov that can be used to create HTML code coverage reports under Windows with the Microsoft compiler? It must work with the MSBuild system on the console and should not rely on an installed Visual Studio, so it can be used on a build server.</p>

<p>I am aware of the possibility to use things like Cygwin, MinGW or MSYS2 but I was hoping there is something that can be used with the MS C++ compiler and the MSBuild system.</p>
",https://stackoverflow.com/questions/43506296/html-code-coverage-report-with-visual-c-and-catch,"['c++', 'visual-studio', 'unit-testing', 'code-coverage']",510,FALSE,2,0
Azure C# EventHubClient mock for unit test,"<p>I am writing an event publisher for our application which internally uses <a href=""https://learn.microsoft.com/en-us/dotnet/api/microsoft.servicebus.messaging.eventhubclient?view=azureservicebus-4.0.0"" rel=""noreferrer"">Azure C# EventHubClient</a>. </p>

<p>I want to unit test that my event gets translated correctly into EventData object (Properties + Body) as well as some other features. Long story short, I need some way to create a mock for EventHubClient. Unfortunately, there does not seem to be a simple way of doing that:</p>

<ul>
<li>EventHubClient does not implement any relevant interface so using something like Moq or NSubstitute to create a mock will not work.</li>
<li>EventHubClient is an abstract class with internal constructor so I cannot extend it and create a custom mock.</li>
</ul>

<p>In theory, I could create a wrapper interface and class around the methods I want to use, but it means having more code to maintain. Does anybody know about a better way of unit testing with EventHubClient?</p>
",https://stackoverflow.com/questions/45052100/azure-c-eventhubclient-mock-for-unit-test,"['c#', 'unit-testing', 'azure-eventhub']",5345,TRUE,6,1
Is it possible to mock custom Angular 2 Material SVG icons for unit tests?,"<p>In my app's root component, I am defining custom SVG icons for <code>md-icon</code>. When unit testing a component that displays the custom icon I get an error. It seems that the error is likely due to the fact that my root component is not being used/initialized in my child unit test.</p>

<p>Is there a way to mock or add these custom icons (or <code>md-icon</code>) when setting up the test module? I would simply define the icons in the component I am testing, but I know other components will need them also.</p>

<p>The error:</p>

<pre><code>Uncaught Error: Error in ./CustomerComponent class CustomerComponent - inline template:34:19 caused by: __WEBPACK_IMPORTED_MODULE_4_rxjs_Observable__.Observable.throw is not a function
</code></pre>

<p>Full error: <a href=""https://i.stack.imgur.com/Dj8I5.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/Dj8I5.png"" alt=""enter image description here""></a></p>

<p>Removing the custom icons from the template solves the error.</p>

<hr>

<p>My template is using the custom icons like this:</p>

<pre><code>&lt;md-icon svgIcon=""vip""&gt;vip&lt;/md-icon&gt;
</code></pre>

<p>And the root component initializes the icons like this:</p>

<pre><code>this.iconRegistry.addSvgIcon(
    'vip',
    this.sanitizer.bypassSecurityTrustResourceUrl('assets/icons/vip.svg') as string,
);
</code></pre>

<p>I set up the test component like this:</p>

<pre><code>beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
        imports: [
            SharedModule,
            CoreModule,
            FormsModule,
            ReactiveFormsModule,
        ],
        providers: [
            {
                provide: Router,
                useClass: class {
                    navigate = jasmine.createSpy('navigate');
                },
            },
            {
                provide: ActivatedRoute,
                useValue: {
                    data: {
                        subscribe: (fn: (value: Data) =&gt; void) =&gt; fn({
                            customer: CUSTOMER,
                            company: COMPANY,
                        }),
                    },
                },
            },
            {
                provide: UtilityService,
                useClass: UtilityServiceMock,
            },
            // etc...
        ],
        declarations: [
            CustomerComponent,
        ],
        schemas: [
            CUSTOM_ELEMENTS_SCHEMA,
        ],
    })
    .compileComponents();
}));
</code></pre>

<h3>Versions</h3>

<ul>
<li>Angular 2.3.0</li>
<li>Material 2.0.0-beta.1</li>
</ul>
",https://stackoverflow.com/questions/41575554/is-it-possible-to-mock-custom-angular-2-material-svg-icons-for-unit-tests,"['unit-testing', 'angular', 'angular-material2']",3767,TRUE,6,4
MVC Mocking (Moq) - HttpContext.Current.Server.MapPath,"<p>I have a method I am attempting to Unit Test which makes use of <strong>HttpContext.Current.Server.MapPath</strong> as well as <strong>File.ReadAllLines</strong> as follows:</p>

<pre><code>public List&lt;ProductItem&gt; GetAllProductsFromCSV()
{
    var productFilePath = HttpContext.Current.Server.MapPath(@""~/CSV/products.csv"");

    String[] csvData = File.ReadAllLines(productFilePath);

    List&lt;ProductItem&gt; result = new List&lt;ProductItem&gt;();

    foreach (string csvrow in csvData)
    {
        var fields = csvrow.Split(',');
        ProductItem prod = new ProductItem()
        {
            ID = Convert.ToInt32(fields[0]),
            Description = fields[1],
            Item = fields[2][0],
            Price = Convert.ToDecimal(fields[3]),
            ImagePath = fields[4],
            Barcode = fields[5]
        };
        result.Add(prod);
    }
    return result;
}
</code></pre>

<p>I have a Unit Test setup which (as expected) fails:</p>

<pre><code>[TestMethod()]
public void ProductCSVfileReturnsResult()
{
    ProductsCSV productCSV = new ProductsCSV();
    List&lt;ProductItem&gt; result = productCSV.GetAllProductsFromCSV();
    Assert.IsNotNull(result);
}
</code></pre>

<p>I have since done a lot of reading on Moq and Dependancy Injection which I just dont seem to be able to implement. I have also seen a few handy answers on SO  such as: <a href=""https://stackoverflow.com/questions/38452743/how-to-avoid-httpcontext-server-mappath-for-unit-testing-purposes/38456288#38456288"">How to avoid HttpContext.Server.MapPath for Unit Testing Purposes</a> however I am just unable to follow it for my actual example.</p>

<p>I am hoping someone is able to take a look at this and tell me exactly how I might go about implementing a successful test for this method. I feel I have a lot of the background required but am unable to pull it all together.</p>
",https://stackoverflow.com/questions/45531795/mvc-mocking-moq-httpcontext-current-server-mappath,"['c#', 'unit-testing', 'dependency-injection', 'moq', 'httpcontext']",999,TRUE,1,2
Unexpected Sinon.js behaviour,"<p>I'm trying to stub the <a href=""https://github.com/stripe/stripe-node"" rel=""nofollow noreferrer"">Stripe</a> module for unit testing using <a href=""https://github.com/mochajs/mocha"" rel=""nofollow noreferrer"">Mocha</a> and <a href=""https://github.com/sinonjs/sinon"" rel=""nofollow noreferrer"">Sinon.js</a>.</p>

<p>I require Stripe like this :</p>

<pre><code>const stripe = require('stripe');
const stubbedStripeClient = stripe.Stripe('test');
</code></pre>

<p>At the root of my tests (inside my top-level <code>describe()</code>) I have this :</p>

<pre><code>before('stub root', () =&gt; {
  sinon.stub(stripe, 'Stripe').returns(stubbedStripeClient);
});
</code></pre>

<p>Then, in the <code>describe()</code> block where I actually would call a Stripe method, I have this <code>before()</code> hook :</p>

<pre><code>let stub;
before('stub', () =&gt; {
  console.log(typeof stubbedStripeClient.customers.create);
  stub = sinon.stub(stubbedStripeClient.customers, 'create', ({id: 'a-stripe-customer-id'}));
});
</code></pre>

<p>This is where I don't understand what happens. The first line in the hook (<code>console.log</code>) outputs:</p>

<blockquote>
  <p>function</p>
</blockquote>

<p>The second line throws this exception :</p>

<blockquote>
  <p>TypeError: Attempted to wrap undefined property create as function</p>
</blockquote>

<p>How is this possible? How can it be a function on one line and be undefined on the very next line?</p>

<p>I looked at the Sinon.js source, and this check is performed <a href=""https://github.com/sinonjs/sinon/blob/6b13ed766b844a15fe7fd03bedd289e4fa6e84eb/lib/sinon/util/core/wrap-method.js#L35"" rel=""nofollow noreferrer"">here</a>. If I then look at their <a href=""https://github.com/sinonjs/sinon/blob/6b13ed766b844a15fe7fd03bedd289e4fa6e84eb/lib/sinon/util/core/wrap-method.js#L8"" rel=""nofollow noreferrer""><code>isFunction</code></a> function, it performs the same check I have in my <code>console.log</code>. I'm puzzled.</p>
",https://stackoverflow.com/questions/43925145/unexpected-sinon-js-behaviour,"['javascript', 'node.js', 'sinon']",198,TRUE,1,1
Unable to open SQLite database in golang: &quot;unable to open database file [recovered]&quot;-error,"<p>I am just starting learning golang and am not sure if my error is conceptual or with the language. </p>

<p>It is peculiar, because the error only occurs, when unit-testing my code. If I ""go run"" everything works fine. As a sqlite-driver I use <a href=""http://github.com/mattn/go-sqlite3"" rel=""nofollow noreferrer"">mattn/go-sqlite3</a>.</p>

<p>Here is where the problem occurs:</p>

<pre><code>    func dbExec(command *string) {
    db, err := sql.Open(""sqlite3"", dbPath) // Path and driver are set correcrtly
    defer db.Close()
    if err != nil { //No problem here
        panic(err)
    }
    _, err = db.Exec(*command)
    if err != nil { //Here the errorNo14 ""Unable to open the database file"" occurs
        panic(err)
    }
 }
</code></pre>

<p>So it seems to me, that the database file can be found, but it can't be open because of other limits. I have no concurrency in all of my code. I have only one test-method so far, so even if the testing would be done concurrently, it would so far be only one thread. Maybe someone has an idea! The problem seems to basic, there really is not much more to my code then this.</p>
",https://stackoverflow.com/questions/47744451/unable-to-open-sqlite-database-in-golang-unable-to-open-database-file-recover,"['unit-testing', 'go', 'sqlite']",3291,TRUE,1,1
How do I use a Chai plugin like chai-date-string with Karma/Mocha/Chai?,"<p>Should be able to use any Chai plugin with unit testing with Karma/Mocha and Chai, or does it need to be converted into a special karma compatible plugin?</p>

<p>I'd like to use <a href=""http://chaijs.com/plugins/chai-date-string/"" rel=""nofollow noreferrer"">chai-date-string</a> to do something like <code>expect(requestBody.time).to.be.a.dateString();</code>, but didn't have any luck just installing them as an NPM module and requiring them in my test file.</p>

<p>Then I came across <a href=""https://www.npmjs.com/package/karma-chai-plugins"" rel=""nofollow noreferrer"">karma-chai-plugins</a>, which I thought was designed to use other chai plugins (even beyond the few that it comes bundled with), but adding that as an NPM module, and then adding the Chai plugin name to the frameworks list, but this didn't work.</p>

<p>My <code>karma.conf.js</code>:</p>

<pre><code>module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ['mocha', 'chai', 'chai-date-string', 'sinon-chai', 'browserify'],
    client: { chai: { includeStack: true } },
    files: [ 'playmob.js', 'test/**/*_test.js' ],
    preprocessors: {
      'test/**/*.js': [ 'browserify' ]
    },
    browserify: {
      debug: true,
    },
    exclude: [ ],
    reporters: ['mocha', 'beep'],
    mochaReporter: { ignoreSkipped: true },
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['ChromeHeadless'],
    singleRun: false,
    concurrency: Infinity
  })
}
</code></pre>

<p>Versions in <code>package.json</code> (I had to explicitly install a newer version of <code>chai-as-promised</code> to get around a dependency problem):</p>

<pre><code>  ""devDependencies"": {
    ""browserify"": ""^14.4.0"",
    ""chai"": ""^4.1.2"",
    ""chai-as-promised"": ""^7.1.1"",
    ""chai-date-string"": ""^0.1.0"",
    ""karma"": ""^1.7.1"",
    ""karma-beep-reporter"": ""^0.1.4"",
    ""karma-browserify"": ""^5.1.1"",
    ""karma-chai-plugins"": ""^0.9.0"",
    ""karma-chrome-launcher"": ""^2.2.0"",
    ""karma-cli"": ""^1.0.1"",
    ""karma-mocha"": ""^1.3.0"",
    ""karma-mocha-reporter"": ""^2.2.4"",
    ""karma-sinon-chai"": ""^1.3.2"",
    ""mocha"": ""^3.5.3"",
    ""sinon"": ""^2.4.1"",
    ""sinon-chai"": ""^2.14.0"",
    ""uglifyjs"": ""^2.4.11"",
    ""url"": ""^0.11.0"",
    ""watchify"": ""^3.9.0""
  }
</code></pre>

<p>Results in the following error:</p>

<pre><code>&gt; playmobjs@0.2.0 test /Users/jschuur/Code/Playmob/js_api_lib
&gt; karma start

/Users/jschuur/Code/Playmob/js_api_lib/node_modules/di/lib/injector.js:9
      throw error('No provider for ""' + name + '""!');
      ^

Error: No provider for ""framework:chai-date-string""! (Resolving: framework:chai-date-string)
    at error (/Users/jschuur/Code/Playmob/js_api_lib/node_modules/di/lib/injector.js:22:12)
</code></pre>
",https://stackoverflow.com/questions/46542078/how-do-i-use-a-chai-plugin-like-chai-date-string-with-karma-mocha-chai,"['unit-testing', 'karma-runner', 'chai']",743,TRUE,1,1
Sinon spy for named exports in ES6,"<p>I use <code>enzyme</code> with <code>sinon</code> for unit testing React components. Normally, when it comes to testing instance methods I just spy on the method on instance of the component and assert respectively. </p>

<p>However, I have this global function that I use in many components of the app, which is a named export. <code>sinon</code> throws if I try to spy on that.</p>

<pre><code>import { openModel } from '../global/handlers/';

&lt;Block
   onRemove={(data) =&gt; openModal(...args)}
/&gt;
</code></pre>

<p>So, currently I am calling prop method <code>onRemove</code> to assert that <code>openModal</code> gets called with the arguments but I can't really spy on the exported method i.e. <code>openModal</code>. </p>

<p>I understand that I need to provide a context to this function to be able to spy on the underlying function but I am not really sure what's the preferred way of doing something like this. </p>

<p>PS: I would be happy to provide more details if need be.</p>
",https://stackoverflow.com/questions/44334837/sinon-spy-for-named-exports-in-es6,"['unit-testing', 'reactjs', 'sinon', 'enzyme']",258,FALSE,1,1
PHPUnit - ReturnValueMap of Mocks not finding Mocked Class Methods,"<p>I'm new to unit testing and have come across something I don't understand when using <code>returnValueMap()</code> in PHPUnit. I've been googling for days now ...</p>

<p>Consider this code under test;</p>

<pre><code>public function __construct(EntityManager $entityManager, AuditLog $auditLog) {
    $this-&gt;entityManager = $entityManager;
    $this-&gt;auditLog = $auditLog;
}

public function updateSomeId($oldId, $newId)
{
    $repositories = ['repo1', 'repo2', 'repo3'];

    foreach ($repositories as $repository) {
        try {
            $this-&gt;entityManager-&gt;getRepository($repository)
                -&gt;updateSomeId($oldId, $newId);

        } catch (RepositoryException $e) {
            throw new SomeOtherException($e-&gt;getMessage(), $e-&gt;getCode(), $e);
        }
    }
}
</code></pre>

<p>The unit test code;</p>

<pre><code>... code removed for brevity

    $repoMaintenance = new RepoMaintenance(
        $this-&gt;getEntityManagerMock(),
        $this-&gt;getAuditLogMock()
    );

    $this-&gt;assertTrue($repoMaintenance-&gt;updateSomeId(
        $this-&gt;oldId,
        $this-&gt;newId
    ));

/**
 * @return EntityManager
 */
private function getEntityManagerMock()
{
    $entityManagerMock = $this-&gt;getMockBuilder(EntityManager::class)
        -&gt;disableOriginalConstructor()
        -&gt;getMock();

    $entityManagerMock
        -&gt;method('getRepository')
        -&gt;willReturn($this-&gt;returnValueMap($this-&gt;getEntityManagerReturnValueMap()));

    return $entityManagerMock;
}

/**
 * @return array
 */
private function getEntityManagerReturnValueMap()
{
    return [
        ['repo1', $this-&gt;getRepo1Mock()],
        ['repo2', $this-&gt;getRepo2Mock()],
        ['repo3', $this-&gt;getRepo3Mock()],
    ];
}

/**
 * @return Repo1
 */
private function getRepo1Mock()
{
    return $this-&gt;getMockBuilder(Repo1::class)
        -&gt;disableOriginalConstructor()
        -&gt;getMock();
}

... Code removed for brevity
</code></pre>

<p>When the unit test is run, the following fatal error is returned;</p>

<p><code>PHP Fatal error:  Call to undefined method PHPUnit_Framework_MockObject_Stub_ReturnValueMap::updateSomeId()</code></p>

<p>I've previously used mocks in return value maps with no issue accessing methods in a public context. The difference is I'm attempting to mock <code>__construct()</code> variables, which are set to <code>private</code> access within the SUT.</p>

<p>What am I missing? The problem (I would naively guess) is with the private access level of the members being mocked.</p>

<p>Is there a way to unit test this code? I don't want to hit the database at any point and this is the reason for mocking the calls to it.</p>
",https://stackoverflow.com/questions/45500935/phpunit-returnvaluemap-of-mocks-not-finding-mocked-class-methods,"['php', 'unit-testing', 'mocking', 'phpunit']",327,TRUE,1,1
PESTER - can i use it for powershell workflows?,"<p>Friends,
I am automating some infra related stuffs using powershell and converting that to workflows and running in SMA (Service Management Automation). </p>

<p>Lets say if I have to automate some linux and windows machine storage addition, they I create 1 main.ps1 workflow and call two child workflow's windows.ps1 and linux.ps1, 1 each for windows and linux storage addition. I have to put those 3 files in SMA and run them. Before that I wanted to test the whole automation functionality.</p>

<p>As per my knowledge pester is best fit for unit testing, i.e., each 3 files testing using pester separately.</p>

<p>My questions is, can i use pester in main.ps1 files and test the work flow in SMA? if not, do you suggest any best open-source tool for this?</p>

<p>Thanks !</p>
",https://stackoverflow.com/questions/46154680/pester-can-i-use-it-for-powershell-workflows,"['automation', 'pester', 'powershell-workflow']",123,FALSE,1,0
How to use PowerShell multithreading and still unit test with Pester Mocks,"<p>I'm trying to do a simple parallel operation in Powershell.  I am using PoshRSJobs for multithreading, though I have also tried Invoke-Parallel with the same issue. 
 I need to call a couple of my own functions in the scriptbody of the job, but this does not allow me to MOCK those functions for unit testing (they end up being the original non-mocked functions).  At this point, I'm just trying to assert that they have been called the correct number of times.</p>

<p>Here is the original class (the functionality of the imported modules are irrelevant - the actual implementations are currently returning test strings)...</p>

<pre><code>Import-Module $PSScriptRoot\Convert-DataTable
Import-Module $PSScriptRoot\Get-History
Import-Module $PSScriptRoot\Get-Assets
Import-Module $PSScriptRoot\Write-DataTable

function MyStuff (
    param(
        [string]$serverInstance = ""localhost\SQLEXPRESS"", 
        [string]$database = ""PTLPowerShell"",
        [string]$tableName = ""Test""
    )
    $assets = Get-Assets
    $full_dt = New-Object System.Data.DataTable
    $assets | Start-RSJob -ModulesToImport $PSScriptRoot\Convert-FLToDataTable, $PSScriptRoot\Get-FLHistory {
        $history = Get-History $asset
        $history_dt = Convert-DataTable $history
        return $history_dt.Rows
    } | Wait-RSJob | Receive-RSJob | ForEach { 
        $full_dt.Rows.Add($_) 
    }
    Write-DataTable $serverInstance $database $tableName $full_dt
}
</code></pre>

<p>Here is the Pester test...</p>

<pre><code>$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
. ""$here\$sut""

Describe ""MyStuff"" {
    BeforeEach {
        Mock Get-Assets { return ""page1"", ""page2""}
        Mock Get-History { return ""history"" }
        Mock Convert-DataTable { 
            $historyDT = New-Object System.Data.Datatable;
            $historyDT.TableName = 'Test'
            return ,$historyDT
        }
        Mock Write-DataTable {}
    }
    It ""should do something"" {
        { MyStuff } | Should -Not -Throw;
    }
    It ""should call Get-FLAssetGrid"" {
        Assert-MockCalled Get-Assets 1
    }
    It ""should call Get-FLHistory"" {
        Assert-MockCalled Get-History 2
    }
    It ""should call Convert-DataTable"" {
        Assert-MockCalled Convert-DataTable 2
    }
    It ""should call Write-DataTable"" {
        Assert-MockCalled Write-DataTable 1
    }
}
</code></pre>

<p>Here is the Pester test's output currently...</p>

<pre><code>Describing MyStuff
  [+] should do something 1.71s
  [+] should call Get-Assets 211ms
  [-] should call Get-History 61ms
    Expected Get-History to be called at least 2 times but was called 0 times
    23:         Assert-MockCalled Get-History 2
    at &lt;ScriptBlock&gt;, myFile.Tests.ps1: line 23
  [-] should call Convert-DataTable 110ms
    Expected Convert-DataTable to be called at least 2 times but was called 0 times
    26:         Assert-MockCalled Convert-DataTable 2
    at &lt;ScriptBlock&gt;, myFile.Tests.ps1: line 26
  [+] should call Write-DataTable 91ms
</code></pre>

<p>So ultimately, <strong>I'm looking for a way to do parallel operations in PowerShell and still be able to mock and unit test them.</strong></p>
",https://stackoverflow.com/questions/47913985/how-to-use-powershell-multithreading-and-still-unit-test-with-pester-mocks,"['multithreading', 'powershell', 'mocking', 'pester']",598,TRUE,5,2
Unit test karma with browser phantomJS doesn&#39;t support import inheritance,"<p>I met this issue when unit testing with phantomjs. That's I think the browser phantomjs doesn't support import inheritance. Here is the issue detail:</p>

<p>Environment:</p>

<ul>
<li>karma 1.5.0</li>
<li>phantomjs: 2.1.1 (using as browser)</li>
</ul>

<p>And I have these model classes:</p>

<p><strong><em>base.model.ts</em></strong></p>

<pre><code>export class BaseModel {
    id?: number;
    name?: string;
}
</code></pre>

<p><strong><em>customer.model.ts</em></strong></p>

<pre><code>import { BaseModel  } from './base.model';

export class CustomerModel extends  BaseModel {
    address?: string;
    // more properties defined
}
</code></pre>

<p><strong><em>home.model.ts</em></strong></p>

<pre><code>import { BaseModel  } from './base.model';
import { CustomerModel } from './customer.model';

export class HomeModel extends  BaseModel {
    param1: CustomerModel;

    constructor(data?: any) { // write some logic in here }
}
</code></pre>

<p><strong><em>home.service.ts</em></strong></p>

<pre><code>import { Injectable } from '@angular/core';
import { Home } from './home.model';

@Injectable()
export class HomeService {
    constructor(){  }

    get() {
        let home = new HomeModel();
    }
}
</code></pre>

<p><strong>Steps to reproduce the behaviour</strong></p>

<ol>
<li>Write the unit test for function get() of HomeService
(home.service.ts)</li>
<li>Run the unit test: <code>npm run test</code> will excute <code>karma start config/karma.conf.js</code></li>
</ol>

<p><strong>Error</strong></p>

<blockquote>
  <p>PhantomJS 2.1.1 (Windows 8 0.0.0) 
  ERROR TypeError: undefined: can't set as prototype!</p>
</blockquote>

<p><strong>Root cause</strong>:
After days of investigating, I have found that the issue just happend when unit test going through <code>new HomeModel()</code>. And then its related to the <code>BaseModel</code> with <code>extends</code>, I think when we <code>new HomeModel()</code>, it initialized the the <code>BaseModel</code> first (import will run from top to bottom), then <code>CustomerModel</code> is initialized after that. In <code>CustomerModel</code>, it still have import <code>BaseModel</code> to <code>extends</code>.</p>
",https://stackoverflow.com/questions/43107688/unit-test-karma-with-browser-phantomjs-doesnt-support-import-inheritance,"['inheritance', 'phantomjs', 'karma-jasmine']",401,TRUE,0,1
Using sinon to mock a date object,"<p>Here is my code:</p>

<pre><code>var startTime = new Date(startDateTime).toLocaleTimeString(""en-US"", options);
</code></pre>

<p>I need to get that <code>startTime</code> in my unit test. From knowing unit testing in a java perspective, I would approach this problem as <em>How can I mock the new date constructor?</em> and then <em>How can I mock the toLocaleTimeString function call?</em>. However, I'm not sure that that's the way to approach this problem in javascript.</p>

<p>I've tried several things including sinon's useFakeTimers, but I don't think that's relevant as I'm not actually interested in the passage of time.</p>

<p>Here is my test code right now gleamed from lots of googling with zero context of how sinon works:</p>

<pre><code>var whatever = sinon.spy(global, 'Date');
sinon.stub(whatever, 'toLocaleTimeString').yields('7:00 PM');
</code></pre>

<p>However, this gives the error ""Attempted to wrap undefined property toLocaleTimeString as function"".</p>

<p>Please help me understand the logic behind how I am meant to stub out this sort of functionality and how I do so.</p>
",https://stackoverflow.com/questions/45723379/using-sinon-to-mock-a-date-object,"['javascript', 'date', 'sinon']",2774,TRUE,5,2
Testing util class with method dependency,"<p>I have a utility class that I need to do some unit testing, but within this utility class I have methods that depend on others in that same utility class.</p>

<p>For that I'm using the following dependencies:</p>

<ul>
<li>jUnit:4.12</li>
<li>Mockito: 2.8</li>
<li>Powermock: 1.7</li>
</ul>

<p>As it's already evident that I am using Java to perform my code.</p>

<p>Now go to the example code:</p>

<pre><code>public final class AppUtils {

    private AppUtils () {
        throw new UnsupportedOperationException(""This class is not instantiable."");
    }

    public static int plus(int a, int b) {
        return a + b;
    }

    public static float average(int a, int b) {
        return ((float) AppUtils.plus(a, b)) / 2;
    }
}
</code></pre>

<p>And the unit test:</p>

<pre><code>@RunWith(PowerMockRunner.class)
@PrepareForTest({AppUtils.class})
public class AppUtilsTest {

    @Test
    public void testPlus() { //This test must be good.
        assertEquals(6, AppUtils.plus(4, 2));
    }

    @Test
    public void testAverage() {
        PowerMockito.mockStatic(AppUtils.classs);
        when(AppUtils.plus(anyInt())).thenReturn(6);
        assertEquals(3f, AppUtils.average(4, 3), 1e-2d);
    }

}
</code></pre>

<p>That way I did my unit test, but this throws me an error because it tells me that the expected result does not correspond to the actual one.</p>

<pre><code>expected: 3.000f
actual: 0
</code></pre>

<p>This is because <code>PowerMock</code> by using the <code>mockStatic()</code> method replaces all static implementations for your defines, but if you do not define the result of one static method then it returns 0.</p>

<p>If anyone can help me, I thank you.</p>
",https://stackoverflow.com/questions/45226845/testing-util-class-with-method-dependency,"['java', 'unit-testing', 'junit', 'mockito', 'powermock']",2179,TRUE,0,1
Vertx FileUpload Unit Test,"<p>My backend code is very similar to this <a href=""https://stackoverflow.com/questions/46189571/vertx-fileupload-uploads-file-without-extension"">question</a>. </p>

<pre><code>Router router  = Router.router(vertx);
router.route().handler(BodyHandler.create().setDeleteUploadedFilesOnEnd(true));

router.route(""/api/*"")
                    .produces(Constants.JSON_CONTENT_TYPE)
                    .failureHandler(rc -&gt; {
                        // handling failure code
                });

router.post(""/api/upload"").handler(uploadHandler::uploadHandler);
vertx.createHttpServer(httpOptions)
                    .requestHandler(router::accept)                             // The router::accept, method passes all routes defined in Router.
                    .listen(// do things);
class UploadHandler() {
    void uploadHandler(RoutingContext context) {
        uploads.forEach(// do things);
    }
}
</code></pre>

<p>I have been using <em>postman</em> to test the methods. It is working perfectly. </p>

<p>In <em>postman</em>, I choose <strong>POST</strong>, <strong>no headers</strong>, <strong>form-data</strong> as body, and choose <strong>files</strong> instead of text to upload files. </p>

<p>I checked in the server that <em>postman</em> include the <strong>content-type</strong> automatically. </p>

<p>I am assuming this is a good approach. Please let me know if there's a better approach. </p>

<p>My problem is at unit testing. 
I used the code similar to this. <a href=""https://github.com/vert-x/vertx-examples/blob/master/src/raw/java/upload/UploadClient.java"" rel=""nofollow noreferrer"">https://github.com/vert-x/vertx-examples/blob/master/src/raw/java/upload/UploadClient.java</a></p>

<p>There are other snippets which does similar things. But the server keeps saying that no files are attached. </p>

<p>What is the a good way to send a file to the server? </p>
",https://stackoverflow.com/questions/47698150/vertx-fileupload-unit-test,"['file-upload', 'vert.x']",726,FALSE,0,1
Creating stream of elements from collection,"<p>I am using Junit 5 Dynamic tests. 
My intention is to create a stream of elements from the collection to pass it on to test in JUnit5. 
However with this code, I am able to run only 1000 records. How do I make this work seamlessly non-blocking. </p>

<pre><code>    MongoCollection&lt;Document&gt; collection = mydatabase.getCollection(""mycoll"");
    final List&lt;Document&gt; cache = Collections.synchronizedList(new ArrayList&lt;Document&gt;());

    FindIterable&lt;Document&gt; f = collection.find().batchSize(1000);
    f.batchCursor(new SingleResultCallback&lt;AsyncBatchCursor&lt;Document&gt;&gt;() {

        @Override
        public void onResult(AsyncBatchCursor&lt;Document&gt; t, Throwable thrwbl) {
            t.next(new SingleResultCallback&lt;List&lt;Document&gt;&gt;() {

                @Override
                public void onResult(List&lt;Document&gt; t, Throwable thrwbl) {
                    if (thrwbl != null) {
                        th.set(thrwbl);
                    }
                    cache.addAll(t);
                    latch.countDown();;

                }
            });
        }
    });
    latch.await();
    return cache.stream().map(batch-&gt;process(batch));
</code></pre>

<p><strong>Updated Code</strong>  </p>

<pre><code>@ParameterizedTest
@MethodSource(""setUp"")
void cacheTest(MyClazz myclass) throws Exception {
    assertTrue(doTest(myclass));
}
public static MongoClient getMongoClient() {
 // get client here
}

private static Stream&lt;MyClazz&gt; setUp() throws Exception {
    MongoDatabase mydatabase = getMongoClient().getDatabase(""test"");
    List&lt;Throwable&gt; failures = new ArrayList&lt;&gt;();
    CountDownLatch latch = new CountDownLatch(1);
    List&lt;MyClazz&gt; list = Collections.synchronizedList(new ArrayList&lt;&gt;());
            mydatabase.getCollection(""testcollection"").find()
            .toObservable().subscribe(
            document -&gt; {
                list.add(process(document));
            },
            throwable -&gt; {
                failures.add(throwable);
            },
            () -&gt; {
                latch.countDown();
            });
    latch.await();
    return list.stream();
}

public boolean doTest(MyClazz myclass) { 
// processing goes here
}
public MyClazz process(Document doc) { 
// doc gets converted to MyClazz
   return MyClazz;
}
</code></pre>

<p>Even now, I see that all the data is loaded after which the unit testing happens. 
I think this is because of latch.await(). However, if I remove that, there is a chance that no test cases are run as the db could possibly be loading collection.</p>

<p>My use case is : I have million records in mongo and am running sort of integration test case with them. It wouldn't be feasible to load all of them in memory and hence I am attempting the streaming solution.  </p>
",https://stackoverflow.com/questions/46186498/creating-stream-of-elements-from-collection,"['java', 'mongodb', 'unit-testing', 'junit5', 'mongodb-asyc-driver']",845,TRUE,0,1
I need help running a unit test for jsonschema2pojo,"<p>I have a question regarding unit testing of jsonschema2pojo.</p>

<p>What I am trying to do is use the sample unit test in <a href=""https://github.com/joelittlejohn/jsonschema2pojo/blob/master/jsonschema2pojo-integration-tests/src/test/java/org/jsonschema2pojo/integration/json/RealJsonExamplesIT.java"" rel=""nofollow noreferrer"">https://github.com/joelittlejohn/jsonschema2pojo/blob/master/jsonschema2pojo-integration-tests/src/test/java/org/jsonschema2pojo/integration/json/RealJsonExamplesIT.java</a>
to set up my own test, however I find that there is no test library available. I tried to set up the sources in my project, but I am not using Maven, but Gradle. For the lack of Maven, the class or.jsonschema2pojo.integration.util.JsonSchema2PojoRule class does not want to compile without Maven in my project. In our team we do not use maven in our build server.</p>

<p>I hope that someone can help me point in the direction of how I would unit test my implementation method.</p>

<p>This is the unit test I am trying to run:</p>

<pre><code>public class AnalyticsGeneratorImplTest extends AbstractGoogleAnalyticsTest {

// Set a logger
private static Logger log = LoggerFactory.getLogger(AnalyticsGeneratorImplTest.class);

private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

@Rule
public JsonSchema2PojoRule schemaRule = new JsonSchema2PojoRule();

@Test
public void getTitleFromGeneratedJson() throws Exception {
    //verify that the incoming Json has been transformed

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile(""/assets/generated-list/google-analytics.json"", ""uk.ac.soton.generators.analytics.target"",
            config(""sourceType"", ""json"",
                    ""useLongIntegers"", true));

    Class&lt;?&gt; googleAnalyticsJsonObject = resultsClassLoader.loadClass(""uk.ac.soton.generators.analytics.serialised.GoogleAnalyticsJsonObject"");

    Object gaJsonObj = OBJECT_MAPPER.readValue(this.getClass().getResourceAsStream(""/assets/generated-list/google-analytics.json""), googleAnalyticsJsonObject);
    Object result = googleAnalyticsJsonObject.getMethod(""getResult"").invoke(gaJsonObj);
    Object data = result.getClass().getMethod(""getData"").invoke(result);
    Object title = data.getClass().getMethod(""getTitle"").invoke(data);

    assertThat(title.getClass().getMethod(""getTitle"").invoke(title).toString(), is(""blue""));

}
}
</code></pre>
",https://stackoverflow.com/questions/41637412/i-need-help-running-a-unit-test-for-jsonschema2pojo,"['java', 'junit', 'jsonschema2pojo']",291,FALSE,0,1
UI Testing with XCUI,"<p>I'm trying for unit testing of view controllers in xCode 8. I'm able to record, assert and run it successfully using XCUI. But I want to test particular view controller independently. </p>

<p>Like there are 4 controllers A,B,C and D in sequence    (A->B->C->D). I want to directly launch C controller and test it independently. </p>

<p>I'm able to test in this way i.e. default XCUIApplication will open A controller then click on something you will go to B Controller and then click on button in B will take you to C Controller. Then you can test it out. But I don't want in sequence. I want to directly test C controller.</p>

<p>Can you please help if anyone else has done same kind of job. 
Thanks in advance.</p>
",https://stackoverflow.com/questions/42130343/ui-testing-with-xcui,"['ios', 'unit-testing', 'swift3', 'xcode8', 'ios10']",1274,TRUE,0,2
Why is Karma not compiling TS how I expect it,"<p>I am trying to add karma/jasmine to an older project I have been working on, so that I can start adding unit testing to my TypeScript code.</p>

<p>The problem I am having is that karma is losing some module/namespace references when it is compiling the files.</p>

<p>TS Source:</p>

<pre><code>/// &lt;reference path=""../../app.ts"" /&gt;
module App.Module {
    'use strict';

    class MyClass extends BaseClass {

        constructor() {
            super();
        }
}
</code></pre>

<p>Built (I use a gulp task):</p>

<pre><code>var App;
(function (App) {
    var Module;
    (function (Module) {
       'use strict';
            var MyClass = (function (_super) {
                __extends(BaseClass, _super);
                function MyClass() {
                    var _this = _super.call(this) || this;
                    return _this;
                }
                return MyClass;
            }(App.BaseClass));
    })(Module = App.Module || (App.Module = {}));
})(App || (App = {}));
</code></pre>

<p>Built with Karma (typescriptPreprocessor):</p>

<pre><code>var App;
(function (App) {
    var Module;
    (function (Module) {
       'use strict';
            var MyClass = (function (_super) {
                __extends(BaseClass, _super);
                function MyClass() {
                    var _this = _super.call(this) || this;
                    return _this;
                }
                return MyClass;
            }(BaseClass));
    })(Module = App.Module || (App.Module = {}));
})(App || (App = {}));
</code></pre>

<p>The difference being that my normal output qualifies BaseClass as App.BaseClass, and is able to find it.</p>

<p>As a test, I changed the TS code to extend App.BaseClass, and code generated by Karma was <em>correct</em>, and was able to run without the error, but I don't want to have to go through my entire application fully qualifying every reference.</p>

<p>Is there anything I could do in the karma setup that might <em>fix</em> this?</p>

<p>karma.config.js</p>

<pre><code>module.exports = function (config) {
    config.set({
        basePath: '',
        frameworks: ['jasmine'],
        files: [
            'App/**/*.ts'
        ],
        preprocessors: {
            '**/*.ts': ['typescript']
        },
        typescriptPreprocessor: {
            transformPath: function (path) {
                return path.replace(/\.ts$/, '.js');
            }
        },
        reporters: ['progress'],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: true,
        browsers: ['Chrome'],
        singleRun: false,
        concurrency: Infinity,
        mime: {
            'text/x-typescript': ['ts', 'tsx']
        }
    });
}
</code></pre>
",https://stackoverflow.com/questions/42748935/why-is-karma-not-compiling-ts-how-i-expect-it,"['typescript', 'karma-runner']",293,TRUE,0,1
Testing ASP.NET Core app using Protractor in Visual Studio 2017,"<p>I've got a asp.net core application which uses angular4 as client frontend and asp.net core for the service api. I've had <a href=""https://stackoverflow.com/questions/41675510/testing-asp-net-core-app-using-protractor-in-visual-studio-2015"">end-to-end unit-testing up and running while using Visual Studio 2015</a>.</p>

<p>Since I switched to Visual Studio <strong>2017</strong> I can't get the tests to use protractor anymore. </p>

<p>First problem: For protractor I need the full .net framework, for hosting my app I want to use .NetCoreApp 1.1. And Visual Studio 2017 does only support using one Framework. There are <a href=""https://stackoverflow.com/questions/42670048/how-to-target-multiple-frameworks-in-vs2017-final"">tricks by editing the proj-file</a>, but even then I could not even compile my test project to use protractor.</p>

<p>So: Has anyone been able to run unit Tests using protractor in Visual Studio 2017? Any pointers about it, maybe you can point me to a website containing a sample?</p>
",https://stackoverflow.com/questions/43587280/testing-asp-net-core-app-using-protractor-in-visual-studio-2017,"['unit-testing', 'asp.net-core', 'visual-studio-2017', 'protractor-net']",452,FALSE,0,0
Dependency Injection with HttpSessionStateBase and Cache in MVC 5 and Unity,"<p>I inherited ASP.NET MVC 5 application which has its own Context object. The context object has few static properties that returns data from <code>session</code> or <code>cache</code> object. 
For brevity purpose i have reduced the number properties to 2, one from Session and one from Cache.</p>

<pre><code>public class MyContext
{
    public static UserVM CurrentUser
    {
        get
        {
            return HttpContext.Current.Session.GetCurrentUserInfo();
        }
    }

    public static IEnumerable&lt;StateProvinceVM&gt; StateProvincesLookup
    {
        get
        {
            return HttpContext.Current.Cache.GetStateProvinces();
        }
    }
}
</code></pre>

<p><strong>Extension methods</strong></p>

<pre><code>   /// Gets the current user information. MVC version
    public static UserVM GetCurrentUserInfo(this HttpSessionStateBase session)
    {            
        // get logged-in user from the database and put it in session ( user specific)
        // and any further request for user info will be retuned from session            
    }


    // Gets the current user information. Use when we are not in MVC context        
    public static CompanyUserDTO GetCurrentUserInfo(this HttpSessionState session)
    {
        return (new HttpSessionStateWrapper(session)).GetCurrentUserInfo();
    }


    // Gets the state provinces from cahe        
    public static IEnumerable&lt;StateProvinceVM&gt; GetStateProvinces(this Cache cache)
    {
       // load states from database and load in Cache. (application specific)
       // any request from any user to States will be returned from Cache.
    }
</code></pre>

<p>Well this implementation is working but makes unit testing hard and also i cannot inject Session and Cache. So i refactored it as below</p>

<pre><code>public class MyContext
{
    private static HttpSessionStateBase _session;
    private static Cache _cache;
    public TPTContext(HttpSessionStateBase session, Cache cache)
    {
        _session = session;
        _cache = cache;
    }

    public static UserVM CurrentUser
    {
        get
        {
            return _session.GetCurrentUserInfo(); 
        }
    }

    public static IEnumerable&lt;StateProvinceVM&gt; StateProvincesLookup
    {
        get
        {
            return _cache.LookupStateProvinces();
        }
    }
}
</code></pre>

<p>I am using Unity for DI. So im registering <code>Session</code> and <code>Cache</code> as  </p>

<pre><code>    container.RegisterType&lt;HttpSessionStateBase&gt;(new InjectionFactory(x =&gt; new HttpSessionStateWrapper(System.Web.HttpContext.Current.Session)));

    container.RegisterType&lt;Cache&gt;(new InjectionFactory(x =&gt; System.Web.HttpContext.Current.Cache));
</code></pre>

<p>I am not sure if my refactoring is the correct way to solve this issue.   Because i am making <code>_session</code> as static variable. Will that cause any issue down the line since session is user specific? Will it cause Captive Dependency?</p>

<p>I think Cache would be okay.     </p>

<p>or this is completely anti pattern? </p>
",https://stackoverflow.com/questions/42633639/dependency-injection-with-httpsessionstatebase-and-cache-in-mvc-5-and-unity,"['asp.net-mvc', 'dependency-injection', 'asp.net-mvc-5', 'unity-container']",647,FALSE,0,0
How to use the open source of any plugins or npms in ionic 2,"<p>I want to know how can I use the functions or files of any plugins or npms that shared in other sites with my project work ?</p>

<p><strong>for example</strong>, some ionic tutorials ends with some links that contains the open source of their work such as this [ <a href=""https://github.com/doo/scanbot-sdk-example-ionic2"" rel=""nofollow noreferrer"">https://github.com/doo/scanbot-sdk-example-ionic2</a> ] or [ <a href=""https://github.com/ionic-team/ionic-unit-testing-example"" rel=""nofollow noreferrer"">https://github.com/ionic-team/ionic-unit-testing-example</a> ]</p>

<p>So, My steps (but I don't know if its correct or not because I had errors):</p>

<ul>
<li><p>I download the files and execute this cmd command ""<strong>npm install</strong>"" to generate ""node_modules"" folder.</p></li>
<li><p>then, I write ""<strong>ionic platform add android</strong>"" to add the platform and plugins</p></li>
<li><p>finally, I copied the the plugins to my project folder plugins and copied the functions but I don't know why I got errors in my project for this step!?</p></li>
</ul>
",https://stackoverflow.com/questions/46548321/how-to-use-the-open-source-of-any-plugins-or-npms-in-ionic-2,"['plugins', 'npm', 'ionic2', 'add']",21,FALSE,0,0
File availability in asp.net core project during testing,"<p>I'm running a number of projects using asp.net core and they're being run in docker containers on Linux. </p>

<p>I want to have certain values available to my code and it's been convenient to create simple '.ini' files which can contain string values which can be easily updated during build and deployment.</p>

<p>I store them in the wwwroot folder and I load them in using ReadAllText</p>

<pre><code>var cfg = System.IO.File.ReadAllText(Directory.GetCurrentDirectory() + @""/wwwroot/app.ini"").TrimEnd('\r', '\n');
</code></pre>

<p>This works fine in both Visual Studio and in the containers. 
But when I'm trying to run unit tests the CurrentDirectory is no longer the project directory, but a build folder in the Unit Testing project. wwwroot is no longer available.</p>

<p>So what should I do/ be doing?</p>

<ul>
<li>Not use files?</li>
<li>Place them elsewhere?</li>
<li>Handle them differently in build?</li>
<li>Use something other than Directory.GetCurrentDirectory?</li>
</ul>
",https://stackoverflow.com/questions/47347876/file-availability-in-asp-net-core-project-during-testing,"['unit-testing', 'asp.net-core', '.net-core']",163,FALSE,0,0
Dependencies between tests in scala,"<p>I want to test a complex workflow, both by unit-testing its components, and running an integration test for the whole thing, without running sub-components twice unnecessarily.</p>

<p>For example, routine <code>c</code> processes the results of <code>a</code> and <code>b</code>. I would like to have the following test suites:</p>

<ul>
<li>Unit test 1: Running <code>a</code> and validating the results</li>
<li>Unit test 2: Running <code>b</code> and validating the results</li>
<li>Nightly integration test: Running <code>a</code> and <code>b</code>, validating their results, then running <code>c</code> and validating its results, <em>without re-running <code>a</code> and <code>b</code></em>, but re-using the outputs</li>
</ul>

<p>Running each component takes some time, so the obvious solution of ""just run everything every time"" is not practical.</p>

<p>The code is in Scala, but I don't care which test framework to use - scalatest, specs2, even TestNG, all are fine, though I would prefer a Scala-ish solution. Thanks!</p>
",https://stackoverflow.com/questions/43704288/dependencies-between-tests-in-scala,"['scala', 'unit-testing']",128,FALSE,0,1
cffi can&#39;t parse memcpy from string.h,"<p>I watched a very compelling lecture on unit testing C code with Python and I've been trying to write some test code using the strategy. When I attempted to run a very simple test, I receive the error:</p>

<pre><code>cffi.api.CDefError: cannot parse ""extern void *memcpy (void *__restrict __dest, const void *__restrict __src,"":5:39: before: __dest
</code></pre>

<p>Is this a limitation of cffi that I can work around or am I just using it wrong?</p>

<p>For reference, the lecture is here: <a href=""https://www.youtube.com/watch?v=zW_HyDTPjO0"" rel=""nofollow noreferrer"">https://www.youtube.com/watch?v=zW_HyDTPjO0</a>
and the slides with code snippets are here: <a href=""https://ep2016.europython.eu/media/conference/slides/writing-unit-tests-for-c-code-in-python.html"" rel=""nofollow noreferrer"">https://ep2016.europython.eu/media/conference/slides/writing-unit-tests-for-c-code-in-python.html</a></p>

<p>My header file:</p>

<pre><code>#include &lt;string.h&gt;

#ifndef _STRING_UTILS_H_

#define _STRING_UTILS_H_

extern int cmp(char* a, char* b);

#endif
</code></pre>

<p>My implementation:</p>

<pre><code>#include &lt;stringutils.h&gt;

int cmp(char* a, char* b) {
    return (strcmp(a, b) == 0);
}
</code></pre>

<p>The python file with the test in it:</p>

<pre><code>#!/usr/bin/python3

import unittest
import cffi
import importlib
import pycparser
import subprocess

def preprocess(source):
    return subprocess.run(['gcc', '-E', '-P', '-'],
            input=source, stdout=subprocess.PIPE,
            universal_newlines=True, check=True).stdout

def load(filename):
    print('Loading ' + filename)
    source = open(filename + '.c').read()
    includes = preprocess(open(filename + '.h').read())

    ffibuilder = cffi.FFI()
    ffibuilder.cdef(includes)
    print('21')
    ffibuilder.set_source(filename + '_', source)
    ffibuilder.compile()

    module = importlib.import_module(filename + '_')
    return module.lib

class StringUtilsTest(unittest.TestCase):
    def test_cmp(self):
        module = load('stringutils')
        self.assertTrue(module.cmp('howdy', 'howdy'))
        self.assertFalse(module.cmp('howdy', 'haudy'))

#run(StringUtilsTest)
if __name__ == '__main__':
    unittest.main()
</code></pre>

<p>Is this something to do with the <code>*__restrict</code> declaration it has?</p>

<p>I have never attempted to mix Python and C in this source-aware way before. Thanks in advance.</p>
",https://stackoverflow.com/questions/45992969/cffi-cant-parse-memcpy-from-string-h,"['python', 'c', 'python-3.x', 'python-cffi']",564,FALSE,0,0
How to morph a fragment into a plug-in?,"<p>I need to turn Eclipse fragments into plug-ins. Haven't found any wizard to support this.</p>

<p>So I've created a plugin.xml and edited the MANIFEST.MF to look exactly like a plug-in project does. Still, Eclipse somehow detects it's not a plug-in: for example it asks for a Host-plugin.</p>

<p>Also checked .project file, nothing seems to indicate ""fragmentness"".</p>

<p><strong>Why I need this:</strong>
Fragments were used for Unit-testing; but they're rather inconvenient: any modification in them triggers a chain of builds, and they block the exporting of individual plug-ins, unless their project is closed.</p>

<p><strong>Solution</strong>
As Greg suggested it was the 'Fragment-Host:' option that did the trick. And as Rüdiger wrote; the project had to be closed/reopened for eclipse to acknowledge the change.</p>
",https://stackoverflow.com/questions/43921380/how-to-morph-a-fragment-into-a-plug-in,"['eclipse-plugin', 'eclipse-rcp', 'eclipse-fragment']",261,TRUE,0,1
Lambda query is throwing object does not contains error while coming dynamic type of data via `MOQ` setup,"<p><strong><em>Lambda query is throwing object does not contains error while coming dynamic type of data via <code>MOQ</code> setup</em></strong></p>

<hr>

<p><strong>test Method:</strong></p>

<pre><code> [Fact]
        public void GetMainTypeList()
        {
            var mockColorsRepository = MoqHelper.CreateInstanceOfIMock&lt;IColorsRepository&gt;();
          mockColorsRepository.Setup(rep =&gt; rep.GetMainTypeList(It.IsAny&lt;Colour&gt;())).Returns((Task.FromResult&lt;IEnumerable&lt;dynamic&gt;&gt;(new[] { new { DoorCode = ""001"", MainTypeCode = ""1"" }, new { DoorCode = ""002"", MainTypeCode = ""2"" } })));
            ColorsValidator colorsValidator = new ColorsValidator(mockColorsRepository.Object);
            CoCApiResponse response = colorsValidator.GetMainTypeList(mockColorsRepository.Object);
            Assert.Equal(1, response.ResultCode);
        }
</code></pre>

<p><strong>Business class method(class name is ColourValidator) :</strong></p>

<pre><code> public CoCBaseCollection&lt;string&gt; GetMainTypeList()
        {
            CoCBaseCollection&lt;string&gt; mtlst = new CoCBaseCollection&lt;string&gt;();
            var carlist = (IEnumerable&lt;dynamic&gt;)vehrep.GetMainTypeList().Result;
            mtlst.AddItems(carlist.Select(cl =&gt; (string)cl.MainTypeCode).Where(mt =&gt; mt != null).Distinct().ToList());
            return mtlst;
        }
</code></pre>

<p>I am did MOQ setup for my repository call which is getting data from database in real time also setup a mock data which is getting data via Moq while  unit testing for this below line </p>

<h2>Repository Call</h2>

<blockquote>
  <p><code>var carlist = (IEnumerable&lt;dynamic&gt;)vehrep.GetMainTypeList().Result;// repository call</code></p>
</blockquote>

<h2>Problem</h2>

<pre><code>mtlst.AddItems(carlist.Select(cl =&gt; (string)cl.MainTypeCode).Where(mt =&gt; 
mt != null).Distinct().ToList());// this code is not working while setup 
mock data in return function of `Moq.Setup` 
</code></pre>

<p>The above code is working if am giving <code>carlist</code> data manually like below, </p>

<pre><code>var carlist = Task.FromResult&lt;IEnumerable&lt;dynamic&gt;&gt;(new[] { new { DoorCode 
= ""001"", MainTypeCode = ""1"" }, new { DoorCode = ""002"", MainTypeCode 
= ""2"" } }).Result;
</code></pre>

<p>but That(repository call) code not working if am giving this same mock data  via <code>MOQ</code> setup response, like this </p>

<pre><code>mockColorsRepository.Setup(rep =&gt; rep.GetMainTypeList(It.IsAny&lt;Colour&gt;
())).Returns((Task.FromResult&lt;IEnumerable&lt;dynamic&gt;&gt;(new[] { new { DoorCode 
= ""001"", MainTypeCode = ""1"" }, new { DoorCode = ""002"", MainTypeCode 
= ""2"" } })));
</code></pre>

<h2>Error:</h2>

<p>And it is showing this below error </p>

<p><a href=""https://i.stack.imgur.com/yA5Oz.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/yA5Oz.jpg"" alt=""enter image description here""></a></p>

<blockquote>
  <p><strong>Note:</strong> Am using this same code for some other test methods which is working perfectly. But this problem only happens when I am using <code>dynamic</code> type instead of Business entity. </p>
</blockquote>
",https://stackoverflow.com/questions/47887269/lambda-query-is-throwing-object-does-not-contains-error-while-coming-dynamic-typ,"['c#', 'unit-testing', 'dynamic', 'lambda', 'moq']",44,TRUE,0,1
How to write unit tests for a sequence of data transformations?,"<p>I am trying to learn TDD while writing a script that transform its input data in a long series of functions. The problem is similar whether I write it in python or R. I guess it's more related to TDD understanding.</p>

<pre><code># Look of main in python
def main():
    data = get_data()
    data_a = transform_fun1(data)
    data_b = transform_fun2(data_a)
    data_c = transform_fun3(data_b)
    ....
    return data_x

# Look of main in R
main &lt;- function() {
    data &lt;- get_data() %&gt;%
      transform_fun1() %&gt;%
      transform_fun2() %&gt;%
      transform_fun3() %&gt;%
      ...
    data_x
}
</code></pre>

<p>What's the best process to write unit tests for each <code>transform_fun</code>, knowing that they need as input the result of the previous <code>transform_fun</code>?</p>

<p>In the beginning it looks fairly clean, but as I get further and further, I start to reproduce more and more of <code>main</code> in each test, which doesn't smell good. Reproducing entire parts of the <code>main</code> process looks counter-intuitive to the idea of unit testing.</p>

<pre><code># in python (pytest)
def test_transform_fun_n(data):
    data_a = transform_fun1(data)
    data_b = transform_fun2(data_a)
    ...
    data_n = transform_fun_n(data_n-1)
    assert data_n == blabla

# in R (testthat)
test_that(""transform_fun_n do what I expect"", {
    data_a &lt;- transform_fun1(data)
    data_b &lt;- transform_fun2(data_a)
    ...
    data_n &lt;- transform_fun_n(data_n-1)
    expect_that(data_n, equals(blabla))
})
</code></pre>

<p>I also tried to add fixture between each step (at least in python) but it doesn't look ideal either.</p>

<p>-- EDIT --
Trying to sketch what VoiceOfUnreason's answer would look like.</p>

<pre><code>def transformV1(data):
     return data + x

def transformV2(data):
     return transformV1(data) + y

def transformV3(data):
     return transformV2(data) + z

def main():
     data = get_data()
     return transformV3(data)
</code></pre>
",https://stackoverflow.com/questions/45308914/how-to-write-unit-tests-for-a-sequence-of-data-transformations,"['python', 'r', 'unit-testing', 'tdd', 'testthat']",1124,TRUE,0,2
Laravel factory specifying column twice,"<p>I'm using factories for unit testing and so far I haven't had any problems until now:</p>

<pre><code>// This is the factory definition (note: other fields removed for brevity).
// Primary key is not included just like Laravel's docs show.
$factory-&gt;define(Media::class, function (Faker\Generator $faker) {
    return [
        'id_media' =&gt; $faker-&gt;unique()-&gt;randomNumber(6),
        'type' =&gt; $faker-&gt;randomNumber(1)
        // other irrelevant fields
    ];
});


 // This is how I call it on my unit test
 $count = 5;
 $id = 3;
 factory(Media::class, $count)-&gt;create([
      'id_media' =&gt; $id
 ]);
</code></pre>

<p>The problem is that this generates invalid SQL (<code>id_media</code> is there twice):</p>

<p><code>INSERT INTO media (id_media, type, id_media) VALUES (73052, 2)</code></p>

<p>If I don't override the id_media property when I call it in my unit test, then the query is valid but it's not what I need. Two things that strike me as odd are:</p>

<ul>
<li>I'm using this all over my tests but the only time invalid SQL is generated is with this factory. I've got around two dozen factories in my app and this is the only problematic one. This particular table has one primary key and no other indexes. The table is as vanilla as they come.</li>
<li>This is actually recommended in <a href=""https://laravel.com/docs/5.3/database-testing#using-factories"" rel=""nofollow noreferrer"">the Laravel docs</a>. I'm not doing anything out of the ordinary.</li>
</ul>
",https://stackoverflow.com/questions/41513236/laravel-factory-specifying-column-twice,"['php', 'laravel', 'unit-testing', 'laravel-5.1']",513,TRUE,0,1
Is this dependency injection example &amp; explanation correct?,"<p>I am learning dependency injection.  After reading many posts and using a book, the code below is based on what I've read and an example from the book.  This console program works.  Before continuing to learn more about DI and it's use in unit testing, I would like to confirm if I'm understanding it correctly, and if I'm coding it correctly.</p>

<p>Main</p>

<pre><code>Sub Main()

  Dim myWriter As IMessageWriter                 'myWriter must be same type as ConsoleMessageWriter, next line.  That is INTERFACE type IMessageWriter
  myWriter = New ConsoleMessageWriter()          'myWriter INSTANCE is required to construct MyConsoleWriter INSTANCE below

  Dim myConsoleWriter As ConsoleWriter           'myConsoleWriter must be same type as ConsoleWriter, next line. That is CLASS type ConsoleWriter
  myConsoleWriter = New ConsoleWriter(myWriter)  'myConsoleWriter INSTANCE contructed w/ myWriter INSTANCE. myConsoleWriter exposes ConsoleWrite

  myConsoleWriter.ConsoleWrite(""Hello DI world."", True) 'INSTANCE myConsoleWriter's ConsoleWrite method uses INSTANCE MyWriter's Write method
End Sub
</code></pre>

<p>ConsoleWriter</p>

<pre><code>Public Class ConsoleWriter

  Private ReadOnly writer As IMessageWriter

  Public Sub New(writer As IMessageWriter)
    If writer Is Nothing Then
      Throw New ArgumentNullException(""writer"")
    End If
    Me.writer = writer
  End Sub    

  Public Sub ConsoleWrite(message As String, pause As Boolean)
    Me.writer.Write(message, pause)
  End Sub
End Class
</code></pre>

<p>ConsoleMessageWriter</p>

<pre><code>Public Class ConsoleMessageWriter
  Implements IMessageWriter

  Public Sub Write(message As String, pause As Boolean) Implements IMessageWriter.Write

    If pause Then
      Console.WriteLine(message)
      Console.WriteLine(""&lt;press any key to continue&gt;"")
      Console.ReadKey()
    Else
      Console.WriteLine(message)
    End If

  End Sub
End Class
</code></pre>

<p>IMessageWriter</p>

<pre><code>Public Interface IMessageWriter
  Sub Write(message As String, pause As Boolean)
End Interface
</code></pre>

<p>I added comments in the code above to remind me why each step is taken, and the graphic below is a picture I created to try to understand this methodology.
<a href=""https://i.stack.imgur.com/wuoBT.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/wuoBT.png"" alt=""enter image description here""></a></p>

<p>My questions are simple.  Is there anything wrong with the code?  The comments in the code?  The graphic?  Regarding the code, I understand several lines could be combined, but I broke them out to enhance my basic understanding.</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/43857897/is-this-dependency-injection-example-explanation-correct,"['vb.net', 'dependency-injection']",227,TRUE,0,1
How to build maven artifact that run test suites? How &#39;sbt test&#39; works?,"<p>I'm scala developer, so i'll try to explain my thoughts with sbt example but i belive java developers can understand me</p>

<p>Traditional scala/java project structure is like follow:</p>

<pre><code>src -&gt;
 - main
 - test
 - it
</code></pre>

<p>test folder is conceptually for unit testing (for testing app logic). So you can run 'sbt test' and will test over your application. This code must be close to your application. </p>

<p>may be that was offtopic, here is my question:</p>

<p>is it possible to build jar artifact that would run all my tests? I don't want to start sbt just in order to run my tests. I want to build many jar artifacts with integration test suites</p>

<pre><code>java my-super-service-it-case1.jar
</code></pre>

<p>this would give me exit code 0 if tests have passed</p>

<pre><code>java my-super-service-it-case2.jar 
</code></pre>

<p>so on...</p>

<p>I belive i need to run test within main block.. </p>
",https://stackoverflow.com/questions/47204115/how-to-build-maven-artifact-that-run-test-suites-how-sbt-test-works,"['java', 'scala', 'unit-testing', 'testing', 'integration-testing']",413,TRUE,0,1
Not able to extend ObjC class using Protocol in swift,"<p>I am trying to extend an ObjC class for dependency injection using a protocol in swift , this class isn't owned by me so I cant make changes. For one of the method its working but for other Xcode always says that the class isn't confirming to the protocol and suggests me to add the method to the extension</p>

<p>Below is the declaration in ObjC header </p>

<pre><code>- (BOOL) subscribeToTopic:(NSString *)topic
                      QoS:(AWSIoTMQTTQoS)qos
          extendedCallback:(AWSIoTMQTTExtendedNewMessageBlock)callback;
</code></pre>

<p>Here is the protocol and its extension</p>

<pre><code>protocol PopAWSIoTDataManagerProtocol {

    func publishString(_ data:String, onTopic:String, QoS:AWSIoTMQTTQoS) -&gt; Bool
    func subscribeToTopic(_ topic: String, qoS: AWSIoTMQTTQoS, extendedCallback: (NSObject, String, Data) -&gt; Void) -&gt; Bool

}

extension AWSIoTDataManager : PopAWSIoTDataManagerProtocol {

}
</code></pre>

<p>Notice the error below it suggests me exactly same func to be added to extension which I already have added to main protocol </p>

<p><a href=""https://i.stack.imgur.com/cwZ6D.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/cwZ6D.png"" alt=""enter image description here""></a></p>

<p>Not sure whats wrong , as I was able to add another method just fine.</p>

<p>Article used as a reference is this <a href=""https://medium.com/flawless-app-stories/the-complete-guide-to-network-unit-testing-in-swift-db8b3ee2c327"" rel=""nofollow noreferrer"">https://medium.com/flawless-app-stories/the-complete-guide-to-network-unit-testing-in-swift-db8b3ee2c327</a></p>
",https://stackoverflow.com/questions/46023670/not-able-to-extend-objc-class-using-protocol-in-swift,"['ios', 'objective-c', 'swift', 'xcode', 'protocols']",630,FALSE,0,2
Comparing fields in select clause works in sqlite but not in DB2,"<p>I'm checking for address discrepancies between two tables, using a query formed like this:</p>

<pre><code>SELECT a.*, (a.address &lt;&gt; b.address) AS discrepancy 
FROM table1 AS a 
LEFT JOIN table2 AS b 
ON a.uniqueIdentifier = b.uniqueIdentifier
</code></pre>

<p>What I'm expecting is that if a.address does not exactly match b.address, it will evaluate to true; hence the field, 'discrepancy' will return true or '1'. </p>

<p>(note, the left join is used because there may not be a matching row in table2, but I need to capture data from table1 regardless because I am iterating through the list and showing if the address has a problem)</p>

<p>The query worked in my unit testing with SQLite, but then failed in development with a DB2 database using ODBC.  </p>

<p>The error code returned is <code>[Code: -104, SQL State: 42601]  [SQL0104] Token A was not valid. Valid tokens: (.</code></p>

<p>If this is simply not supported in DB2, I'm open to alternate ideas how to craft the query.</p>

<hr>

<p>Note: further testing shows that </p>

<p><code>select a.id, (1+1) as two from table1 as a</code> </p>

<p>works, while </p>

<p><code>select a.id, (1=1) as two from table1 as a</code> => <code>Token 1 was not valid</code></p>
",https://stackoverflow.com/questions/44288967/comparing-fields-in-select-clause-works-in-sqlite-but-not-in-db2,"['sql', 'sqlite', 'db2', 'odbc']",96,TRUE,0,2
Application crashing from async method,"<p>I am creating an application that requests a small amount of data from a webserver in JSON format, deserializes the data using Json.net, and returns a list of a custom object. I am debugging the application using an android phone.</p>

<p>A listview is then created using the created list. The ui code seems to work with premade objects inserted into the list instead of the async method. The async method crashed the application.</p>

<pre><code>public partial class Membership : ContentPage
{
    int increment = 1;

    public Membership()
    {
        //begin task
        var task = GetMembers(increment);

        //irrelevant stuff happening

        //wait for task to complete to continue execution
        List&lt;Person&gt; people = task.Result;


        // Create the ListView.
        ListView listView = new ListView
        {

            // Source of data items.
            ItemsSource = people,

            // Define template for displaying each item.
            // (Argument of DataTemplate constructor is called for 
            //      each item; it must return a Cell derivative.)
            ItemTemplate = new DataTemplate(() =&gt;
            {
                // Create views with bindings for displaying each property.
                Label nameLabel = new Label();
                Label statusLabel = new Label();


                nameLabel.SetBinding(Label.TextProperty, ""name"");
                statusLabel.SetBinding(Label.TextProperty, ""status"");

                // Return an assembled ViewCell.
                return new ViewCell
                {
                    View = new StackLayout
                    {
                        Padding = new Thickness(0, 5),
                        Orientation = StackOrientation.Horizontal,
                        Children =
                            {
                                //boxView,
                                new StackLayout
                                {
                                    VerticalOptions = LayoutOptions.Center,
                                    Spacing = 0,
                                    Children =
                                    {
                                        nameLabel,
                                        statusLabel
                                    }
                                    }
                            }
                    }
                };
            })
        }; 

        // Build the page.
        this.Content = new StackLayout
        {
            Children =
            {
                header,
                listView
            }
        };


    }
</code></pre>

<p>And the async task in question:</p>

<pre><code>async Task&lt;List&lt;Person&gt;&gt; GetMembers(int increment)
{
        string jsonString;

        using (var client = new HttpClient())
        {
            //gets the members from the server in json format
            //increment defines which set of members (1-50, 51-100, etc)
            var responseString = await client.GetStringAsync(""GENERIC URL"" + ""increment="" + increment.ToString());
            jsonString = responseString;
        }

        List&lt;Person&gt; memberList = JsonConvert.DeserializeObject&lt;List&lt;Person&gt;&gt;(jsonString);

        return memberList;
}
</code></pre>

<p>Now, I've tested this code by bypassing the async task and creating a list of a couple of predefined People, and it worked just fine. </p>

<p>I understand using the task.Result; method will block the application until the async task completes, but, when unit testing there were no problems with speed so I am a bit confused. Any help would be appreciated.</p>
",https://stackoverflow.com/questions/42850278/application-crashing-from-async-method,"['c#', 'xamarin', 'xamarin.forms']",2617,TRUE,4,1
PHPUnit is not reading configuration file?,"<p>I want to install PHPUnit with composer and followed this tutorial: <a href=""https://jtreminio.com/2013/03/unit-testing-tutorial-introduction-to-phpunit/"" rel=""nofollow noreferrer"">https://jtreminio.com/2013/03/unit-testing-tutorial-introduction-to-phpunit/</a></p>

<p>I added </p>

<pre><code>{
    ""require-dev"": {
        ""phpunit/phpunit"": ""3.7.14""
    },
    ""autoload"": {
        psr-0"": {
           ""phpUnitTutorial"": """"
        }
 }
}
</code></pre>

<p>to the file <code>composer.json</code>. Entering <code>./vendor/bin/phpunit</code> shows me that phpunit is installed. </p>

<p>This is my folder structure:</p>

<pre><code>composer.json
composer.phar
phpUnitTutorial/
vendor/
</code></pre>

<p>I created a <code>phpunit.xml</code> file inside the <code>phpUnitTutorial</code> folder with the content</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;phpunit colors=""true""&gt;
    &lt;testsuites&gt;
        &lt;testsuite name=""Application Test Suite""&gt;
            &lt;directory&gt;./phpUnitTutorial/Test/&lt;/directory&gt;
        &lt;/testsuite&gt;
    &lt;/testsuites&gt;
&lt;/phpunit&gt;
</code></pre>

<p>Further I created an file at <code>phpUnitTutorial/Test/StupidTest.php</code> with the content</p>

<pre><code>&lt;?php

namespace phpUnitTutorial\Test;

class StupidTest extends \PHPUnit_Framework_TestCase
{
    public function testTrueIsTrue(){
      $foo = ture;
      $this-&gt;assertTrue($foo);
    }
}
</code></pre>

<p>In the tutorial it is advised to do the following:</p>

<blockquote>
  <p>From project root, run PHPUnit: $ vendor/bin/phpunit</p>
</blockquote>

<p>with the following screenshot:</p>

<p><a href=""https://i.stack.imgur.com/O52M4.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/O52M4.png"" alt=""enter image description here""></a></p>

<p>If I execute <code>$ vendor/bin/phpunit</code> inside the <code>phpUnitTutorial</code> folder then I receive the error</p>

<blockquote>
  <p>bash: vendor/bin/phpunit: No such file or directory</p>
</blockquote>

<p>which makes sense to me because the folder <code>vendor</code> is on the same level as the folder <code>phpUnitTutorial</code>. If I execute <code>$ ../vendor/bin/phpunit</code> I get </p>

<p><a href=""https://i.stack.imgur.com/agqvU.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/agqvU.png"" alt=""enter image description here""></a></p>

<p>It says no test executed and it doesn't confirm that my configuration file was read. Why is it not executing the test?</p>
",https://stackoverflow.com/questions/44327318/phpunit-is-not-reading-configuration-file,"['php', 'phpunit', 'composer-php']",8865,TRUE,4,1
Unit Test Url.Link in .net core,"<p>I am using .net core creating an API.
One of my methods is a POST which inserts a new record. The successful response returns a 201 Created. In .net I can use the helper CreatedResult e.g.</p>

<pre><code>return Created(new Uri(Url.Link(""get_method"", new { id = record.id })), record);
</code></pre>

<p>This will return a 201 response with the correct Location header set. The Location header uses the incoming request to build up the url using the hostname.</p>

<p>When unit testing in .net webapi2 I could create a custom HttpRequestMessage and set the hostname myself. Now this seems to have disappeared in the new .net core framework.</p>

<p>How do I mock the incoming request so I can unit test and create a valid Location header. </p>

<p>I believe that I need to be mocking HttpRequest on the HttpContext for the controller. </p>

<pre><code>UserController controller = new UserController();
controller.ControllerContext.HttpContext.Request = ?
</code></pre>

<p>How to I mock this Request parameter? It is a readonly property.</p>
",https://stackoverflow.com/questions/42194124/unit-test-url-link-in-net-core,"['c#', 'unit-testing', 'asp.net-core-mvc', '.net-core']",4161,TRUE,4,3
How to start a job from another job in a declarative pipeline?,"<p>Lets assume there are two job:</p>

<ol>
<li>a job for a micro-service repository</li>
<li>a job for end-to-end tests</li>
</ol>

<p>I'd like, in specific cases, to start the end-to-end tests job from the micro-service job. For example, after introducing a change that even though passed unit testing and integration testing, it needs further testing, available in the end-to-end tests job.</p>

<p>I'd like for the developers to make a commit with a specific phrase. To that end, I implemented the following in the micro-service pipeline:</p>

<pre><code>pipeline {
    ...
    ...
    stages {
        ...
    }    


    post {
        success {
            if (BRANCH_NAME == ""develop"") {
                result = sh (script: ""git log -1 | grep '.*\\[e2e\\].*'"", returnStatus: true) 
                if (result == 0) {
                    build job: '****', wait: false
                }
            }
        }
    ...
    ...
    }
}
</code></pre>

<p>This seemingly works, as I see the following in the log:</p>

<blockquote>
  <p>git log -1<br>
  grep '.<em>[e2e].</em>'<br>
      Run tests [e2e] [Pipeline] build (Building ****)<br>
  Scheduling item: ****</p>
</blockquote>

<p>So it found ""[e2e]"" and supposedly scheduled a build in the end-to-end tests job, but in actuality nothing happened - no job was scheduled/run.</p>
",https://stackoverflow.com/questions/43375243/how-to-start-a-job-from-another-job-in-a-declarative-pipeline,"['jenkins', 'jenkins-pipeline', 'declarative']",2658,TRUE,3,1
Private methods in service layer,"<p>I have a situation:
I want to provide a service class with one functionality, for example:
generating json file based on some params.. So I have one public method, and some private methods invoked by the public one. There are some private methods, and now I have a problem with unit testing them. I know possibilities (no test private method, make them public (NO!), refelctions,package private) , and the best is package private solution, but that service class is inside  xx.service package and I only want to the one method be visible outside... </p>

<p>I am using Spring BOOT, and my question is : Maybe this is a bad approach with keeping private methods inside service class at all? Maybe move them to any kind of util classes? (To be honest that methods are kind of util methods..)</p>

<p>Please help :)  </p>
",https://stackoverflow.com/questions/47454865/private-methods-in-service-layer,"['java', 'spring', 'unit-testing', 'spring-boot', 'private-methods']",2502,TRUE,3,1
Angular2 Karma Phantom-JS ZoneAwareError,"<p>I am a bit of a novice on TypeScript/JavaScript and Angular2. I'm trying to set up a unit testing framework for an Angular2 app that can be run as part of a VSTS build pipeline. The idea is to run the unit tests in phantomjs instead of Chrome.</p>

<p>I downloaded the Angular2 quickstart project here: <a href=""https://github.com/angular/quickstart"" rel=""nofollow noreferrer"">https://github.com/angular/quickstart</a> and the Karma test runner worked fined with the Chrome browser. I then followed the instruction here to get the quickstart tests running with phantomjs: <a href=""https://stackoverflow.com/questions/40470806/how-to-configure-angular2-quickstart-to-run-phantomjs"">How to configure Angular2 Quickstart to run phantomjs?</a>.</p>

<p>I added the missing ""system-polyfills.js"" reference reference, however I'm still getting a ZoneAware error when executing Karma.</p>

<p>I'm on Windows 10.</p>

<p>My karma.conf.js file looks like this:</p>

<pre><code>    module.exports = function(config) {

  var appBase    = 'src/';       // transpiled app JS and map files
  var appSrcBase = appBase;      // app source TS files

  // Testing helpers (optional) are conventionally in a folder called `testing`
  var testingBase    = 'testing/'; // transpiled test JS and map files
  var testingSrcBase = 'testing/'; // test source TS files

  config.set({
    basePath: '',
    frameworks: ['jasmine'],

    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-phantomjs-launcher'),
      require('karma-jasmine-html-reporter')
    ],

    client: {
      builtPaths: [appBase, testingBase], // add more spec base paths as needed
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },

    customLaunchers: {
      // From the CLI. Not used here but interesting
      // chrome setup for travis CI using chromium
      Chrome_travis_ci: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    },

    files: [

      // System.js for module loading
      'node_modules/systemjs/dist/system.src.js',

      // Polyfills
      'node_modules/core-js/client/shim.js',

      // zone.js
      'node_modules/zone.js/dist/zone.js',
      'node_modules/zone.js/dist/long-stack-trace-zone.js',
      'node_modules/zone.js/dist/proxy.js',
      'node_modules/zone.js/dist/sync-test.js',
      'node_modules/zone.js/dist/jasmine-patch.js',
      'node_modules/zone.js/dist/async-test.js',
      'node_modules/zone.js/dist/fake-async-test.js',

      // RxJs
      { pattern: 'node_modules/rxjs/**/*.js', included: false, watched: false },
      { pattern: 'node_modules/rxjs/**/*.js.map', included: false, watched: false },

      // Paths loaded via module imports:
      // Angular itself
      { pattern: 'node_modules/@angular/**/*.js', included: false, watched: false },
      { pattern: 'node_modules/@angular/**/*.js.map', included: false, watched: false },

      { pattern: appBase + '/systemjs.config.js', included: false, watched: false },
      { pattern: appBase + '/systemjs.config.extras.js', included: false, watched: false },
      'karma-test-shim.js', // optionally extend SystemJS mapping e.g., with barrels

      // transpiled application &amp; spec code paths loaded via module imports
      { pattern: appBase + '**/*.js', included: false, watched: true },
      { pattern: testingBase + '**/*.js', included: false, watched: true },


      // Asset (HTML &amp; CSS) paths loaded via Angular's component compiler
      // (these paths need to be rewritten, see proxies section)
      { pattern: appBase + '**/*.html', included: false, watched: true },
      { pattern: appBase + '**/*.css', included: false, watched: true },

       {pattern: 'node_modules/systemjs/dist/system-polyfills.js', included: false, watched: false},
    // Paths for debugging with source maps in dev tools
      { pattern: appBase + '**/*.ts', included: false, watched: false },
      { pattern: appBase + '**/*.js.map', included: false, watched: false },
      { pattern: testingSrcBase + '**/*.ts', included: false, watched: false },
      { pattern: testingBase + '**/*.js.map', included: false, watched: false}
    ],

    // Proxied base paths for loading assets
    proxies: {
      // required for modules fetched by SystemJS
      '/base/src/node_modules/': '/base/node_modules/'
    },

    exclude: [],
    preprocessors: {},
    reporters: ['progress', 'kjhtml'],

    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: false,
    browsers: ['PhantomJS'],

    // you can define custom flags
    customLaunchers: {
      'PhantomJS_custom': {
        base: 'PhantomJS',
        options: {
          windowName: 'my-window',
          settings: {
            webSecurityEnabled: false
          },
        },
        flags: ['--load-images=true'],
        debug: false
      }
    },

    phantomjsLauncher: {
      // Have phantomjs exit if a ResourceError is encountered (useful if karma exits without killing phantom)
      exitOnResourceError: true
    },

    singleRun: true
  })
}
</code></pre>

<p>My package.json looks like this:</p>

<pre><code>{
  ""name"": ""angular-quickstart"",
  ""version"": ""1.0.0"",
  ""description"": ""QuickStart package.json from the documentation, supplemented with testing support"",
  ""scripts"": {
    ""build"": ""tsc -p src/"",
    ""build:watch"": ""tsc -p src/ -w"",
    ""build:e2e"": ""tsc -p e2e/"",
    ""serve"": ""lite-server -c=bs-config.json"",
    ""serve:e2e"": ""lite-server -c=bs-config.e2e.json"",
    ""prestart"": ""npm run build"",
    ""start"": ""concurrently \""npm run build:watch\"" \""npm run serve\"""",
    ""pree2e"": ""npm run build:e2e"",
    ""e2e"": ""concurrently \""npm run serve:e2e\"" \""npm run protractor\"" --kill-others --success first"",
    ""preprotractor"": ""webdriver-manager update"",
    ""protractor"": ""protractor protractor.config.js"",
    ""pretest"": ""npm run build"",
    ""test"": ""concurrently \""npm run build:watch\"" \""karma start karma.conf.js\"""",
    ""pretest:once"": ""npm run build"",
    ""test:once"": ""karma start karma.conf.js --single-run"",
    ""lint"": ""tslint ./src/**/*.ts -t verbose""
  },
  ""keywords"": [],
  ""author"": """",
  ""license"": ""MIT"",
  ""dependencies"": {
    ""@angular/common"": ""~4.0.0"",
    ""@angular/compiler"": ""~4.0.0"",
    ""@angular/core"": ""~4.0.0"",
    ""@angular/forms"": ""~4.0.0"",
    ""@angular/http"": ""~4.0.0"",
    ""@angular/platform-browser"": ""~4.0.0"",
    ""@angular/platform-browser-dynamic"": ""~4.0.0"",
    ""@angular/router"": ""~4.0.0"",
    ""angular-in-memory-web-api"": ""~0.3.0"",
    ""systemjs"": ""0.19.40"",
    ""core-js"": ""^2.4.1"",
    ""rxjs"": ""5.0.1"",
    ""zone.js"": ""^0.8.4""
  },
  ""devDependencies"": {
    ""@types/jasmine"": ""2.5.36"",
    ""@types/node"": ""^6.0.46"",
    ""canonical-path"": ""0.0.2"",
    ""concurrently"": ""^3.2.0"",
    ""jasmine-core"": ""~2.4.1"",
    ""karma"": ""^1.3.0"",
    ""karma-chrome-launcher"": ""^2.0.0"",
    ""karma-cli"": ""^1.0.1"",
    ""karma-jasmine"": ""^1.0.2"",
    ""karma-jasmine-html-reporter"": ""^0.2.2"",
    ""karma-phantomjs-launcher"": ""^1.0.4"",
    ""lite-server"": ""^2.2.2"",
    ""lodash"": ""^4.16.4"",
    ""phantomjs-prebuilt"": ""^2.1.14"",
    ""protractor"": ""~4.0.14"",
    ""rimraf"": ""^2.5.4"",
    ""tslint"": ""^3.15.1"",
    ""typescript"": ""~2.1.0""
  },
  ""repository"": {}
}
</code></pre>

<p>When I execute <code>npm test</code> or <code>.\node_modules\.bin\karma start</code> I get the following output:</p>

<pre><code>04 04 2017 13:17:59.648:INFO [karma]: Karma v1.5.0 server started at http://0.0.0.0:9876/
04 04 2017 13:17:59.649:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
04 04 2017 13:17:59.680:INFO [launcher]: Starting browser PhantomJS
04 04 2017 13:18:05.398:INFO [PhantomJS 2.1.1 (Windows 8 0.0.0)]: Connected on socket RP6_gUObf8qGXHOgAAAA with id 50128128
PhantomJS 2.1.1 (Windows 8 0.0.0) ERROR
  {
    ""line"": 923,
    ""sourceURL"": ""node_modules/zone.js/dist/zone.js"",
    ""stack"": ""ZoneAwareError@node_modules/zone.js/dist/zone.js:923:28\naddToError@node_modules/systemjs/dist/system.src.js:122:87\nlinkSetFailed@node_modules/systemjs/dist/system.src.js:687:25\nnode_modules/systemjs/dist/system.src.js:495:22\ninvoke@node_modules/zone.js/dist/zone.js:365:31\nrun@node_modules/zone.js/dist/zone.js:125:49\nnode_modules/zone.js/dist/zone.js:760:60\ninvokeTask@node_modules/zone.js/dist/zone.js:398:36\nrunTask@node_modules/zone.js/dist/zone.js:165:57\ndrainMicroTaskQueue@node_modules/zone.js/dist/zone.js:593:42\nrun@node_modules/core-js/client/shim.js:4005:30\nnode_modules/core-js/client/shim.js:4018:32\nflush@node_modules/core-js/client/shim.js:4373:12"",
    ""originalStack"": ""ZoneAwareError@node_modules/zone.js/dist/zone.js:923:28\naddToError@node_modules/systemjs/dist/system.src.js:122:87\nlinkSetFailed@node_modules/systemjs/dist/system.src.js:687:25\nnode_modules/systemjs/dist/system.src.js:495:22\ninvoke@node_modules/zone.js/dist/zone.js:365:31\nrun@node_modules/zone.js/dist/zone.js:125:49\nnode_modules/zone.js/dist/zone.js:760:60\ninvokeTask@node_modules/zone.js/dist/zone.js:398:36\nrunTask@node_modules/zone.js/dist/zone.js:165:57\ndrainMicroTaskQueue@node_modules/zone.js/dist/zone.js:593:42\nrun@node_modules/core-js/client/shim.js:4005:30\nnode_modules/core-js/client/shim.js:4018:32\nflush@node_modules/core-js/client/shim.js:4373:12"",
    ""zoneAwareStack"": ""addToError@node_modules/systemjs/dist/system.src.js:122:87 [&lt;root&gt;]\nlinkSetFailed@node_modules/systemjs/dist/system.src.js:687:25 [&lt;root&gt;]\nnode_modules/systemjs/dist/system.src.js:495:22 [&lt;root&gt;]\nrun@node_modules/zone.js/dist/zone.js:125:49 [&lt;root&gt; =&gt; &lt;root&gt;]\nnode_modules/zone.js/dist/zone.js:760:60 [&lt;root&gt;]\nrunTask@node_modules/zone.js/dist/zone.js:165:57 [&lt;root&gt; =&gt; &lt;root&gt;]\ndrainMicroTaskQueue@node_modules/zone.js/dist/zone.js:593:42 [&lt;root&gt;]\nrun@node_modules/core-js/client/shim.js:4005:30 [&lt;root&gt;]\nnode_modules/core-js/client/shim.js:4018:32 [&lt;root&gt;]\nflush@node_modules/core-js/client/shim.js:4373:12 [&lt;root&gt;]"",
    ""originalErr"": {
      ""stack"": ""eval@[native code]\n__exec@node_modules/systemjs/dist/system.src.js:1555:18\nexecute@node_modules/systemjs/dist/system.src.js:4035:22\nlinkDynamicModule@node_modules/systemjs/dist/system.src.js:3300:36\nlink@node_modules/systemjs/dist/system.src.js:3135:28\nexecute@node_modules/systemjs/dist/system.src.js:3510:17\ndoDynamicExecute@node_modules/systemjs/dist/system.src.js:766:32\nlink@node_modules/systemjs/dist/system.src.js:964:36\ndoLink@node_modules/systemjs/dist/system.src.js:623:11\nupdateLinkSetOnLoad@node_modules/systemjs/dist/system.src.js:669:24\nnode_modules/systemjs/dist/system.src.js:485:30\ninvoke@node_modules/zone.js/dist/zone.js:365:31\nrun@node_modules/zone.js/dist/zone.js:125:49\nnode_modules/zone.js/dist/zone.js:760:60\ninvokeTask@node_modules/zone.js/dist/zone.js:398:36\nrunTask@node_modules/zone.js/dist/zone.js:165:57\ndrainMicroTaskQueue@node_modules/zone.js/dist/zone.js:593:42\nrun@node_modules/core-js/client/shim.js:4005:30\nnode_modules/core-js/client/shim.js:4018:32\nflush@node_modules/core-js/client/shim.js:4373:12"",
      ""line"": 1555,
      ""sourceURL"": ""node_modules/systemjs/dist/system.src.js""
    },
    ""__zone_symbol__currentTask"": {
      ""type"": ""microTask"",
      ""state"": ""notScheduled"",
      ""source"": ""Promise.then"",
      ""zone"": ""&lt;root&gt;"",
      ""cancelFn"": null,
      ""runCount"": 0
    }
  }

PhantomJS 2.1.1 (Windows 8 0.0.0) ERROR
  {
    ""line"": 923,
    ""sourceURL"": ""node_modules/zone.js/dist/zone.js"",
    ""stack"": ""ZoneAwareError@node_modules/zone.js/dist/zone.js:923:28\naddToError@node_modules/systemjs/dist/system.src.js:122:87\nlinkSetFailed@node_modules/systemjs/dist/system.src.js:687:25\nnode_modules/systemjs/dist/system.src.js:495:22\ninvoke@node_modules/zone.js/dist/zone.js:365:31\nrun@node_modules/zone.js/dist/zone.js:125:49\nnode_modules/zone.js/dist/zone.js:760:60\ninvokeTask@node_modules/zone.js/dist/zone.js:398:36\nrunTask@node_modules/zone.js/dist/zone.js:165:57\ndrainMicroTaskQueue@node_modules/zone.js/dist/zone.js:593:42\nrun@node_modules/core-js/client/shim.js:4005:30\nnode_modules/core-js/client/shim.js:4018:32\nflush@node_modules/core-js/client/shim.js:4373:12"",
    ""originalStack"": ""ZoneAwareError@node_modules/zone.js/dist/zone.js:923:28\naddToError@node_modules/systemjs/dist/system.src.js:122:87\nlinkSetFailed@node_modules/systemjs/dist/system.src.js:687:25\nnode_modules/systemjs/dist/system.src.js:495:22\ninvoke@node_modules/zone.js/dist/zone.js:365:31\nrun@node_modules/zone.js/dist/zone.js:125:49\nnode_modules/zone.js/dist/zone.js:760:60\ninvokeTask@node_modules/zone.js/dist/zone.js:398:36\nrunTask@node_modules/zone.js/dist/zone.js:165:57\ndrainMicroTaskQueue@node_modules/zone.js/dist/zone.js:593:42\nrun@node_modules/core-js/client/shim.js:4005:30\nnode_modules/core-js/client/shim.js:4018:32\nflush@node_modules/core-js/client/shim.js:4373:12"",
    ""zoneAwareStack"": ""addToError@node_modules/systemjs/dist/system.src.js:122:87 [&lt;root&gt;]\nlinkSetFailed@node_modules/systemjs/dist/system.src.js:687:25 [&lt;root&gt;]\nnode_modules/systemjs/dist/system.src.js:495:22 [&lt;root&gt;]\nrun@node_modules/zone.js/dist/zone.js:125:49 [&lt;root&gt; =&gt; &lt;root&gt;]\nnode_modules/zone.js/dist/zone.js:760:60 [&lt;root&gt;]\nrunTask@node_modules/zone.js/dist/zone.js:165:57 [&lt;root&gt; =&gt; &lt;root&gt;]\ndrainMicroTaskQueue@node_modules/zone.js/dist/zone.js:593:42 [&lt;root&gt;]\nrun@node_modules/core-js/client/shim.js:4005:30 [&lt;root&gt;]\nnode_modules/core-js/client/shim.js:4018:32 [&lt;root&gt;]\nflush@node_modules/core-js/client/shim.js:4373:12 [&lt;root&gt;]"",
    ""originalErr"": {
      ""stack"": ""eval@[native code]\n__exec@node_modules/systemjs/dist/system.src.js:1555:18\nexecute@node_modules/systemjs/dist/system.src.js:4035:22\nlinkDynamicModule@node_modules/systemjs/dist/system.src.js:3300:36\nlink@node_modules/systemjs/dist/system.src.js:3135:28\nexecute@node_modules/systemjs/dist/system.src.js:3510:17\ndoDynamicExecute@node_modules/systemjs/dist/system.src.js:766:32\nlink@node_modules/systemjs/dist/system.src.js:964:36\ndoLink@node_modules/systemjs/dist/system.src.js:623:11\nupdateLinkSetOnLoad@node_modules/systemjs/dist/system.src.js:669:24\nnode_modules/systemjs/dist/system.src.js:485:30\ninvoke@node_modules/zone.js/dist/zone.js:365:31\nrun@node_modules/zone.js/dist/zone.js:125:49\nnode_modules/zone.js/dist/zone.js:760:60\ninvokeTask@node_modules/zone.js/dist/zone.js:398:36\nrunTask@node_modules/zone.js/dist/zone.js:165:57\ndrainMicroTaskQueue@node_modules/zone.js/dist/zone.js:593:42\nrun@node_modules/core-js/client/shim.js:4005:30\nnode_modules/core-js/client/shim.js:4018:32\nflush@node_modules/core-js/client/shim.js:4373:12"",
      ""line"": 1555,
      ""sourceURL"": ""node_modules/systemjs/dist/system.src.js""
    },
    ""__zone_symbol__currentTask"": {
      ""type"": ""microTask"",
      ""state"": ""notScheduled"",
      ""source"": ""Promise.then"",
      ""zone"": ""&lt;root&gt;"",
      ""cancelFn"": null,
      ""runCount"": 0
    }
  }
</code></pre>

<p>Any assistance would be appreciated!</p>
",https://stackoverflow.com/questions/43197718/angular2-karma-phantom-js-zoneawareerror,"['angular', 'phantomjs', 'karma-jasmine']",681,TRUE,3,1
How to run Jasmine JS in ReSharper?,"<p>I started out with a .NET 4.5 solution in VS2015, with the latest ReSharper plugin. I followed this tutorial:</p>

<p><a href=""https://blogs.endjin.com/2014/09/unit-testing-angularjs-with-visual-studio-resharper-and-teamcity/"" rel=""nofollow noreferrer"">https://blogs.endjin.com/2014/09/unit-testing-angularjs-with-visual-studio-resharper-and-teamcity/</a></p>

<p>All I get is <code>Inconclusive: Test not run</code> in ReSharper's Unit Test Sessions window.</p>

<p>When following this tutorial:</p>

<p><a href=""https://evanhahn.com/how-do-i-jasmine/"" rel=""nofollow noreferrer"">https://evanhahn.com/how-do-i-jasmine/</a></p>

<p>I can run the test page in a browser and the two tests fail, correctly.</p>

<p>What I don't understand is why ReSharper would not be running the tests when I have the same references in the <code>serviceSpec.js</code> file as in the <code>SpecRunner.html</code> file.</p>

<p>I would also like to know how I can get some more information out of ReSharper about the problem it sees in attempting to run my tests.</p>

<p>Here is my servicesSpec.js:</p>

<pre><code>///&lt;reference path=""~/bower_components/jasmine-core/lib/jasmine-core/jasmine.js""/&gt;
///&lt;reference path=""~/bower_components/jasmine-core/lib/jasmine-core/jasmine-html.js""/&gt;
///&lt;reference path=""~/bower_components/jasmine-core/lib/jasmine-core/boot.js""/&gt;
///&lt;reference path=""~/bower_components/angular/angular.js""/&gt;
///&lt;reference path=""~/bower_components/angular-mocks/angular-mocks.js""/&gt;

describe(""Testum"",
    function() {
        describe(""Service test"",
            function() {
                it('should at least run this test',
                    function() {
                        console.log(""stuff"");
                        expect([1, 2, 3].length).toBe(3);
                    });
            });
    });
</code></pre>

<p>Here is the SpecRunner.html which passes (I simplified the tests) in a browser window:</p>

<pre><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;meta charset=""utf-8""&gt;
    &lt;title&gt;Jasmine Spec Runner&lt;/title&gt;
    &lt;link rel=""stylesheet"" href=""../../bower_components/jasmine-core/lib/jasmine-core/jasmine.css""&gt;
    &lt;script src=""../../bower_components/jasmine-core/lib/jasmine-core/jasmine.js""&gt;&lt;/script&gt;
    &lt;script src=""../../bower_components/jasmine-core/lib/jasmine-core/jasmine-html.js""&gt;&lt;/script&gt;
    &lt;script src=""../../bower_components/jasmine-core/lib/jasmine-core/boot.js""&gt;&lt;/script&gt;
    &lt;!-- include source files here... --&gt;
    &lt;!-- include spec files here... --&gt;
    &lt;script src=""shared/orderServiceSpecs.js""&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
",https://stackoverflow.com/questions/42971627/how-to-run-jasmine-js-in-resharper,"['angularjs', 'unit-testing', 'jasmine', 'resharper']",744,FALSE,2,0
How to integrate CMock unit test framework with Make,"<p>Is there a way around having to switch my project to use rake as its build system? I have a large project using Make as its build system and would like to add CMock functionality for unit testing (I'm already successfully using Unity), but have found no information about integrating CMock with Makefiles (instead, it seems the world has just accepted using Ruby's rake as their build system if they want CMock to work with their projects).</p>

<p>I have been able to run the CMock example tests, which include a (seemingly unfinished?) 'make' example.</p>

<p>I've modified the test code in the 'make_example' to the following:</p>

<pre><code>#include ""mock_foo.h""
#include ""unity.h""

void setUp(void) {}

void tearDown(void) {}

void test_main_should_initialize_foo(void) {
        foo_init_Ignore();
        TEST_IGNORE_MESSAGE(""TODO: Implement main!"");
}
</code></pre>

<p>however, when running 'make' from the folder with the Makefile, it seems UNITY_LINE_TYPE is undefined (e.g. something is missing from my dependency chain):</p>

<pre><code>make
mkdir -p ./build
mkdir -p ./build/obj
ruby ../../scripts/create_makefile.rb --silent
cc -o build/test/obj/test_main.o -c test/test_main.c -DTEST -I ./src -I /home/user/Documents/gitrepos/cmock/vendor/unity/src -I /home/user/Documents/gitrepos/cmock/src -I ./build/test/mocks 
In file included from test/test_main.c:1:0:
./build/test/mocks/mock_foo.h:27:27: error: unknown type name ‘UNITY_LINE_TYPE’
 void foo_init_CMockExpect(UNITY_LINE_TYPE cmock_line);
                           ^
build/test/MakefileTestSupport:29: recipe for target 'build/test/obj/test_main.o' failed
make: *** [build/test/obj/test_main.o] Error 1
</code></pre>

<p>Has anyone successfully implemented a project using Makefiles and CMock?</p>
",https://stackoverflow.com/questions/45526804/how-to-integrate-cmock-unit-test-framework-with-make,"['c', 'unit-testing', 'makefile', 'cmock']",1762,TRUE,2,3
"Unit test angular 1.x components with Jasmine (using Typescript, Webpack)","<p>I am writing an app using angular 1.6, typescript, webpack, karma and jasmine. I was able to create unit tests for angular services, but now I am having troubles for testing components. On SO<a href=""https://stackoverflow.com/questions/39195921/angular-1-5-test-component-with-jasmine"">(1)</a> and <a href=""https://stackoverflow.com/questions/39487487/unit-testing-with-webpack-jasmine-core-typescript"">(2)</a> and on the net I found different examples (<a href=""https://github.com/vintem/TypescriptMochaWebpackDemo/blob/master/test/MovieDataService.spec.ts"" rel=""nofollow noreferrer"">like this</a>), but not a clear guide explaining how to test angular 1 components with the above technology set.</p>

<p>My <strong>component</strong> (HeaderComponent.ts):</p>

<pre><code>import {IWeatherforecast} from '../models/weather-forecast';
import WeatherSearchService from '../search/weather-search.service';
import WeatherMapperService from '../common/mapping/weatherMapper.service';


export default class HeaderComponent implements ng.IComponentOptions {
  public bindings: any;
  public controller: any;
  public controllerAs: string = 'vm';
  public templateUrl: string;
  public transclude: boolean = false;

constructor() {
    this.bindings = {
    };

    this.controller = HeaderComponentController;
    this.templateUrl = 'src/header/header.html';
    }
}

 export class HeaderComponentController {
   public searchText:string
   private weatherData : IWeatherforecast;

static $inject: Array&lt;string&gt; = ['weatherSearchService', 
                                 '$rootScope', 
                                 'weatherMapperService'];

     constructor(private weatherSearchService: WeatherSearchService, 
                 private $rootScope: ng.IRootScopeService, 
                 private weatherMapperService: WeatherMapperService) {
 }

 public $onInit = () =&gt; {
     this.searchText = '';
 }

 public searchCity = (searchName: string) : void =&gt; {

     this.weatherSearchService.getWeatherForecast(searchName)
         .then((weatherData : ng.IHttpPromiseCallbackArg&lt;IWeatherforecast&gt;) =&gt; {
             let mappedData = this.weatherMapperService.ConvertSingleWeatherForecastToDto(weatherData.data);

             sessionStorage.setItem('currentCityWeather', JSON.stringify(mappedData));

             this.$rootScope.$broadcast('weatherDataFetched', mappedData);

         })
         .catch((error:any) =&gt; console.error('An error occurred: ' + JSON.stringify(error)));
 }
}
</code></pre>

<p>The <strong>unit test</strong>:</p>

<pre><code>import * as angular from 'angular';
import 'angular-mocks';

import HeaderComponent from '../../../src/header/header.component';

describe('Header Component', () =&gt; {
  let $compile: ng.ICompileService;
  let scope: ng.IRootScopeService;
  let element: ng.IAugmentedJQuery;

  beforeEach(angular.mock.module('weather'));
  beforeEach(angular.mock.inject(function (_$compile_: ng.ICompileService, _$rootScope_: ng.IRootScopeService) {
    $compile = _$compile_;
    scope = _$rootScope_;
  }));

beforeEach(() =&gt; {
    element = $compile('&lt;header-weather&gt;&lt;/header-weather&gt;')(scope);
    scope.$digest();
});
</code></pre>

<p>To me is not clear how to access the controller class, in order to test the component business logic. I tried injecting $componentController, but i keep getting the error ""Uncaught TypeError: Cannot set property 'mock' of undefined"", I think this is related to angular-mocks not properly injected. </p>

<p>Can anyone suggest an approach of solution or a site where to find further details about unit testing angular 1 components with typescript and webpack?</p>
",https://stackoverflow.com/questions/42072049/unit-test-angular-1-x-components-with-jasmine-using-typescript-webpack,"['angularjs', 'typescript', 'webpack', 'karma-jasmine', 'angular-components']",3714,TRUE,2,2
Unit tests for modules using Play cache (Scala),"<p>Looking for some guidance for unit testing a module using Play cache in Scala. I have a method which queries database, gets static data and stores in Play's  cache. While writing unit tests the following error shows:</p>

<p><em>Error in custom provider, java.lang.IllegalStateException: The CacheManager has been shut down. It can no longer be used.</em></p>

<p>I do not have any tear down in my scala unit tests for this error to show up. Any advice as to why this is happening would be great.</p>

<p>Also, any suggestions for resolving this would by an eye-opener. One possible way I could think is having an additional parameter and enable/disable the cache depending on the parameter value for test/non-test workflows. But is that the only way. Should I pass a custom implementation of my cache just for my tests?</p>
",https://stackoverflow.com/questions/45654830/unit-tests-for-modules-using-play-cache-scala,"['scala', 'unit-testing', 'caching', 'cachemanager']",182,FALSE,2,0
Xamarin portable .NETStandard 1.5 unit test,"<p>I created a portable class library <a href=""https://i.stack.imgur.com/LscLB.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/LscLB.png"" alt=""Project selection for portable""></a> and then targeted it at .NETStandard 1.5 from the project properties<a href=""https://i.stack.imgur.com/Zy2Dc.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Zy2Dc.png"" alt=""enter image description here""></a>. I then created a second project with the exact same project settings, but added code to use for invoking and testing the code in the first project. But I have been unable to add MSTest to use for triggering execution. I tried using the guidance at <a href=""https://stackoverflow.com/questions/41350323/unit-testing-a-net-standard-1-6-library"">stack overflow # 41350323</a>
but ran into problems. Wondering if anyone out there has been able to use MSTest for unit testing portable .NETStandard class libraries. Note that I also tried using the guidance for <a href=""https://blogs.msdn.microsoft.com/visualstudioalm/2016/05/30/announcing-mstest-framework-support-for-net-core-rc2-asp-net-core-rc2/"" rel=""nofollow noreferrer"">.NET core</a> but the MSTest framework nuget does not seem to support .NETStandard.</p>

<p>If not a unit test, then is there a way to invoke from a console? I just need to test my code and this should not be so difficult.</p>
",https://stackoverflow.com/questions/41486116/xamarin-portable-netstandard-1-5-unit-test,"['c#', '.net', 'xamarin', 'portability', '.net-standard-1.5']",365,TRUE,2,1
TransactionScope + NHIbernate multiple sessions,"<p>im writing database related tests, but they take long time to complete and im trying to speed them up..</p>

<p>my current code looks like this:</p>

<pre><code>[TestClass]
public class TestClass
{
    private const string ConnectionString = ""..."";
    private const string TemplateDatabaseBackupPath = ""..."";

    [ClassInitialize]
    public static void ClassInitialize(TestContext context) {
        InitializeTestEnviroment(); // create &amp; fill db, init internals

        using (SqlConnection connection = new SqlConnection(ConnectionString)) {
            connection.Open();
            using (SqlCommand command = connection.CreateCommand()) {
                command.CommandText = ""BACKUP DATABASE [Testing] TO DISK = @path"";
                command.Parameters.AddWithValue(""path"", TemplateDatabaseBackupPath);
                command.ExecuteNonQuery();
            }
        }
    }

    [TestCleanup]
    public static void TestCleanup() {
        using (SqlConnection connection = new SqlConnection(ConnectionString)) {
            connection.Open();

            using (SqlCommand command = connection.CreateCommand()) {
                command.CommandText = ""ALTER DATABASE [Testing] SET SINGLE_USER WITH ROLLBACK IMMEDIATE"";
                command.ExecuteNonQuery();
            }

            using (SqlCommand command = connection.CreateCommand()) {
                command.CommandText = @""RESTORE DATABASE [Testing] FROM DISK = @path WITH REPLACE"";
                command.Parameters.AddWithValue(""path"", TemplateDatabaseBackupPath);
                command.ExecuteNonQuery();
            }
        }
    }

    [TestMethod]
    public void TestMethod() {
         Entity entity = new Entity { Name = ""Fred Flindstone"" };
         BlackBox.UpdateEntity(entity, 42);

         Entity actual = BlackBox.GetEntityById(42);
         Assert.AreEqual(""Fred Flindstone"", actual.Name);
    }

    [TestMethod]
    public void TestMethod2() {
         Entity entity = new Entity { Name = ""Fred Flindstone"" };
         BlackBox.UpdateEntity(entity, 42); // 42 = entity id

         Entity actual = BlackBox.GetEntityById(42);
         Assert.AreEqual(""Fred Flindstone"", actual.Name);
    }
}

// NH mapping class
public class Entity {
    public int Id;
    public string Name;
}

// Not real code - just to get the idea how CRUD are performed internally,  this code cannot be easily changed (no unit tests for it)
public static class BlackBox {
    public static void UpdateEntity(object entity, int id) {
        using(var s = GetSession()){
            s.Update(id, entity);
        }
    }

    public static void GetEntityById(int id) {
        using(var s = GetSession()){
            return s.Session.Query&lt;Entity&gt;().Single(o =&gt; o.Id == Id);
        }
    }

    private static IHiberSession GetSession(){ 
        return ...; // not relevant
    }

    public interface IHiberSession {
        ISession Session { get; }
        ...
    }
}
</code></pre>

<p>after some mesumenents i found this:</p>

<pre><code>ClassInitialize                8s
TestMethod and TestMethod2     ~20ms
TestCleanup                    3s
</code></pre>

<p>obviously i would like to reduce TestCleanup time ...</p>

<p>after some searching i found System.Transactions.TransactionScope and thought i have a winner:</p>

<pre><code>[ClassInitialize]
public static void ClassInitialize(TestContext context) {
    InitializeTestEnviroment();
}

[TestInitialize]
public static void TestInitialize() {
    _Scope = new System.Transactions.TransactionScope();
}

[TestCleanup]
public static void TestCleanup() {
    _Scope.Dispose(); // Rollback any changes made by test
}
</code></pre>

<p>with should be faster than database restore but unfortunately
i get this exception during in session Close() method</p>

<pre><code>System.InvalidOperationException: Disconnect cannot be called while a transaction is in progress.
</code></pre>

<p>with seems to be related to this closed issue: <a href=""https://nhibernate.jira.com/browse/NH-1744"" rel=""nofollow noreferrer"">NH-1744</a> but that dont give me any idea, gow to fix my code :(</p>

<p>Anyway my question is how to make this code to work:</p>

<pre><code>void TestMethod() {
    using(var scope = new System.Transactions.TransactionScope()) {

        // these two usings cannot be changed ...
        using (ISession session = GetSession()) {
             // some CRUD
        }

        using (ISession session = GetSession()) {
            // some more CRUD
        }
    }
}
</code></pre>

<p>or any other idea, how to make database fast backup/restore? (in-memory backup would be nice)</p>

<p>PS: TransactionScope is used ONLY in unit testing, 'live' code is scopeless</p>

<p>Thanks for any help ...</p>
",https://stackoverflow.com/questions/45861419/transactionscope-nhibernate-multiple-sessions,"['c#', 'nhibernate', 'transactionscope']",489,FALSE,2,0
How can I set up paths for reading input from a file in check unit test?,"<p>I am learning to use check for unit testing my code. I have my project set up with autotools, and I have check set up to do some tests.</p>

<p>The program I'm making is a red black tree that I want to be able to use for other projects. For one of my tests, I want to read input from a file to use as test data to insert into the tree. I have a file called words.txt in my tests directory that I want to read from. I like to keep my build tree separate though. So how can set up my makefiles to put the words file in the right place? Then can I just read it from the directory that make check runs in?</p>

<p>Here's what everything looks like:</p>

<blockquote>
  <p>Project Directory:</p>
</blockquote>

<pre><code>├── aclocal.m4
├── autom4te.cache
│   ├── output.0
│   ├── output.1
│   ├── requests
│   ├── traces.0
│   └── traces.1
├── build-aux
│   ├── ar-lib
│   ├── compile
│   ├── depcomp
│   ├── install-sh
│   ├── missing
│   └── test-driver
├── config.h.in
├── config.h.in~
├── configure
├── configure.ac
├── Makefile.am
├── Makefile.in
├── src
│   ├── libredblack.c
│   ├── libredblack.h
│   ├── main.c
│   ├── Makefile.am
│   └── Makefile.in
└── tests
    ├── check_libredblack.c
    ├── Makefile.am
    ├── Makefile.in
    └── words.txt
</code></pre>

<blockquote>
  <p>tests/Makefile.am:</p>
</blockquote>

<pre><code>TESTS = check_libredblack
check_PROGRAMS = check_libredblack
check_libredblack_SOURCES = check_libredblack.c $(top_builddir)/src/libredblack.h
check_libredblack_CFLAGS = @CHECK_CFLAGS@
check_libredblack_LDADD = $(top_builddir)/src/libredblack.a @CHECK_LIBS@
</code></pre>
",https://stackoverflow.com/questions/42471945/how-can-i-set-up-paths-for-reading-input-from-a-file-in-check-unit-test,"['c', 'unit-testing', 'makefile', 'autotools']",110,FALSE,2,1
macOS Xcode blackbox testing,"<p>I'm developing an app which is like a file-sync-client (like Dropbox).</p>

<p>I'd like to have acceptance (black-box) tests kind of like:</p>

<pre><code>- (void) testLocalFolderCreation
{
    // assert there is no folder on the server

    // create folder (either via NSFileManager or system('mkdir ...'))

    // wait a few seconds

    // assert there is now a relevant folder on the server
}
</code></pre>

<p>and bunch of other tests which test local and remote changes and sync client behavior.</p>

<p>I tried creating unit-testing bundle in Xcode, but that one doesn't actually start the app which I need for this kind of tests.</p>

<p>I'd like to test the app in one-go, not to restart the whole app for every test method or test class.</p>

<p>Does anyone have an idea how to approach this problem?
I guess, one option would be to create separate app (in Xcode or some completely other language), which would start the app (my sync client) and conduct tests while the app is running; but I'm not sure if this would be a proper approach.</p>
",https://stackoverflow.com/questions/46778555/macos-xcode-blackbox-testing,"['xcode', 'macos', 'acceptance-testing', 'black-box-testing']",169,TRUE,2,1
Moq CreateInstance fails when constructor has dependencies using Func&lt;T&gt;,"<pre><code>public class MyService
{
    private readonly ISomething _something;
    private readonly Func&lt;IRarelyGetUsed&gt; _rarelyGetUsed;

    public MyService(ISomething something, Func&lt;IRarelyGetUsed&gt; rarelyGetUsed)
    {
        _something = something;
        _rarelyGetUsed = rarelyGetUsed;
    }
}
</code></pre>

<p>We use Autofac for our IOC and found we can get big performance gains (when under load) using the <code>Func&lt;T&gt;</code> approach because those dependencies don't get resolved until they are used, and in some scenarios certain dependencies are not used.  </p>

<p>We are also using Moq for some unit testing.</p>

<pre><code>var _container = new AutoMocker();
var _service = _container.CreateInstance&lt;MyService&gt;();
</code></pre>

<p>At this point it blows up - <code>System.NullReferenceException : Object reference not set to an instance of an object.</code></p>

<p>Anyone know how to tell Moq to play nicely with Func dependencies?</p>

<p>Note that if I change <code>Func&lt;IRarelyGetUsed&gt;</code> to <code>IRarelyGetUsed</code> there's no exception.</p>

<p><strong>Edit:</strong> Turns out the nuget package was pretty old - after updating the package <code>https://github.com/tkellogg/Moq.AutoMocker</code> this is now working.</p>

<p>However, there's one more problem to solve - </p>

<pre><code>_container.GetMock&lt;Func&lt;IRarelyGetUsed&gt;&gt;().Setup(p =&gt; p().DoSomething(It.IsAny&lt;string&gt;())).Returns(true).Verifiable();
</code></pre>

<p>Trying to setup the result of the above method result in - <code>Unable to cast object of type 'System.Linq.Expressions.InstanceMethodCallExpressionN' to type 'System.Linq.Expressions.InvocationExpression'</code></p>

<p><strong>Edit 2:</strong> </p>

<pre><code>var serviceMock = _container.GetMock&lt;IRarelyGetUsed&gt;();
serviceMock.Setup(r =&gt; r.DoSomething()).Returns(someData);
_container.GetMock&lt;Func&lt;IRarelyGetUsed&gt;&gt;().Setup(s =&gt; s()).Returns(serviceMock.Object);
</code></pre>

<p>The above now works, however it requires setting up both the <code>Func&lt;IRarelyGetUsed&gt;</code> and <code>IRarelyGetUsed</code> - would be nice if it was only necessary to do one, otherwise there's more overhead per test.</p>
",https://stackoverflow.com/questions/42354828/moq-createinstance-fails-when-constructor-has-dependencies-using-funct,"['c#', 'moq', 'func', 'automocking']",1736,TRUE,1,2
Using the Singleton pattern for Game class,"<p>I'm working on a web game using HTML5 websockets and Java as backend. Currently creating a new instance of the game class for every player, which also creates a timer with a timer task to run the game loop and send updates to the frontend every 60fps. </p>

<p>As these timers would be very heavy on server resources with alot of players playing, I was thinking to apply the Singleton pattern in the game class and keep an array of matches. Instead of creating a timer for every single player, I would create 1 single timer that updates the game loop with a for loop for every match in the array.</p>

<p>I wonder if there is a better approach, as i've heard there are alot of cons that come with the singleton pattern especially for unit testing.</p>
",https://stackoverflow.com/questions/47240725/using-the-singleton-pattern-for-game-class,"['java', 'design-patterns']",788,TRUE,1,2
How to tell Liquibase to ignore a db.changelog*.xml?,"<p>I would like liquibase to create a set of unit testing functions ONLY if the database is being created in a DEV environment.</p>

<p>I know I could create a ""changeset"" tag with a ""context"" attribute for every unit test function but I'd like to avoid that if possible.</p>

<p>What would be ideal is using ""context"" with the ""includeAll"" tag, like:</p>

<pre><code>&lt;includeAll path=""./sql/UnitTest/"" context=""dev"" /&gt;
</code></pre>

<p>but sadly that is not supported.</p>

<p>OR since I have several changelogs:</p>

<pre><code>db.changelog.xml
   include db.changelog-tables.xml
   include db.changelog-functions.xml
   ...
   include db.changelog-unit_test_functions.xml
</code></pre>

<p>If I could tell LiquiBase to skip running ""db.changelog-unit_test_functions.xml"" based on a command line parameter that would also work.  </p>

<p>However, the ""context"" attribute is not allowed in the ""include"" element.</p>

<pre><code>&lt;include file=""./sql/db.changelog-unit-test.xml"" context=""dev"" /&gt;
</code></pre>

<p>I tried to attach a ""preconditions"" test to db.changelog-unit-test.xml but that fails ALL db.changelogs execution.</p>

<p>Does anyone have any clever ideas on how I can avoid writing a granular db.changelog-unit-test.xml? </p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/46982567/how-to-tell-liquibase-to-ignore-a-db-changelog-xml,"['unit-testing', 'liquibase']",1504,FALSE,1,1
Unit testing WebApi controller that calls an async method with return type of void and Moq,"<p>I have a controller that calls a method that has a return type of void. I am also mocking up the object that method is a member of using Moq.  Is there a special way to setup a mock with a method that has a return type of void?  I am currently doing something like this: </p>

<pre><code>_mockClient.Setup(m =&gt; m.MyMethod(It.IsAny&lt;int&gt;())).Verifiable();
</code></pre>

<p>The client interface is like this:</p>

<pre><code>public interface IMyClient
{
    Task MyMethod(int i);
}
</code></pre>

<p>Here is the actual unit test:</p>

<pre><code>public async Task DeleteNavMenuAsync_ReturnsOk()
{
    MyController = new MyController(_mockClient.Object);

    //TODO: This is always returning a 500, not sure why.
    IHttpActionResult actionResult = await MyController.DeleteNavMenuAsync(6);

    _mockClient.Verify(m =&gt; m.MyMethod(It.IsAny&lt;int&gt;()),Times.Once());
    Assert.IsNotNull(actionResult as OkResult);
}
</code></pre>

<p>Here is the actual controller method under test:</p>

<pre><code>public async Task&lt;IHttpActionResult&gt; DeleteNavMenuAsync(int navMenuId)
{
    try
    {
        await Client.MyMethod(navMenuId); //Errors here
        return Ok();
    }
    catch (Exception e)
    {
        return HandleException(e);
    }
}
</code></pre>

<p>The error I am receiving is ""Object reference not set to an instance of an object.""  I'm only having this problem on methods that have a return type of void.  The method works no problem with live data, it is only an issue with Mocks and unit testing.  Ultimately I'm just looking to verify that the call returns an Ok HttpStatus.</p>
",https://stackoverflow.com/questions/46424678/unit-testing-webapi-controller-that-calls-an-async-method-with-return-type-of-vo,"['c#', 'unit-testing', 'asp.net-web-api', 'moq', 'void']",745,TRUE,1,1
Unable to unit test http call happening through the controller,"<p>I am trying to write a code to test the service call which is done in my controller . I am trying to unit test that particular function in controller which is doing the service call and bringing the data . Currently i am trying with local json , but it will actually do a service call . </p>

<p>I got to know that first i have to create a spy object but i am getting the error, my goal is to successfully unit test the http call happening in the controller.</p>

<p>i am new to unit testing .Pasting my code , request you to help me please , struggling in this from many days now.Also i have gone through many solutions , they are so different making be confused.Your help is greatly appreciated</p>

<p>Service code : </p>

<pre><code>    //xlpApp is the module name
    xlpApp.factory('xlpServices', ['$rootScope', '$http', function($rootScope, 
    $http) {
    var xlpServices = {};
    xlpServices.getProgramData = function(){
          return $http.get(scripts/services/data/unitTesting.json'); 
     };
</code></pre>

<p>unitTesting.json code : </p>

<pre><code>    {
    ""name"":""unit testing""
    }
</code></pre>

<p>Controller Code : </p>

<pre><code>$scope.events = {

    programData: function(){
            xlpServices.getProgramData().then(function(response) {
                if (response &amp;&amp; response.data) {
                    $scope.testVariable= response.data.name;
                }
            });
        },
    selectSortingType : function(type) {
            $scope.selectedSorting = type;
            selectedFilter.sortingBy = $scope.selectedSorting;
        }   

}
$scope.events.programData();  
</code></pre>

<p>Unit Test Code : </p>

<pre><code>  describe('myProgramGpmCtrl', function() {
  beforeEach(module('xlp'));

  var $controller;

  beforeEach(inject(function(_$controller_){
    $controller = _$controller_;
  }));

describe('service call test', function() {
    var xlpServices , myService , $q;
    var $scope = {};

     beforeEach(inject(function(xlpServices,_$q_){
       xlpServices = xlpServices;
       $q = _$q_;
       var controller = $controller('myProgramGpmCtrl', { $scope: $scope });
       myService = jasmine.createSpyObj('xlpServices',['getProgramData']);
    }));

    it('Service call test ', function() {
      expect(myService.getProgramData).toHaveBeenCalled();
    }); 
});

});
</code></pre>

<p>ERROR : </p>

<pre><code>      Expected spy xlpServices.getProgramData to have been called.
</code></pre>
",https://stackoverflow.com/questions/47893788/unable-to-unit-test-http-call-happening-through-the-controller,"['javascript', 'angularjs', 'unit-testing', 'karma-jasmine']",39,TRUE,1,1
Android binding and JUnit testing of notification,"<p>I want to test my Android view models. Especially when the setter should notify about changes or not.</p>

<p>The view model looks like this (with more bindable properties):</p>

<pre class=""lang-java prettyprint-override""><code>public class EditViewModel extends BaseObservable {

  private String _comment;
  @Bindable
  public String getComment() {
    return _comment;
  }

  public void setComment(String comment) {
    if (_comment == null &amp;&amp; comment == null) {
      // No changes, both NULL
      return;
    }

    if (_comment != null &amp;&amp; comment != null &amp;&amp; _comment.equals(comment)) {
      //No changes, both equals
      return;
    }

    _comment = comment;
    // Notification of change
    notifyPropertyChanged(BR.comment);
  }
}
</code></pre>

<p>In my UnitTest I register a listener, to get the notifications and track them with a following class:</p>

<pre class=""lang-java prettyprint-override""><code>public class TestCounter {
  private int _counter = 0;
  private int _fieldId = -1;

  public void increment(){
    _counter++;
  }

  public int getCounter(){
    return _counter;
  }

  public void setFieldId(int fieldId){
    _fieldId = fieldId;
  }

  public int getFieldId(){
    return _fieldId;
  }
}
</code></pre>

<p>So my test methods looks like the following:</p>

<pre class=""lang-java prettyprint-override""><code>@Test
public void setComment_RaisePropertyChange() {
  // Arrange
  EditViewModel sut = new EditViewModel(null);
  sut.setComment(""One"");
  final TestCounter pauseCounter = new TestCounter();
  // -- Change listener
  sut.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
    @Override
    public void onPropertyChanged(Observable sender, int propertyId) {
      pauseCounter.increment();
      pauseCounter.setFieldId(propertyId);
    }
  });
  String newComment = ""two"";

  // Act
  sut.setComment(newComment);

  // Assert
  assertThat(pauseCounter.getCounter(), is(1));
  assertThat(pauseCounter.getFieldId(), is(BR.comment));
  assertThat(sut.getComment(), is(newComment));
}
</code></pre>

<p>If I execute the test methods alone, this approach works well. If I execute all tests at one, some fail, that the notification was <code>0</code> times called. I think, that the assertions is called before the callback could be handled.</p>

<p>I tried already following approches:</p>

<p>(1) Mock the listener with mockito as described in <a href=""https://fernandocejas.com/2014/04/08/unit-testing-asynchronous-methods-with-mockito/"" rel=""nofollow noreferrer"">https://fernandocejas.com/2014/04/08/unit-testing-asynchronous-methods-with-mockito/</a>.</p>

<pre class=""lang-java prettyprint-override""><code>@Test
public void setComment_RaisePropertyChange() {  
  // Arrange
  EditViewModel sut = new EditViewModel(null);
  sut.setComment(""One"");
  Observable.OnPropertyChangedCallback listener = mock(Observable.OnPropertyChangedCallback.class);

  // -- Change listener
  sut.addOnPropertyChangedCallback(listener);
  String newComment = ""two"";

  // Act
  sut.setComment(newComment);

  // Assert
  verify(listener, timeout(500).times(1)).onPropertyChanged(any(Observable.class), anyInt());
}
</code></pre>

<p>(2) Tried to use <code>CountDownLatch</code> as described in several SO answers.</p>

<p>None of them helped me. What can I do to be able to test the binding notification?</p>
",https://stackoverflow.com/questions/44684014/android-binding-and-junit-testing-of-notification,"['android', 'unit-testing', 'mockito', 'android-databinding']",2512,TRUE,5,1
How to test an MVC controller with instantiation and action invocation from request content?,"<p>I have test-driven a Backbone model in Javascript, so I'm sure that when user clicks the ""Save"" button, a proper POST request is being sent to my ASP.NET MVC application. This is the final integration-like test for this model (<code>this.server</code> is a <a href=""http://sinonjs.org/docs/#fakeServer"" rel=""nofollow noreferrer"">Fake server from Sinon.JS</a>):</p>

<pre class=""lang-js prettyprint-override""><code>it('should properly formulate request to save data', function () {
    this.model.data = [{ id: 1, type: 'type', value: 'value' }];

    this.model.save();

    expect(this.server.requests.length).toEqual(1);
    expect(this.server.requests[0].method).toEqual('POST');
    expect(this.server.requests[0].url).toEqual('MyController/SaveData');
    expect(this.server.requests[0].requestHeaders['Content-Type'])
        .toEqual('application/json;charset=utf-8');
    expect(this.server.requests[0].requestBody)
        .toEqual('[{""id"":1,""type"":""type"",""value"":""value""}]');
});
</code></pre>

<p>Now I want to test-drive the controller. I want to be sure that I've not only properly implemented the <code>SaveData</code> action (that's easy), but I also want to verify that the mapping from request body to action arguments and MVC routes make sense. </p>

<p>I've found many questions regarding unit-testing controllers with stubbed <code>HttpContextBase</code> et consortes, for example:</p>

<ul>
<li><a href=""https://stackoverflow.com/questions/2497575/asp-net-mvc-unit-test-controller-with-httpcontext"">ASP.NET MVC unit test controller with HttpContext</a></li>
<li><a href=""https://stackoverflow.com/questions/970198/how-to-mock-the-request-on-controller-in-asp-net-mvc"">How to mock the Request on Controller in ASP.Net MVC?</a></li>
</ul>

<p>Unfortunately, they all instantiate the controller and call the action method manually. This is unsatisfactory for me: I want to assert that the same request content that's going out from JS (and is guarded by the aforementioned unit-test) is what will correctly work on the ASP.NET application side.</p>

<p>What I currently have is just a draft to make it work and illustrate the problem. I'm using <a href=""https://hibernatingrhinos.com/oss/rhino-mocks"" rel=""nofollow noreferrer"">Rhino Mocks</a> for stubs and mocks. In particular, <code>dataWebService</code> is a mock I want to use for assertions. I've included it just to make clear what's the point of the test, but in general it's of course irrelevant to the problem. The problem is twofold (controller instantiation and action invocation) and is indicated by the comments in the following code:</p>

<pre class=""lang-cs prettyprint-override""><code>[Test]
public void GivenNoData_WhenPostingData_ThenCallsWebServiceSaveData()
{
    var httpContext = MockRepository.GenerateStub&lt;HttpContextBase&gt;();
    var httpRequest = MockRepository.GenerateStub&lt;HttpRequestBase&gt;();

    httpRequest
        .Stub(hr =&gt; hr.Url)
        .Return(new Uri(""http://localhost/MyController/SaveData""));
    httpRequest
        .Stub(hr =&gt; hr.Headers)
        .Return(new WebHeaderCollection()
        {
            { ""X-Requested-With"", ""XMLHttpRequest"" },
            { ""Content-Type"", ""application/json;charset=utf-8"" }
        });
    httpRequest
        .Stub(hr =&gt; hr.RequestType)
        .Return(""POST"");

    var requestBody = @""[{""""id"""":1,""""type"""":""""type"""",""""value"""":""""value""""}]"";
    httpRequest
        .Stub(hr =&gt; hr.InputStream)
        .Return(new MemoryStream(Encoding.UTF8.GetBytes(requestBody)));

    httpContext.Stub(hc =&gt; hc.Request).Return(httpRequest);

    // The problem starts here
    // I want MVC to instantiate the controller based on the request

    var controller = new MyController(dataWebService);
    controller.ControllerContext
        = new ControllerContext(httpContext, new System.Web.Routing.RouteData(), controller);

    dataWebService.Expect(dws =&gt; dws.SaveData(Arg&lt;Data&gt;.Matches(/*...*/));

    // Second part of the problem, I want MVC to invoke SaveData with arguments
    // generated from request's body
    controller.SaveData(/* arguments */);

    dataWebService.VerifyAllExpectations();    
}
</code></pre>

<p>Now, I know that this doesn't match a strict definition of a unit-test and is somewhere between unit-testing and integration testing. </p>

<p>However, first I want to have confidence that the whole process, from top to bottom, is covered by tests, and then I'll worry about definitions (and perhaps split the test into a unit-test for controller only and an integration-like test for routing and controller arguments parsing).</p>

<p>Also note, that assuming MVC works correctly, the point is to test only my own code, in particular <code>SaveData</code> method signature and MVC route configuration.</p>
",https://stackoverflow.com/questions/42089519/how-to-test-an-mvc-controller-with-instantiation-and-action-invocation-from-requ,"['c#', '.net', 'asp.net-mvc', 'testing']",1141,TRUE,1,2
Jasmine unit test module is not defined,"<p>I am currently busy with jasmine unit testing Angular.
I have put this unit test in test.js</p>

<pre><code>describe('The countInput filter', function(){
    var $filter;

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

        inject(function(_$filter_){
            $filter = _$filter_;
        });
    });

    it('Should not give an output when the length of the input is &gt; 3', function(){

        var input = 'test';

        result = $filter('countInputFilter')(input);

        expect(result).toBe(null);
    });


});
</code></pre>

<p>When i run it with karma start karma.conf.js i get the error: Module is not defined. </p>

<p>In my karma.conf.js file i have the following files code:</p>

<pre><code>files: [
  '../bower_components/angular/angular.js',
  '../bower_components/angular-mocks.js',
  '../bower_components/angular-route/angular-route.js',
  '../scripts/**/*.js',
  '../scripts/filters.js',
  'spec/**/*.js',
  'spec/*.js'
],
</code></pre>

<p>And the structure of my project is:</p>

<pre><code>scripts
--filters.js
test
--spec
----test.js
--karma.conf.js
</code></pre>

<p>First time trying to unit test something with Jasmine but i don't see the error.</p>

<p>26 03 2017 11:29:10.103:WARN [watcher]: Pattern ""C:/Users/user/Desktop/angular/bower_components/angular-mocks.js"" does not match any file.
26 03 2017 11:29:10.134:WARN [karma]: No captured browser, open <a href=""http://localhost:9876/"" rel=""nofollow noreferrer"">http://localhost:9876/</a>
26 03 2017 11:29:10.150:INFO [karma]: Karma v1.5.0 server started at <a href=""http://0.0.0.0:9876/"" rel=""nofollow noreferrer"">http://0.0.0.0:9876/</a>
26 03 2017 11:29:10.150:INFO [launcher]: Launching browser Chrome with unlimited concurrency
26 03 2017 11:29:10.181:INFO [launcher]: Starting browser Chrome</p>
",https://stackoverflow.com/questions/43027033/jasmine-unit-test-module-is-not-defined,"['angularjs', 'jasmine']",1015,TRUE,0,1
Java Elasticsearch database testing,"<p>i'm currently using ES 5 and Jest in a project i'm working in, and i was assigned to to integration and unit testing on the classes that interact with the DB.</p>

<p>lets asume i have a method like this:</p>

<pre><code> @Override
public Aptitude save(Aptitude aptitude) {
    Index index = new Index.Builder(aptitude).index(aptitudeIndexName).type(aptitudeTypeName).refresh(true).build();
    try {
        client.execute(index);
        return aptitude;
    } catch (IOException e) {
        logger.error(""The aptitude couldn't be saved in the data base "" + e.getMessage());
        throw new RuntimeException(e);
    }
}
</code></pre>

<p>or one like this:</p>

<pre><code>@Override
public List&lt;Aptitude&gt; findAll() {
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder.query(QueryBuilders.matchAllQuery());
    searchSourceBuilder.sort(""id"", SortOrder.ASC);

    Search search = new Search.Builder(searchSourceBuilder.toString()).addIndex(aptitudeIndexName).build();

    try {
        SearchResult result = client.execute(search);

        if (!result.isSucceeded()) {
            return null;
        }

        List&lt;Hit&lt;Aptitude, Void&gt;&gt; aptitudes = result.getHits(Aptitude.class);
        return aptitudes.stream().map(this::getAptitude).collect(Collectors.toList());
    } catch (IOException e) {
        logger.error(""The search couldn't be executed"" + e.getMessage());
        throw new RuntimeException(e);
    }
}
</code></pre>

<p>and my task is to write some test (unit and integration) to make sure all my classes are working correctly and to have better test coverage, i searched a bit online for ES testing but can quite grasp how im supposed to make the tests.</p>

<p>i made some tests that looked like this:</p>

<pre><code>@Test
public void aptitudeSaveDelete() {
    Aptitude aptitude = new Aptitude();
    aptitude.setId(1993L);
    aptitude.setEn(""ENaptitudeEN"");
    aptitude.setEs(""ESaptitudeES"");
    Aptitude aptitudeSaved = elasticsearchAptitudeRepository.save(aptitude);

    assertEquals(aptitude.getEs(), aptitudeSaved.getEs());
    assertEquals(aptitude.getEn(), aptitudeSaved.getEn());
    assertEquals(aptitude.getId(), aptitudeSaved.getId());

    Aptitude aptitudeFoundById = elasticsearchAptitudeRepository.findById(String.valueOf(aptitude.getId()));

    assertEquals(aptitude.getId(), aptitudeFoundById.getId());
    assertEquals(aptitude.getEn(), aptitudeFoundById.getEn());
    assertEquals(aptitude.getEs(), aptitudeFoundById.getEs());

    boolean wasDeleted;
    wasDeleted = elasticsearchAptitudeRepository.deleteAptitudeById(String.valueOf(aptitude.getId()));
    assertEquals(true, wasDeleted);
}
</code></pre>

<p>but my coworkers told me that this kind of test compromised the DB and that in case something went wrong with them then the DB would had to be repaired manually.</p>

<p>so that is why im at a loss here, any kind of help is apreciated</p>
",https://stackoverflow.com/questions/42653797/java-elasticsearch-database-testing,"['java', 'unit-testing', 'elasticsearch', 'integration-testing', 'elasticsearch-jest']",596,TRUE,0,1
Mocha reporter does not seem to be taken into account when tests ran by chimp,"<p>I have a very simple project that contains a <em>package.json</em> with this:</p>

<pre><code>{
  ""scripts"": {
    ""acceptance"": ""chimp --mocha --mochaReporter=mocha-junit-reporter  --chai --browser=chrome --path=src/spec/acceptance/**""
   },
  ""devDependencies"": {
  ""chai"": ""^3.5.0"",
  ""chimp"": ""^0.47.1"",
  ""mocha"": ""^3.2.0"",
  ""mocha-junit-reporter"": ""^1.13.0"",
  ""uglify-js"": ""^2.7.5"",
  ""webdriverio"": ""^4.6.2""
},
  ""dependencies"": {}
}
</code></pre>

<p>To execute the tests, I'm running the following command:</p>

<pre><code>npm run-script acceptance
</code></pre>

<p>Which makes chimp execute the tests with mocha (those are webdriverio tests, hence why I am using chimp)
The tests run as intended, however, there isn't any <strong>test-results.xml</strong> produced and the test results show up in the default ""spec"" format.</p>

<p>As suggested in the <a href=""https://chimp.readme.io/docs/reporting"" rel=""nofollow noreferrer"">documentation</a>, I tried different alternatives such as creating a <em>chimp.js</em> file at the root of the project, that contains the following:</p>

<pre><code>{
  mochaCommandLineOptions: ['--reporter mocha-junit-reporter'];
  mochaConfig: { reporter: 'mocha-junit-reporter' };
  mochaReporter: ""mocha-junit-reporter"";
}
</code></pre>

<p>But neither of these options seem to be taken into account.</p>

<p>So, anyone can tell me if I am doing something wrong? </p>

<p>ps: I have a separate unit testing script that works fine, and where custom reporting is taken into account, but for those, I'm simply using mocha without chimp.</p>
",https://stackoverflow.com/questions/41896039/mocha-reporter-does-not-seem-to-be-taken-into-account-when-tests-ran-by-chimp,"['npm', 'mocha.js', 'chimp.js']",669,TRUE,0,1
Running Jasmine tests from inbside objects,"<p>I just arrived in a mid-size cordova project and would like to add unit testing to the code practices - e.g. but not necessarily Jasmine.</p>

<p>We are using the following ""singleton function-like"" pattern for simulating classes in EC5 javascript:</p>

<pre><code>var myInstance = function( dependency1, dependency2 ){

    var _prop1,_prop2;

    function init( p1, p2 ) {
        _prop1 = p1;
        _prop2 = p2;
    }

    function foo() {
        return p1 + "" foo "" + p2;
    }

    function nicePublicMethod() {
        return ""Public: "" + foo();
    }

    return {
       init: init,
       nicePublicMethod: nicePublicMethod
    }

}
</code></pre>

<p>The dependencies are all loaded one by one in an index.html file in a following manner:</p>

<pre><code>&lt;script src=""js/app/dependency1.js""&gt;&lt;/script&gt;
&lt;script src=""js/app/dependency2.js""&gt;&lt;/script&gt;
&lt;script src=""js/app/myInstance.js""&gt;&lt;/script&gt;
</code></pre>

<p><strong>What I want to achieve:</strong></p>

<p>add a ""public test"" Jasmine function into the myInstance ""singleton"":</p>

<pre><code>var myInstance = function( dependency1, dependency2 ){

        var _prop1,_prop2;

        function init( p1, p2 ) {
            _prop1 = p1;
            _prop2 = p2;
        }

        function foo() {
            return p1 + "" foo "" + p2;
        }

        function nicePublicMethod() {
            return ""Public: "" + foo();
        }
    /** TEST METHOD EXAMPLE **
        function test() {
            describe( ""it tests myInstance"", function() {
                it( ""foo runs fine"", function() {
                    expect(true).toBe(true);
                });
            } );
        }

        return {
           init: init,
           nicePublicMethod: nicePublicMethod,
           test: test // PUBLIC TEST METHOD OF THE COMPONENT
        }

    }
</code></pre>

<p>This is the only way I came up with to make sure we can unit test private methods.</p>

<p>Is it possible to somehow integrate Jasmine, or any other JavaScript test library/tool with these kind of test architecture?</p>

<p>PS: I understand this is really a general (and also way too specific) question, but the comments of knowledgeable people from this community are worth receiving a couple of -1s.</p>
",https://stackoverflow.com/questions/42834850/running-jasmine-tests-from-inbside-objects,"['javascript', 'cordova', 'unit-testing', 'jasmine']",20,FALSE,0,0
necessity of Dispose method mocking EF core with the in memory provider,"<p><strong>Background</strong></p>

<p>I'm working on a asp.net core application that uses Entity Framework Core as it's orm. For unit testing I'm using microsoft's in memory provider (<code>Microsoft.EntityFrameworkCore.InMemory</code> specifically version <code>1.1.0</code>) to manually mock the database with a class that is derived from my DBContext.</p>

<p><em>MockDBContext.cs:</em></p>

<pre><code>public class MockDBContext:DBContext{
    public MockDBContext:base(
        new DbContextOptionsBuilder&lt;DBContext&gt;().UseInMemoryDatabase(
            Guid.NewGuid().ToString()
        ).Options
    ){}
    public override void Dispose(){}
    public void clear(){
        base.Dispose();
    }
}
</code></pre>

<p>where a new unique in memory database is created for each context.</p>

<p>I'm currently overriding Dispose to do nothing to allow me to check values written by the target methods, which have <code>using(DBContext...</code> inside them, otherwise checking would throw a <code>ObjectDisposedException</code> when I run the assert in my tests. I currently have another method called <code>clear</code> that I can manually call that calls <code>base.Dispose</code> in <code>MockDBContext</code>.</p>

<p><strong>Question</strong></p>

<p>My question is, since the mock database is in memory, do I actually need to dispose it? or will it get garbage collected if I don't bother with calling <code>clear</code> inside a <code>try finally</code> for each test</p>
",https://stackoverflow.com/questions/45740218/necessity-of-dispose-method-mocking-ef-core-with-the-in-memory-provider,"['.net-core', 'entity-framework-core', 'dispose', 'idisposable']",1079,TRUE,0,1
Extend the Laravel\Lumen\Exceptions\Handler.php inside package,"<p>I've got several Lumen services that have the same code inside the <code>render()</code> function within the <code>App\Exceptions\Handler.php</code> class. I want to move this code to a separate package that all of the services can include. I was able to get this working by making the package Handler.php file extend the <code>Laravel\Lumen\Exceptions\Handler.php</code> class, basically inserting my class between the default framework file and the Handler that users edit.</p>

<p>Change: </p>

<p><code>class Handler extends Laravel\Lumen\Exceptions\Handler {...}</code></p>

<p>To:</p>

<p>My class</p>

<pre><code>use Laravel\Lumen\Exceptions\Handler;

class MyHandler extends Handler {...}
</code></pre>

<p>Framework class</p>

<pre><code>use ServiceHelpers\Exceptions\MyHandler;

class Handler extends MyHandler {...}
</code></pre>

<p>However I ran into the problem where <code>Laravel\Lumen\Exceptions\Handler</code> doesn't exist when unit testing my file within the package. I've requires several <code>illuminate/...</code> packages in my composer file but it looks like the file I'm trying to extend is in the Laravel or Lumen framework and I'd have to require the <code>laravel/lumen</code> package which I don't think is appropriate.</p>

<p>I'm currently have the following required:</p>

<pre><code>""illuminate/support"": ""^5.5"",
""illuminate/http"": ""^5.5"",
""illuminate/validation"": ""^5.5"",
</code></pre>

<p>The error I'm getting is:</p>

<pre><code>[Symfony\Component\Debug\Exception\FatalErrorException]  
  Class 'Laravel\Lumen\Exceptions\Handler' not found 
</code></pre>
",https://stackoverflow.com/questions/46870971/extend-the-laravel-lumen-exceptions-handler-php-inside-package,"['laravel', 'lumen']",451,TRUE,0,1
how to mock the dependencies of module in angular js using jasmine,"<p>I'm doing unit testing using jasmine, in my case module has some third party and some custom dependencies, i have tried some way to mock those dependencies but it doesn't works for me.</p>

<p>Below my code sample</p>

<p><strong>Module.js</strong></p>

<pre><code> var myApp = angular.module('mpapp', ['customservice', ""xeditable"",'ui.bootstrap', 'ngSanitize']); 
</code></pre>

<p><strong>testmodule.js</strong></p>

<pre><code>angular.mock.module('customservice', []);

angular.mock.module('xeditable', []);

angular.mock.module('ui.bootstrap', []);

angular.mock.module('ngSanitize', []);

module('myapp');
</code></pre>

<p>--- some required test cases here.</p>

<p>Like that i have tried to mock but it get error </p>

<p>""[$injector:modulerr] <a href=""http://errors.angularjs.org/1.5.9/"" rel=""nofollow noreferrer"">http://errors.angularjs.org/1.5.9/</a>$injector/modulerr?p0=eai.pages&amp;p1=Error%3A%20%5B%24injector%3Amodulerr%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.5.9%2F%24injector%2Fmodulerr%3Fp0%3Dui.bootstrap%26p1%3DError%253A%2520%255B%2524injector%253Anomod%255D%2520http%253A%252F%252Ferrors.angularjs.org%252F1.5.9%252F%2524injector%252Fnomod%253Fp0%253Dui.bootstrap%250A%2520%2520%2520at%2520Anonymous%2520function%2520(file%253A%252F%252F%252Fd%253A%252Fvinoth%252Feai%252Fmetlife.eai-newlayout%252Fmetlife.eai%252Fangular%252Flib%252Fangular.min.js%253A25%253A229)%250A%2520%2520%2520at%2520b%2520(file%253A%252F%252F%252Fd%253A""</p>

<p>So, give me any suggestion to resolve this issue. thanks.</p>
",https://stackoverflow.com/questions/46158280/how-to-mock-the-dependencies-of-module-in-angular-js-using-jasmine,"['angularjs', 'unit-testing', 'jasmine']",146,FALSE,0,1
Including external .js files for unit tests,"<p>I am trying to run coverage tests for my JavaScript unit tests (written in QUnit [not my idea, legacy project]) and run them via command line.
Problem i am facing is references to external bits of code.
Look at example bellow:</p>

<p>Code:</p>

<pre><code>var DateHelper = function() {
return {
    GetUtcDate: function (date) {
            if (DateTypeChecker.Data[""date""]) {
                return new Date();
            }
            return date;
    }
}    
</code></pre>

<p>Test:</p>

<pre><code>QUnit.test('GetUtcNow - compare UTC date', function(assert) {
  var currentUtcDate = DateHelper.GetUtcNow();
  var nowDate = new Date();

  assert.equal(nowDate.getUTCFullYear() == currentUtcDate.getFullYear(), 'dates are the same');
});
</code></pre>

<p>So a very simple test that checks two dates, this works lovely when run in the browser, because the external javascript file containing <code>DateTypeChecker</code> is loaded in the HEAD.
But this test fails in the command line as <code>node</code> (or w/e is performing the test) doesn't have a reference to <code>DateTypeChecker</code> object.</p>

<p>My question is, how do i fix this, so that the file for <code>DateTypeChecker</code> is loaded/required? (i know that i can do this with RequireJS, but i don't wan't to add more dependencies and frameworks)</p>

<p>I think this is a general question for <code>js</code> unit testing (not just QUnit).</p>
",https://stackoverflow.com/questions/44000165/including-external-js-files-for-unit-tests,"['javascript', 'jquery', 'node.js', 'tdd', 'qunit']",1472,TRUE,0,1
VS 2015 Express not discovering/or buggy built in Unit Test,"<p>my problem is that VS 2015 Express doesn't discover/are buggy the Unit Tests that are built in VS, my code looks like this: </p>

<pre><code>[TestClass]
    public class UnitTest1
    {
        [TestClass]
        public class Service1Test
        {
            [TestMethod]
            public void Test1()
            {
                Assert.IsTrue(true);
            }
        }
    }
</code></pre>

<p>Dunno why but VS doesn't discover even this basic Unit Test,nor other ones, interestingly if I let the PC for about 5-10 mins VS finally discover the Unit Tests :</p>

<p><a href=""https://i.stack.imgur.com/OGyxv.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/OGyxv.png"" alt=""After 5-10 min""></a></p>

<p>Also if I try to run it I have to wait another 5 to 10 mins just to run this very basic Unit Test, here is a gift to show what I'm talking about : </p>

<p><a href=""https://giphy.com/gifs/l0Iy6YRszqsz6720M"" rel=""nofollow noreferrer"">GIF Buggy Unit Testing</a></p>

<p>And finally after 5-10 mins the unit test is done: 
<a href=""https://i.stack.imgur.com/ZqRak.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ZqRak.png"" alt=""enter image description here""></a></p>

<p>Can anyone help me? Why does VS behaves like this? At this pace currently I cant work, thanks. </p>

<blockquote>
  <p>EDIT: Even when I don't nest Test Classes VS doesn't run my Unit Tests</p>
</blockquote>
",https://stackoverflow.com/questions/42633369/vs-2015-express-not-discovering-or-buggy-built-in-unit-test,"['c#', 'visual-studio', 'unit-testing']",41,FALSE,0,0
Custom dependency filters for targets in makefiles,"<p>I am working with a legacy library and am trying to shoehorn in a bit of unit testing to help me with development. In working with that I have found that if I can create target specific filters on my dependencies, that would make adapting their makefiles to my unit tests a bit easier. Currently I would do something like this</p>

<pre><code>    var_list = input1 input2
    out_list = $(var_list:%=%.txt)

    all_deps = dep1 dep2 dep3

    input1_filter = dep2
    input2_filter = dep1 dep3

    all: $(out_list)

    input1.txt: %.txt: % $(filter-out $(input1_filter),$(all_deps))
        @echo ""reqs = $?""
        @echo ""$&lt; &gt; $@""
        @echo $&lt; &gt; $@

    input2.txt: %.txt: % $(filter-out $(input2_filter),$(all_deps))
        @echo ""reqs = $?""
        @echo ""$&lt; &gt; $@""
        @echo $&lt; &gt; $@

    clean:
       @rm $(out_list)
</code></pre>

<p>Obviously the to rules for <code>input1.txt</code> and <code>input2.txt</code> are nearly identical, so it would be great if one could write</p>

<pre><code>    var_list = input1 input2
    out_list = $(var_list:%=%.txt)

    all_deps = dep1 dep2 dep3

    input1_filter = dep2
    input2_filter = dep1 dep3

    all: $(out_list)

    $(out_list): %.txt: % $(filter-out $(%_filter),$(all_deps))
        @echo ""reqs = $?""
        @echo ""$&lt; &gt; $@""
        @echo $&lt; &gt; $@

    clean:
       @rm $(out_list)
</code></pre>

<p>Which means that for every target I make, I only need to specify a corresponding <code>_filter</code> variable and the makefile would take care of the rest. However I still haven't been able to get this to work. I found out that one can reference these variables in the body of the rule, e.g. one can write <code>$(filter-out $($&lt;_filter),$(all_deps))</code> in the body but not in the dependency list.</p>
",https://stackoverflow.com/questions/45566677/custom-dependency-filters-for-targets-in-makefiles,"['makefile', 'gnu-make']",761,TRUE,0,1
clover@eclipse : tests not relaunched at new build,"<p>I am trying to use clover (), a unit-testing plugin for Eclipse, but I wonder about the utility of the option ""toggle whether clover instrumentation is performed during compilation for the selected project"". </p>

<p>I guessed it has the purpose of launch again the tests and the code coverage after a SAVE option and the following build, but in a dummy project a modification followed by a new build makes the color of the text under test becoming red, but if I modify again the test (this time by setting the test in order to pass) the code coverage stays red, and the tests aren't launched again.</p>

<p>Am I missing something? Is this behavior the correct one? (I mean continuous testing and nearly real time code coverage, at least at each saving).</p>

<p>I use Eclipse Neon, JDK 8 x64 for Windows.</p>
",https://stackoverflow.com/questions/46991594/clovereclipse-tests-not-relaunched-at-new-build,"['java', 'eclipse', 'unit-testing', 'code-coverage', 'clover']",91,FALSE,0,0
Mocking service when testing controller in Karma for angularjs,"<p>I am working on the Single Page Application with AngularJS project for the Treehouse Full Stack JavaScript TechDegree and I am trying to do unit tests on the controllers.  To test the controllers that make api calls to the dataService I have to mock the dataService and I can not figure out how to do this correctly.  I have read article after article on unit testing angular and I am so lost that I have no idea what to do next.</p>

<p>controllers.js:</p>

<pre><code>(function() {
  'use strict';
  angular.module('app')
  .controller('RecipesController', function(dataService,$location) {
    const vm = this;

    vm.init = () =&gt; {
      vm.hidden = true;
      dataService.getAllRecipes(function(response) {
        vm.recipes = response.data;
        vm.getCategories(response.data);
      });
    }

    vm.selectCategory = (category) =&gt; {
      if (category === null) {
        vm.init();
      } else {
        dataService.getCategory(category,function(response) {
          vm.recipes = response.data;
        });
      }
    };

    vm.getCategories = (data) =&gt; {
      let categories = new Set();
      for (let item of data) {
        categories.add(item.category);
      }
      vm.categories = Array.from(categories);
    };

    vm.addRecipe = () =&gt; {
      $location.path('/add');
    }

    vm.deleteRecipe = (recipe,$index) =&gt; {
      vm.toDelete = recipe.name;
      vm.hidden = false;
      vm.deleteIt = () =&gt; {
        vm.hidden = true;
        dataService.deleteRecipe(recipe._id,function(response) {
          vm.init();
        });
      }
    }

    vm.init();
  })
  .controller('RecipeDetailController', function($scope,dataService,$location) {
    const vm = this;
    const init = () =&gt; {
      const path = $location.path();
      if (path.includes(""edit"")) {
        let id = path.slice(6);
        dataService.getID(id,function(response) {
          vm.recipe = response.data;
          vm.title = response.data.name;
          vm.editCategory = response.data.category;
        });
      } else if (path.includes(""add"")) {
        vm.recipe = {
          name: """",
          description: """",
          category: """",
          prepTime: 0,
          cookTime: 0,
          ingredients: [
            {
              foodItem: """",
              condition: """",
              amount: """"
            }
          ],
          steps: [
            {
              description: """"
            }
          ]
        }
        vm.title = 'Add New Recipe.'
      }

      dataService.getAllCategories(function (response) {
        vm.categories = response.data;
        let index = response.data.findIndex(item =&gt; item.name === $scope.editCategory);
        if (index === -1) {
          vm.initial = {""name"": ""Choose a Category""};
        } else {
          vm.initial = $scope.categories[index];
        }
      });

      dataService.getAllFoodItems(function (response) {
        vm.foods = response.data;
      });
    }

    vm.addItem = (item) =&gt; {
      if (item === 'ingredient') {
        vm.recipe.ingredients.push({amount: ""amount"", condition: ""condition"", foodItem: """"});
      } else if (item === 'step') {
        vm.recipe.steps.push({description: ""description""});
      }
    };

    vm.deleteItem = (item,$index) =&gt; {
      if (item === 'ingredient') {
        vm.recipe.ingredients.splice($index,1);
      } else if (item === 'step') {
        vm.recipe.steps.splice($index,1);
      }

    }

    vm.saveChanges = (recipe) =&gt; {

      vm.errors = [];

      const buildErrorArray = (errorArray) =&gt; {
        for (let item of errorArray) {
          vm.errors.push(item.userMessage);
        }
      }

      const collectErrors = (response) =&gt; {
        if (response.data.errors.category) { buildErrorArray(response.data.errors.category) }
        if (response.data.errors.ingredients) { buildErrorArray(response.data.errors.ingredients) }
        if (response.data.errors.name) { buildErrorArray(response.data.errors.name) }
        if (response.data.errors.steps) { buildErrorArray(response.data.errors.steps) }
      }

      if (recipe._id) {
        dataService.updateID(recipe,function(response) {
          $location.path('/');
          }, function(response) {
            collectErrors(response)
        });
      } else {
        dataService.addRecipe(recipe,function(response) {
          $location.path('/');
          }, function(response) {
            collectErrors(response)
        });
      }

    }

    vm.cancelChanges = () =&gt; {
      $location.path('/');
    }

    init();

  });
}());
</code></pre>

<p>services.js:</p>

<pre><code>(function() {
  'use strict';
  angular.module('app')
  .service('dataService', function($http,errors,httpErrors) {

    this.getAllRecipes = function (callback) {
      $http.get('http://localhost:5000/api/recipes')
      .then(callback,httpErrors.display('HTTP Error'))
      .catch(errors.catch());
    };

    this.getAllCategories = function (callback) {
      $http.get('http://localhost:5000/api/categories')
      .then(callback,httpErrors.display('HTTP Error'))
      .catch(errors.catch());
    };

    this.getAllFoodItems = function (callback) {
      $http.get('http://localhost:5000/api/fooditems')
      .then(callback,httpErrors.display('HTTP Error'))
      .catch(errors.catch());
    };

    this.getCategory = function(category,callback) {
      $http.get('http://localhost:5000/api/recipes?category=' + category)
      .then(callback,httpErrors.display('HTTP Error'))
      .catch(errors.catch());
    };

    this.getID = function (id,callback) {
      $http.get('http://localhost:5000/api/recipes/' + id)
      .then(callback,httpErrors.display('HTTP Error'))
      .catch(errors.catch());
    };

    this.updateID = function (data,success,error) {
      $http.put('http://localhost:5000/api/recipes/' + data._id, data)
      .then(success,error).catch(errors.catch());
    };

    this.addRecipe = function (data,success,error) {
      $http.post('http://localhost:5000/api/recipes', data)
      .then(success,error).catch(errors.catch());
    };

    this.deleteRecipe = function (id,callback) {
      $http.delete('http://localhost:5000/api/recipes/' + id)
      .then(callback,httpErrors.display('HTTP Error'))
      .catch(errors.catch());
    };

  });
}());
</code></pre>

<p>controllersSpec.js:</p>

<pre><code>describe(""Unit Testing Controllers"", function() {

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

  let $scope;
  let getAllRecipesMock;

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

    getAllRecipesMock = {
      getAllRecipes: function() {
        var deferred = $q.defer();
        deferred.resolve([{name: ""recipename""}]);
        return deferred.promise;
      }            
    }
  }));

  it('has a test to test that tests are testing', function() {
    expect(2 + 2).toEqual(4);
  });

  it('should have a RecipesController', function() {
    const controller = $controller('RecipesController',{$scope:$scope});
    expect(controller).toBeDefined();
  });

  it('should have a RecipeDetailController', function() {
    const controller = $controller('RecipeDetailController',{$scope:$scope});
    expect(controller).toBeDefined();
  });

  it('should call the getAllRecipes service and return response', inject(function() {
    const controller = $controller('RecipesController',{$scope:$scope,dataService:getAllRecipesMock});
    $scope.$digest();
    expect(controller.recipes).toBe([{name: ""recipename""}]);
  }));

  it('should remove duplicate categories', function() {
    const controller = $controller('RecipesController',{$scope:$scope});
    let data = [{'category':'dog'},{'category':'cat'},{'category':'horse'},{'category':'dog'},{'category':'cow'}];
    controller.getCategories(data);
    expect(controller.categories).toEqual(['dog','cat','horse','cow']);
  });

  it('should take you to the /add route when the addRecipe method is called', inject(function($location) {
    const controller = $controller('RecipesController',{$scope:$scope});
    controller.addRecipe();
    expect($location.path()).toEqual('/add');
  }));

});
</code></pre>

<p>This is the result I get when I run the tests:</p>

<pre><code> Unit Testing Controllers
    √has a test to test that tests are testing
    √should have a RecipesController
    √should have a RecipeDetailController
    ×should call the getAllRecipes service and return response
        Expected undefined to be [ Object({ name: 'recipename' }) ].
            at Object.&lt;anonymous&gt; (test/controllersSpec.js:38:32)
            at Object.invoke (node_modules/angular/angular.js:4839:19)
            at Object.WorkFn (node_modules/angular-mocks/angular-mocks.js:3155:20)

    √should remove duplicate categories
    √should take you to the /add route when the addRecipe method is called

Chrome 55.0.2883 (Windows 10 0.0.0): Executed 6 of 6 (1 FAILED) (0.235 secs / 0.084 secs)
TOTAL: 1 FAILED, 5 SUCCESS


1) should call the getAllRecipes service and return response
     Unit Testing Controllers
     Expected undefined to be [ Object({ name: 'recipename' }) ].
    at Object.&lt;anonymous&gt; (test/controllersSpec.js:38:32)
    at Object.invoke (node_modules/angular/angular.js:4839:19)
    at Object.WorkFn (node_modules/angular-mocks/angular-mocks.js:3155:20)
</code></pre>

<p><strong>EDIT</strong></p>

<p>I decided to change the service to return a promise instead of a callback:</p>

<pre><code>this.getAllRecipes = function () {
     return $http.get('http://localhost:5000/api/recipes');
    };
</code></pre>

<p>Then I changed the corresponding function in the controller:</p>

<pre><code>vm.init = () =&gt; {
      vm.hidden = true;
      let allRecipes = dataService.getAllRecipes();
      allRecipes.then(function(response) {
        vm.recipes = response.data;
        vm.getCategories(response.data);
      },httpErrors.display('HTTP Error'))
      .catch(errors.catch());
    }
</code></pre>

<p>but I'm still getting</p>

<p><code>Expected undefined to be [ Object({ name: 'recipename' }) ].</code></p>

<p>Am I not implementing the promise correctly?  Is there still something in my test that I'm missing?</p>
",https://stackoverflow.com/questions/41538337/mocking-service-when-testing-controller-in-karma-for-angularjs,"['javascript', 'angularjs', 'unit-testing']",1320,TRUE,0,1
How to use PHPUnit with TestCaseTrait,"<p>I am newbie in unit testing. I read <a href=""https://phpunit.de/manual/current/en/database.html"" rel=""nofollow noreferrer"">documentation</a> and try to do the same.</p>

<p>First of all, I have next environment:</p>

<pre><code>$ php -v
PHP 7.0.15-1+deb.sury.org~trusty+1 (cli) (built: Jan 20 2017 09:16:11) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies with Zend OPcache v7.0.15-1+deb.sury.org~trusty+1, Copyright (c) 1999-2017, by Zend Technologies

$ cat composer.json 
...
""require-dev"": {
    ""phpunit/phpunit"": ""^6.0"",
    ""phpunit/dbunit"": ""^3.0""
},
...
</code></pre>

<p>I have /src, /tests and /vendor directories. Composer autoloader works perfect.</p>

<p>My PHP-project is tightly coupled with MySQL database and all I want is unit test these functionality.</p>

<pre><code>$ cat tests/phpunit.xml 
&lt;phpunit&gt;
    &lt;php&gt;
        &lt;ini name=""display_errors"" value=""On"" /&gt;
        &lt;ini name=""display_startup_errors"" value=""On"" /&gt;
    &lt;/php&gt;
&lt;/phpunit&gt;
</code></pre>

<p>And the test:</p>

<pre><code>$ cat tests/SimpleTest.php 
&lt;?php
use PHPUnit\Framework\TestCase;
use PHPUnit\DbUnit\TestCaseTrait;

require_once(__DIR__.'/../vendor/autoload.php');

class SimpleTest extends TestCase
{
    // use TestCaseTrait;

    protected function getConnection() {}
    protected function getDataSet() {}

    public function testFirstExample()
    {
        $this-&gt;assertEquals(1, 1);
    }

    public function testSecondExample()
    {
        $this-&gt;assertEquals(1, 0);
    }

}
?&gt;

$ phpunit --testdox --verbose --configuration=tests/phpunit.xml tests/SimpleTest.php 
PHPUnit 6.0.6 by Sebastian Bergmann and contributors.

Runtime:       PHP 7.0.15-1+deb.sury.org~trusty+1
Configuration: /home/ubuntu/workspace/tests/phpunit.xml

Simple
 [x] First example
 [ ] Second example
</code></pre>

<p>Everything fine and works as expected until I uncomment the line <code>use TestCaseTrait;</code>. Since this moment, the tests don't work.
They even don't executed (I checked it by adding next code: <code>fwrite(STDERR, 'Here we are!')</code>) inside the test-functions.</p>

<p>The question: what is wrong with <code>use TestCaseTrait;</code> statement? Why does it broke the whole test? How can I solve it?</p>

<p>Thank you!
P.S. Sorry for my English.</p>

<hr>

<p>Conclusion:
It is strange, but the problem was in <code>setUp()</code> function. You have to add it in the test! When I did it, my test became work properly...</p>
",https://stackoverflow.com/questions/42313807/how-to-use-phpunit-with-testcasetrait,"['php', 'unit-testing', 'phpunit']",801,FALSE,0,1
Testing a bot using Direct Line,"<p>I have developed a bot that I want to  test. 
Due to few discussions (<a href=""https://stackoverflow.com/questions/43264251/conversations-sendtoconversationasync-crashes-on-unit-testing/43265239#43265239"">Conversations.SendToConversationAsync crashes on Unit testing</a>) it seems that an approach is to make use of Direct Line. The bot must be hosted locally, so that the sent messages can be captured and evaluated on the bot. On this point, I am not sure about two aspects. </p>

<ol>
<li>Isn’t there any alternative way to do functional test?</li>
<li>I was planning to do the functional test on the localhost using Emualtor and Visual Studio. Checking this github page (<a href=""https://github.com/Microsoft/AzureBot/tree/master/AzureBot.Tests"" rel=""nofollow noreferrer"">https://github.com/Microsoft/AzureBot/tree/master/AzureBot.Tests</a>) I understand that a test case can be converted into a code in an easy way writing down an action and its expected reply.
However I don’t understand the requirement and benefits of using Direct Line for the functional test?</li>
</ol>
",https://stackoverflow.com/questions/45134504/testing-a-bot-using-direct-line,"['botframework', 'functional-testing']",771,TRUE,0,1
Web API Request is null in ExecuteAsync method of ApiController,"<p>I am trying to access the <code>Request</code> property in my <code>ApiController</code>-derived class.</p>

<p>For some reason, <code>Request</code> is null in <code>ExecuteAsync</code> method. I've seen the other questions, so before you ask:</p>

<ul>
<li>I am <strong>not</strong> initializing the controller by calling the constructor, it's a regular HTTP POST API call from an external device.</li>
<li>I've tried the same request locally with Fiddler, the behavior is identical.</li>
<li>I am not unit testing.</li>
<li>Before hitting the <code>ExecuteAsync</code> method, my request passes through a delegating handler, and in the delegating handler, my request object exists (I even add some properties without any problem).</li>
<li>At the last line of delegating handler, I call <code>return await base.SendAsync(request, cancellationToken);</code> without a problem and <code>request</code> <strong>exists</strong>.</li>
<li>Right after than in API controller, <code>HttpContext.Current.Request</code> is not null and accessible without problem.</li>
<li>In API controller, <code>RequestContext</code> is not null and accessible without problem.</li>
<li>In that same line, <code>Request</code> is null.</li>
</ul>

<p>Why would this occur? I'm on Web API 2.2 (and MVC 5, if relevant).</p>
",https://stackoverflow.com/questions/42782141/web-api-request-is-null-in-executeasync-method-of-apicontroller,"['c#', 'asp.net', 'asp.net-web-api', 'asp.net-web-api2']",2935,TRUE,4,1
Context Related Problems inside MVP presenter,"<p>I am new to android MVP pattern and working on my project i have some basic problem related to Android Context in the presenter. Although there are many answers related to this but i didn't get a perfect one which can solve my problem.</p>

<p>I have following queries:</p>

<ol>
<li>how to access shared preferences inside presenter.</li>
<li>how to access other system services inside presenter.</li>
<li>if i am working on SQLite Databases then during any transaction in my database which is done by call from presenter to my SQLite Helper class need context to access database.</li>
</ol>

<p>If i will pass my activity context in presenter then it will a problem during unit testing, also it is a violation according to MVP Format.
I need a perfect solution so that my code quality is not degraded.</p>

<p><strong>Note</strong>: I dont want to use dagger tool so the answer should be dagger independent</p>
",https://stackoverflow.com/questions/44736099/context-related-problems-inside-mvp-presenter,"['android', 'sqlite', 'mvp']",726,TRUE,4,1
How do I unit test Spring Controller using annotations?,"<p>I am new to the concept of unit testing with Spring controllers. I'm following some examples I found online and trying to implement their testing strategy. This is my basic controller:</p>

<pre><code>@Controller
public class GreetingController {

    @RequestMapping(""/greeting"")
    public String greeting(@RequestParam(value = ""name2"", required = false, defaultValue = ""World2"") String name2,
                           Model model) {

        model.addAttribute(""name"", name2);
        return ""greeting"";
    }

}
</code></pre>

<p>This is my unit test:</p>

<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class ControllerGreetingTest {

    private MockMvc mockMvc;

    @Autowired
    GreetingController greetingController;
    @Test
    public void shouldReturnSomething() throws Exception {
        mockMvc.perform(get(""/greeting""))
                .andExpect(status().isOk())
                .andExpect(view().name(""greeting""));
    }

}
</code></pre>

<p>Seems pretty straight forward but I get the following error:</p>

<blockquote>
  <p>java.lang.IllegalStateException: Neither GenericXmlWebContextLoader
  nor AnnotationConfigWebContextLoader was able to detect defaults, and
  no ApplicationContextInitializers were declared for context
  configuration [ContextConfigurationAttributes@1698539 declaringClass =
  'com.practice.demo.ControllerGreetingTest', locations = '{}', classes
  = '{}', inheritLocations = true, initializers = '{}', inheritInitializers = true, name = [null], contextLoaderClass =
  'org.springframework.test.context.ContextLoader']</p>
</blockquote>

<p>I'm assuming I have to add a parameter to the <code>@ContextConfiguration</code> annotation but not sure what to include in there.</p>

<p>EDIT = This is what I have so far:</p>

<pre><code>public class ControllerGreetingTest {

    private MockMvc mockMvc;

   @Before
    public void setup(){
        this.mockMvc = standaloneSetup(new GreetingController()).build();
    }

    @Test
    public void shouldReturnDefaultString() throws Exception {
        mockMvc.perform(get(""/greeting""))
                .andExpect(status().isOk())
                .andExpect(view().name(""greetings""))
                .andExpect(model().attribute(""name"",""World2""));
    }

}
</code></pre>

<p>It does the job but it doesn't use any of the Spring annotations like I tried to do before.. this approach is not good so trying to figure out why I keep gettings errors whenever I include the annotations in my test file.</p>

<p>My POM:</p>

<pre><code>&lt;dependencies&gt;
    &lt;!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
        &lt;version&gt;1.5.7.RELEASE&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-data-mongodb&lt;/artifactId&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-thymeleaf&lt;/artifactId&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-devtools&lt;/artifactId&gt;
        &lt;optional&gt;true&lt;/optional&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.hamcrest&lt;/groupId&gt;
        &lt;artifactId&gt;hamcrest-all&lt;/artifactId&gt;
        &lt;version&gt;1.3&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;junit&lt;/groupId&gt;
        &lt;artifactId&gt;junit&lt;/artifactId&gt;
        &lt;scope&gt;test&lt;/scope&gt;
        &lt;exclusions&gt;
            &lt;exclusion&gt;
                &lt;artifactId&gt;hamcrest-core&lt;/artifactId&gt;
                &lt;groupId&gt;org.hamcrest&lt;/groupId&gt;
            &lt;/exclusion&gt;
        &lt;/exclusions&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.mockito&lt;/groupId&gt;
        &lt;artifactId&gt;mockito-core&lt;/artifactId&gt;
        &lt;version&gt;1.9.5&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework&lt;/groupId&gt;
        &lt;artifactId&gt;spring-test&lt;/artifactId&gt;
        &lt;version&gt;3.2.3.RELEASE&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;junit&lt;/groupId&gt;
        &lt;artifactId&gt;junit&lt;/artifactId&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver --&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.mongodb&lt;/groupId&gt;
            &lt;artifactId&gt;mongo-java-driver&lt;/artifactId&gt;
            &lt;version&gt;3.4.2&lt;/version&gt;
        &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-dependencies&lt;/artifactId&gt;
        &lt;version&gt;1.5.7.RELEASE&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;

&lt;/dependencies&gt;
</code></pre>
",https://stackoverflow.com/questions/46745900/how-do-i-unit-test-spring-controller-using-annotations,"['java', 'spring', 'spring-mvc', 'spring-boot', 'junit']",4168,TRUE,3,3
Using Moq : Mock object update automatically?,"<p>I am new to  MoQ framework. I am writing unit testing for controller using MoQ framework and here is my test method,</p>

<pre><code>var mockedItemDetail = new ItemDetail()
        {
            Name = null
        };

        var mockObject = new Mock&lt;IItem&gt;();
        mockObject.Setup(x =&gt; x.GetItemDetail()).Returns(mockedItemDetail);

        var result = myController.GetDetails() as ViewResult;
</code></pre>

<p>Here is my Controller Method,</p>

<pre><code>public ActionResult GetDetails()
    {
        var controllerItemDetail = new ItemDetail();
        controllerItemDetail = _item.GetItemDetail();
        controllerItemDetail.Name = ""Changed Name"";
        return View(""ViewName"", controllerItemDetail);
    }
</code></pre>

<p>Test runs and now I want to assert the sent mockedItemDetail and received model result controllerItemDetail.</p>

<p>In above case, mockedItemDetail property ""Name"" has null and received controllerItemDetail property Name as ""Changed Name"". </p>

<p>But whenever I debug, after calling the test method GetDetails(), </p>

<ol>
<li>My mockedItemDetail property Name is also updated as ""Changed Name"" in the current scope and I don't know why? Is this is the actual behavior of MoQ?</li>
</ol>

<p>Edited Content</p>

<p>Consider the same above case in below mock list, here the change in the mock object will not update in all contexts. i.e. The list count for mockedItemDetailList remains 0 and the list count of controllerItemDetail is 1 even after test method calls. Why?</p>

<p>Test method:</p>

<pre><code>var mockedItemDetailList = new List&lt;ItemDetail&gt;();

    var mockObject = new Mock&lt;IItem&gt;();
    mockObject.Setup(x =&gt; x.GetListOfItemDetail()).Returns(mockedItemDetailList);

    var result = myController.GetDetails() as ViewResult;
</code></pre>

<p>Controller method:</p>

<pre><code>    public ActionResult GetDetails()
{
    var controllerItemDetail = new ItemDetail();
    controllerItemDetail = _item.GetListOfItemDetail();
    controllerItemDetail.Add(new ItemDetail(){
    Name = ""Changed Name""
    });
    return View(""ViewName"", controllerItemDetail);
}
</code></pre>
",https://stackoverflow.com/questions/44963479/using-moq-mock-object-update-automatically,"['c#', 'unit-testing', 'nunit', 'moq', 'moq-3']",2163,TRUE,3,1
ReactiveUI - Cancel a command from another - Unit Test of code from documentation fails,"<p>I take the code from <a href=""https://docs.reactiveui.net/en/user-guide/commands/canceling.html"" rel=""nofollow noreferrer"">ReactiveUi website documentation</a> and try to unit test it but it fails.<br/>
It is about invoking a command to cancel another one.</p>

<p>Below is the class to test.</p>

<pre><code>public class SomeViewModel : ReactiveObject
{
    public SomeViewModel(IScheduler scheduler)
    {
        this.CancelableCommand = ReactiveCommand
            .CreateFromObservable(
                () =&gt; Observable
                    .StartAsync(DoSomethingAsync)
                    .TakeUntil(CancelCommand), outputScheduler: scheduler);
        this.CancelCommand = ReactiveCommand.Create(
            () =&gt;
            {
                Debug.WriteLine(""Cancelling"");
            },
            this.CancelableCommand.IsExecuting, scheduler);
    }

    public ReactiveCommand&lt;Unit, Unit&gt; CancelableCommand
    {
        get;
        private set;
    }

    public ReactiveCommand&lt;Unit, Unit&gt; CancelCommand
    {
        get;
        private set;
    }

    public bool IsCancelled { get; private set; }

    private async Task DoSomethingAsync(CancellationToken ct)
    {
        try
        {
            await Task.Delay(TimeSpan.FromSeconds(3), ct);
        }
        catch (TaskCanceledException)
        {
            IsCancelled = true;
        }
    }
}
</code></pre>

<p>And here is the unit test:</p>

<pre><code>[TestFixture]
[Category(""ViewModels"")]
public class SomeViewModelFixture
{
    public async Task Executing_cancel_should_cancel_cancelableTask()
    {
        var sut = new SomeViewModel(Scheduler.Immediate);
        var t = sut.CancelableCommand.Execute();
        await sut.CancelCommand.Execute();

        await t;

        Assert.IsTrue(sut.IsCancelled);
    }
}
</code></pre>

<p>The <code>CancelCommand</code> is excuted (a breakpoint on the Console log is hit) however the <code>Task.Delay</code> is never cancelled. It seems <code>TakeUntil</code> doesn't request the cancellation.</p>

<p><b>UPDATE</b><br/>
I edited the code above so that my <code>ViewModel</code> ctor takes a <code>IScheduler</code> and create the commands with it as per <a href=""https://github.com/reactiveui/ReactiveUI/issues/1108"" rel=""nofollow noreferrer"">that issue about unit testing</a> but the test still fails.<br/>
I tried both nUnit and xUnit.<br/>
I also tried to do <code>RxApp.MainThreadScheduler = Scheduler.Immediate</code> in my test setup as per <a href=""http://putridparrot.com/blog/unit-testing-a-reactiveui-viewmodel/"" rel=""nofollow noreferrer"">that article</a> but still fails.</p>

<p><b>UPDATE2</b><br />
From the solution that I marked as the answer and the comments, the simplest is not to use IScheduler in the ctor and then to write the test like that and it passes.</p>

<pre><code>[Test]
    public async Task Executing_cancel_should_cancel_cancelableTask()
    {
        var sut = new SomeViewModel();
        sut.CancelableCommand.Execute().Subscribe();
        await sut.CancelCommand.Execute();

        Assert.IsTrue(sut.IsCancelled);
    }
</code></pre>
",https://stackoverflow.com/questions/42303710/reactiveui-cancel-a-command-from-another-unit-test-of-code-from-documentatio,"['unit-testing', 'reactiveui']",459,TRUE,3,2
TFS 2017 doesn&#39;t build Fakes targets,"<p>I have a TFS 2017 Update 2 on-prem server with VS 2017 Enterprise installed. Our Build contains a Unit-Testing project which contains a Fakes assembly and works locally on the dev machines.
When build on TFS, the build fails with </p>

<blockquote>
  <p>The type or namespace name 'Fakes' does not exist in the namespace
  'Our.Product' (are you missing an assembly reference?)</p>
</blockquote>

<p>(i.e. misses/fails to generate the <code>Our.Product.Assembly.Fakes.dll</code> file)</p>

<p>I have additionally set up Fakes as suggested <a href=""https://stackoverflow.com/questions/44156571/msbuild-15-the-type-or-namespace-fakes-does-not-exist-in-the-namespace"">here</a>.</p>

<p>What baffles me is that there are no mentions of Fakes in the build log (except for the error itself and the paths where MSBuild looks for the file), even with debug verbosity. He doesn't event try to generate the Fakes assembly.</p>

<p>Are there other steps I need to take? We use the vNext build definitions.</p>

<p>Update:
This is the build step that works now, before the <code>/tv:15.0 /p:VisualStudioVersion=15.0</code> were <em>not</em> there.</p>

<p><a href=""https://i.stack.imgur.com/2yE4E.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/2yE4E.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/45035838/tfs-2017-doesnt-build-fakes-targets,"['tfs', 'tfsbuild', 'microsoft-fakes']",1236,TRUE,3,1
Calling base class method after child class __init__ from base class __init__?,"<p>This is a feature I miss in several languages and wonder if anyone has any idea how it can be done in Python.</p>

<p>The idea is that I have a base class:</p>

<pre><code>class Base(object):
    def __init__(self):
        self.my_data = 0
    def my_rebind_function(self):
        pass
</code></pre>

<p>and a derived class:</p>

<pre><code>class Child(Base):
    def __init__(self):
        super().__init__(self)
        # Do some stuff here
        self.my_rebind_function() # &lt;==== This is the line I want to get rid of
    def my_rebind_function(self):
        # Do stuff with self.my_data
</code></pre>

<p>As can be seen above, I have a rebound function which I want called <strong>after</strong> the <code>Child.__init__</code> has done its job. And I want this done for all inherited classes, so it would be great if it was performed by the base class, so I do not have to retype that line in every child class.</p>

<p>It would be nice if the language had a function like <code>__finally__</code>, operating similar to how it operates with exceptions. That is, it should run after all <code>__init__</code>-functions (of all derived classes) have been run, that would be great. So the call order would be something like:</p>

<pre><code>Base1.__init__()
...
BaseN.__init__()
LeafChild.__init__()
LeafChild.__finally__()
BaseN.__finally__()
...
Base1.__finally__()
</code></pre>

<p>And then object construction is finished. This is also kind of similar to unit testing with <code>setup</code>, <code>run</code> and <code>teardown</code> functions.</p>
",https://stackoverflow.com/questions/45000947/calling-base-class-method-after-child-class-init-from-base-class-init,"['python', 'python-3.x', 'class', 'constructor']",3559,TRUE,7,3
problems with testing and debugging datastore code in python using py.test,"<p>I am unit testing some <code>Python</code> <code>google cloud datastore</code> code using <code>py.test</code> in <code>PyCharm</code>. The code is running locally on <code>datastore emulator</code>.The problem is </p>

<ol>
<li>I have to put multiple <code>time.sleep(num_secs)</code> after the code that does <code>put_multi()</code>, <code>put()</code> etc, and run the code under debug mode, going line by line to check the results so that <code>assert</code> wouldn't fail, since even if the code runs correctly, the result got back from the <code>emulator</code> using <code>query.fetch()</code> does not reflect the changes in the <code>datastore</code>. I realised that there might be a race condition happening between <code>Python</code> and <code>datastore simulator</code>. Hence a (big?) delay in making the changes effective?</li>
<li>Sometimes, even under debug mode and using <code>emulator</code>, I encountered <code>HTTP Error 404: Service Unavailable</code>. I then have to turn on the <code>Compute Engine</code> VMs, and so the code can be working again, even turn off the VMs afterwards. That is very strange. Note that it happened when the <code>App Engine</code> is already associated with the <code>project_id</code>.</li>
</ol>

<p>I am wondering what is the best way to debug and test the <code>datastore</code> code in <code>Python</code>.</p>
",https://stackoverflow.com/questions/42396298/problems-with-testing-and-debugging-datastore-code-in-python-using-py-test,"['python-3.x', 'google-app-engine', 'google-cloud-datastore']",261,TRUE,2,1
Propagate Progress Information from Callable to Task,"<p>I am using <code>javafx.concurrent.Task</code> to do background work in our JavaFX application.</p>

<p>When unit testing such tasks, I usually just invoke <code>task.call()</code>. In contrast to <code>task.run()</code>, this will not change the state of the task (see also <a href=""https://stackoverflow.com/questions/46778025/task-run-vs-task-call-and-composition-of-multiple-tasks-into-one"">here</a>, <em>please vote for undelete</em>). If I do not call any <code>update..()</code> method, I can call <code>task.call()</code> even without the JavaFX Platform running.</p>

<p>I would like to refactor this approach to be <strong>independent from a running JavaFX environment</strong>, and <strong>move the implementation of the <code>call()</code> method</strong> into a JavaFX independent <code>Callable</code>. </p>

<p>Testing this independent class would be more simple and this callable can be easily used from within a task.</p>

<p>The question is now how can I update the callable's progress and propagate this progress information to the calling task?</p>

<p><code>Task</code> does progress updating via protected <code>update...()</code> methods and does not use a dedicated object for that (e.g. like <code>org.eclipse.core.runtime.IProgressMonitor</code>) which would make delegating this functionality easy.</p>
",https://stackoverflow.com/questions/47419949/propagate-progress-information-from-callable-to-task,"['java', 'javafx']",615,TRUE,2,1
When is it more appropriate to move logic from the VM to a custom binding in Knockout?,"<p>I would like to display the current time in my Knockout web app and have it update every second. There are 2 solutions that I'm considering and I'm trying to decide which approach is more appropriate.</p>

<p><strong>Approach 1</strong>: View Model logic</p>

<p>JS:</p>

<pre><code>vm.currentTime = ko.observable(Date.now());
setInterval(function () {
  vm.currentTime(Date.now());
}, 1000);
</code></pre>

<p>HTML:</p>

<pre><code>&lt;span data-bind=""text: currentTime""&gt;&lt;/span&gt;
</code></pre>

<p><strong>Approach 2</strong>: Custom Binding</p>

<p>JS:</p>

<pre><code>vm.getTime = function () {
  return Date.now();
};
</code></pre>

<p>HTML:</p>

<pre><code>&lt;span data-bind=""textInterval: { cb: getTime, interval: 1000 }""&gt;&lt;/span&gt;
</code></pre>

<p>The <code>textInterval</code> binding is a custom binding that would essentially invoke the callback at the specified interval and update the node with the returned value. It would also clear the interval on <code>domNodeDisposal</code>.</p>

<p>A few things to note:</p>

<ul>
<li>The logic for getting the time is actually more complex than shown and belongs in the VM and not the binding</li>
<li>Unit testing is important to us regardless of the approach</li>
</ul>

<p>I realize there's not much difference between both approaches but I'm more interested in the most <em>correct</em> approach in the Knockout philosophy. When should you move the logic from the VM to a custom binding?</p>
",https://stackoverflow.com/questions/44681509/when-is-it-more-appropriate-to-move-logic-from-the-vm-to-a-custom-binding-in-kno,"['javascript', 'knockout.js']",28,TRUE,2,1
XUnit working with .NET Core using Cake,"<p>I have a relatively simple solution. All works fine under MSBuild (in VS 2017 Mac). I'm creating a Cake build script, but I just cannot get unit testing to work. There are tons of examples, but it seems that none are valid anymore. Some call for DotnetCoreTest, most for XUnit2. Neither work at all in my project.</p>

<p>I get the following error when running XUnit2: <code>System.InvalidOperationException: Unknown test framework: could not find xunit.dll (v1) or xunit.execution.*.dll (v2) in /Users/dev/Projects/MyProject/tst/MyProject.Serialization.UnitTests/bin/Release/netcoreapp1.1</code></p>

<p>And that output is absolutely valid, the file is in fact not there. Here are the references for my unit test project:</p>

<pre><code>&lt;ItemGroup&gt;
    &lt;PackageReference Include=""Microsoft.NET.Test.Sdk"" Version=""15.0.0"" /&gt;
    &lt;PackageReference Include=""xunit"" Version=""2.2.0"" /&gt;
    &lt;PackageReference Include=""xunit.runner.visualstudio"" Version=""2.2.0"" /&gt;
    &lt;PackageReference Include=""xunit.runner.console"" Version=""2.2.0"" /&gt;
    &lt;PackageReference Include=""FluentAssertions"" Version=""4.19.2"" /&gt;
    &lt;PackageReference Include=""Moq"" Version=""4.7.99"" /&gt;
    &lt;PackageReference Include=""FluentAssertions.AspNetCore.Mvc"" Version=""0.7.0-beta1"" /&gt;
    &lt;PackageReference Include=""AutoMapper"" Version=""6.1.1"" /&gt;
    &lt;PackageReference Include=""ExpectedObjects"" Version=""1.3.0"" /&gt;
    &lt;PackageReference Include=""OpenCover"" Version=""4.6.519"" /&gt;
    &lt;PackageReference Include=""xunit.extensibility.execution"" Version=""2.2.0"" /&gt;
&lt;/ItemGroup&gt;
</code></pre>

<p>I have referenced <code>xunit.runner.console</code> AND <code>xunit.extensibility.execution</code>, yet these are not copied to the destination directory. .NET Core doesn't appear to have any way to force that, and even if I copy them manually the test assemblies still won't load.</p>

<p>Here is my Cake Test script:</p>

<pre><code>#tool nuget:?package=NUnit.ConsoleRunner&amp;version=3.4.0
#tool nuget:?package=xunit.runner.console
...
Task(""Test"")
    .IsDependentOn(""Build"")
    .Does(() =&gt;
{
    Information(""Start Running Tests"");
    XUnit2(string.Format(""./tst/**/*Tests/bin/{0}/**/*Tests.dll"", configuration), new XUnit2Settings
    {
    });
});
</code></pre>

<p>Clearly I'm missing something very basic, but with all the conflicting information out there I don't know what it is. Should I not be using XUnit?</p>
",https://stackoverflow.com/questions/46307971/xunit-working-with-net-core-using-cake,"['c#', 'unit-testing', '.net-core', 'cakebuild']",2954,TRUE,6,2
What is the correct way in Speedment to access a database schema that&#39;s different from the default one?,"<p>In my project I'm using Speedment for ORM. Of course I want my code properly tested. So I decided to create an identical copy of my default database schema which I wanted to use for unit testing. In this case the name of the original schema is ""project"" and the name of the copy is ""test_project""</p>

<p>My problem is that I don't know how to properly address the other database schema.<br>
 I know that, upon establishing a connection, I can use the method <code>withSchema(""test_project"")</code> to tell speedment which schema to use. 
This works just fine as long as I don't have any columns identifiers in my query.  </p>

<p>So this works: </p>

<p><code>List &lt;User&gt; users = userManager.stream().collect(Collectors.toList());</code> </p>

<p>whereas this doesn't:  </p>

<pre><code>List &lt;User&gt; users = userManager.stream().filter(User.UID.equal(id)).collect(Collectors.toList());  
</code></pre>

<p>It's telling me this:  <code>Unknown column 'project.User.uid' in 'where clause</code>  </p>

<p>I don't really understand what's going on there. (Note: I'm quite new to Speedment).<br>
My question is: How can I access my other schema with all its rows properly addressed to it? </p>
",https://stackoverflow.com/questions/43959360/what-is-the-correct-way-in-speedment-to-access-a-database-schema-thats-differen,"['mysql', 'speedment']",92,FALSE,1,1
Jetty+Jersey: are container-managed entity transactions possible?,"<p>I'm using hibernate/jpa 5.2.10 with Jetty 9.4.</p>

<p>Is it possible to set up Jetty in a way such that:</p>

<p>a) servlet requests (including Jersey) are wrapped in entity transactions, and</p>

<p>b) the required EntityManager is accessible from within Jersey resource classes</p>

<p>?</p>

<p>I don't want to use Spring/DI/IoC and stuff and keep things as simple and fast as possible. Are there other ways to achieve Jersey RESTful development with rapid ""RTT""?</p>

<p>Maybe I just implement a static method to create an entity manager and associate it with the current request, and set up a request listener for cleanup, and use that method explicitly inside the Jersey resource methods? Similarly I could to with the EM factory and store that inside webapp context, and use a listener for cleanup. Though, I'd prefer a trodden path, but the existing Java EE seem bent on killing unit testing to some extent.</p>
",https://stackoverflow.com/questions/45806351/jettyjersey-are-container-managed-entity-transactions-possible,"['jpa', 'transactions', 'jersey', 'jetty', 'entitymanager']",116,FALSE,1,0
get property from object using enum value from loop,"<p>In one file there are enums as follows:</p>

<pre><code>public enum RelativeFatLevels
{
    Low,
    Medium,
    High
}
</code></pre>

<p>There is a Component class in a separate file like so:</p>

<pre><code>public class Component
{        
    public Enum RelativeFatLevel;
    public double Fat;
    // other properties here
}
</code></pre>

<p>There is a FormulaOutput class in a separate file that acts like a container to hold Component objects for a formula:</p>

<pre><code>public class FormulaOutput
{
    public Component Low { get; set; }
    public Component Medium { get; set;}
    public Component High { get; set;}
}
</code></pre>

<p>In a separate unit testing file I am trying to build a generic method to replace this logic:</p>

<pre><code>private FormulaOutput GetDifferences(FormulaOutput app, FormulaOutput test)
{
    FormulaOutput container = new FormulaOutput();

    Component componentDifferencesLow = new Component();
    componentDifferencesLow.RelativeFatLevel = RelativeFatLevels.Low;

    Component componentDifferencesMedium = new Component();
    componentDifferencesMedium.RelativeFatLevel = RelativeFatLevels.Medium;

    Component componentDifferencesHigh = new Component();
    componentDifferencesHigh.RelativeFatLevel = RelativeFatLevels.High;

    container.Low = componentDifferencesLow;
    container.Medium = componentDifferencesMedium;
    container.High = componentDifferencesHigh;

    return container;
}
</code></pre>

<p>This is a pared down version - there are several properties in Component that need to be set which are not shown above (they were removed to make the code snippets more readable).</p>

<p>Below is what I've tried.  The lines that are commented out are not working.  I'm stuck on how to proceed from here.  Note that the file does include <code>using System.Reflection;</code> so I don't think that's the issue.  Also, the code to add the component to the container object doesn't exist yet - not sure how to write that either.</p>

<pre><code>private FormulaOutput GetDifferences(FormulaOutput app, FormulaOutput test)
{
    FormulaOutput container = new FormulaOutput();

    foreach (RelativeFatLevels relativeFatLevel in Enum.GetValues(typeof(RelativeFatLevels)))
    {
        Component componentDifferences = new Component();
        //componentDifferences.RelativeFatLevel = test.Low.RelativeFatLevel;
        //componentDifferences.RelativeFatLevel; 
        //PropertyInfo xyz = test.GetType().GetProperty(relativeFatLevel.ToString()).GetValue(test, null);
        //PropertyInfo abc = typeof(FormulaOutput).GetProperty(relativeFatLevel.ToString()).GetValue(test, null);
        //Type type = typeof(FormulaOutput);
        //var aaa = type.GetProperty(relativeFatLevel.ToString()).GetValue(test, null);
        //Component current = typeof(FormulaOutput).GetProperty(relativeFatLevel.ToString()).GetValue(test, null);
    }

    return container;
}
</code></pre>
",https://stackoverflow.com/questions/46331661/get-property-from-object-using-enum-value-from-loop,['c#'],381,TRUE,1,2
How can I test my asynchronous code in a restify HTTP handler?,"<p>I have a function in my Restify project that handles an HTTP GET request. After some processing it uses Sequelize to find the user entity for my current session. The <code>User.findOne</code> function returns a promise and depending on the result of that promise, I'm sending an HTTP response with 200 or 404.</p>

<pre><code>static getMe(req, res, next) {
    const userInfo = BaseController.getUserSession(req);

    // hard to test this part
    User.findOne({
      where: {email: userInfo.email}
    }).then(function(user) {
      if (user) BaseController.respondWith200(res, user);
      else BaseController.respondWith404(res, 'User not found.');
    }, function(error) {
      BaseController.respondWith404(res, error);
    }).then(function() {
      return next();
    });
}
</code></pre>

<p>I've tried a few different libraries to help with testing so I'm sorry if this is a messy combination of things. This is in my <code>beforeEach</code> function for my tests:</p>

<pre><code>const usersFixture = [
  {id:2, email:'ozzy@osbourne.com', facebookId:54321, displayName: 'Ozzy Osbourne'},
  {id:3, email:'zakk@wylde.com', facebookId:34521, displayName: 'Zakk Wylde'},
  {id:4, email:'john@lennon.com', facebookId:12453, displayName: 'John Lennon'}
];

this.findOneSpy = sinon.spy(function(queryObj) {
  return new Promise(function(resolve, reject) {
    const user = usersFixture.find(function(el) { return el.email === queryObj.where.email });
    if (user) resolve(user);
    else resolve(null);
  });
});

this.respondWith200Spy = sinon.spy(function(res, data) {});
this.respondWith400Spy = sinon.spy(function(res, error) {});
this.respondWith404Spy = sinon.spy(function(res, error) {});

this.controller = proxyquire('../../controllers/user-controller', {
  '../models/user': {
    findOne: this.findOneSpy
  },
  './base-controller': {
    respondWith200: this.respondWith200Spy,
    respondWith400: this.respondWith400Spy,
    respondWith404: this.respondWith404Spy
  }
});
</code></pre>

<p>And here is what one of my tests looks like:</p>

<pre><code>it('should return 200 with user data if user email matches existing user', function() {
  // THIS FUNCTION IS NEVER HIT
  this.respondWith200Spy = function(res, data) {
    data.should.equal({id:4, email:'john@lennon.com', facebookId:12453, displayName: 'John Lennon'});
    done();
  };
  const req = {session:{user:{email:'john@lennon.com'}}};
  this.controller.getMe(req, this.res, this.nextSpy);
  this.findOneSpy.should.have.been.called;
});
</code></pre>

<p>Since we aren't actually passing a callback to the function and the function doesn't really return anything (just does asynchronous things elsewhere), I can't figure out how to test it to make sure it's working right. Any help is appreciated.</p>

<p>The actual code works just fine. I'm just trying to get some quality unit testing into the project. Thanks!</p>
",https://stackoverflow.com/questions/41981792/how-can-i-test-my-asynchronous-code-in-a-restify-http-handler,"['node.js', 'sequelize.js', 'sinon', 'chai', 'restify']",528,TRUE,1,1
Using setTimeout() in React and Testing it,"<p>I realized that I have been using <code>setTimeout()</code> in my project -maybe- more than I should, I did a quick research and scroll through some open source react projects on Github and decided I should ask about it.</p>

<p>I use <code>setTimeout</code> mostly for changing the classname or adding styles to animate the DOM objects also using CSS transition, one point I thought it will be hard to write unit testing with this many setTimeout.</p>

<p>Since I came from using AngularJS, there is a <code>$timeout</code> service which has the same functionality with setTimeout, but in testing you can flush the timeout like <code>$timeout.flush()</code> and the timeout ends instantly.</p>

<p><strong>My questions;</strong></p>

<ul>
<li>Is there an alternative testable way that I can use instead setTimeout (logicly or programaticly)?</li>
<li>Is there any builtin testable function in React does the same thing with <code>setTimeout</code>?</li>
<li>Is there any react addons I can use for ""flushable"" timeout?</li>
</ul>

<p>Keep in mind I'm fairly new at reactjs and haven't write any unit test on it yet.</p>
",https://stackoverflow.com/questions/41634832/using-settimeout-in-react-and-testing-it,"['unit-testing', 'reactjs']",16895,TRUE,4,1
Karma/Jasmine Unit Test of Component with Injected Service in Angular,"<p>I am new to Karma/Jasmine unit testing, and I am attempting to write some tests for my authentication component that has an AuthService injected into it.  I also have another authentication service that is used for Microsoft (Azure) authentication injected into the general AuthService.  For building my spec, I have:</p>

<pre><code>describe('AuthAdminComponent', function () {
  let de: DebugElement;
  let comp: AuthAdminComponent;
  let fixture: ComponentFixture&lt;AuthAdminComponent&gt;;
  let authService: AuthService;

  let authServiceStub: {
    // Fill in later
  }

    beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ AuthAdminComponent ], // declare the test component
      providers: [
        {provide: AuthService, useValue: authServiceStub},
      ]
    })
    .compileComponents(); // compile template and css
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(AuthAdminComponent);
    comp = fixture.componentInstance;
    authService = TestBed.get(authService) // Get the needed service
  });

})
</code></pre>

<p>There are not any tests currently because I wanted to make sure everything is getting set up correctly.  However, when I run <code>npm test</code>, I receive:</p>

<pre><code>404: /base/node_modules/ng2-adal/core.js
Chrome 59.0.3071 (Windows 10 0.0.0) ERROR

{
[1]     ""originalErr"": {
[1]       ""__zone_symbol__currentTask"": {
[1]         ""type"": ""microTask"",
[1]         ""state"": ""notScheduled"",
[1]         ""source"": ""Promise.then"",
[1]         ""zone"": ""&lt;root&gt;"",
[1]         ""cancelFn"": null,
[1]         ""runCount"": 0
[1]       }
[1]     },
[1]     ""__zone_symbol__currentTask"": {
[1]       ""type"": ""microTask"",
[1]       ""state"": ""notScheduled"",
[1]       ""source"": ""Promise.then"",
[1]       ""zone"": ""&lt;root&gt;"",
[1]       ""cancelFn"": null,
[1]       ""runCount"": 0
[1]     }
[1]   }
</code></pre>

<p>I don't particularly understand where I've gone wrong.  Apparently, it's not finding that .js file, but that .js file does exist in that location and works fine when I run the Angular app normally.  So I just assume I'm setting up the test incorrectly?  Any help would be appreciated.  I've been attempting to follow the Angular documentation on testing.  If this would be helpful, this is how the beginning of my AuthService looks:</p>

<pre><code>import {Injectable} from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';
import { AdalService } from 'ng2-adal/core';

@Injectable()
export class AuthService {

    public authType: string = null;
    public connection: string = null;
    public accessToken: string = null;
    public refreshToken: string = null;

    constructor(private adalService: AdalService, private http: Http) {}
</code></pre>
",https://stackoverflow.com/questions/44770590/karma-jasmine-unit-test-of-component-with-injected-service-in-angular,"['angular', 'unit-testing', 'karma-jasmine', 'adal']",1391,FALSE,0,1
Proper testing of JPA DAO with Spring,"<p>I've created simple JPA entities: Topic and Word. Topic contains a list of words.</p>

<pre><code>@ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.MERGE, CascadeType.REMOVE})
@JoinTable
private List&lt;Word&gt; words;
</code></pre>

<p>Now I want to test my DAO using an in-memory H2 database. In the test class, I write different tests for manipulating the data. But I want to get a clean database for each test, so I've added tearDown method to delete all words and topics.</p>

<p>Snippet of my test class:</p>

<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest
public class TopicServiceJpaDaoTest {
    @Autowired
    private TopicDao topicDao;

    @Autowired
    private WordDao wordDao;

    // different test methods

    @After
    public void tearDown() throws Exception {
        topicDao.deleteAll();
        wordDao.deleteAll();
    }
}
</code></pre>

<ol>
<li>But when I try to run all tests in the class I receive an error, that Entry is locked.</li>
<li>Also, when I run all my integrational tests, I receive following error: <code>Unable to acquire JDBC Connection</code>.</li>
</ol>

<p>Stack trace for the Entry is locked error:</p>

<pre><code>javax.persistence.PessimisticLockException: could not execute statement

    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.wrapLockException(AbstractEntityManagerImpl.java:1760)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1649)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1602)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:1700)
    at org.hibernate.jpa.spi.AbstractQueryImpl.executeUpdate(AbstractQueryImpl.java:70)
    at io.github.solomkinmv.glossary.persistence.dao.impl.WordServiceJpaDao.deleteAll(WordServiceJpaDao.java:66)
    at io.github.solomkinmv.glossary.persistence.dao.impl.TopicServiceJpaDaoTest.tearDown(TopicServiceJpaDaoTest.java:287)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:33)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: org.hibernate.PessimisticLockException: could not execute statement
    at org.hibernate.dialect.H2Dialect$3.convert(H2Dialect.java:370)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:95)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:207)
    at org.hibernate.hql.internal.ast.exec.BasicExecutor.doExecute(BasicExecutor.java:91)
    at org.hibernate.hql.internal.ast.exec.BasicExecutor.execute(BasicExecutor.java:60)
    at org.hibernate.hql.internal.ast.exec.DeleteExecutor.execute(DeleteExecutor.java:111)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.executeUpdate(QueryTranslatorImpl.java:429)
    at org.hibernate.engine.query.spi.HQLQueryPlan.performExecuteUpdate(HQLQueryPlan.java:374)
    at org.hibernate.internal.SessionImpl.executeUpdate(SessionImpl.java:1348)
    at org.hibernate.internal.QueryImpl.executeUpdate(QueryImpl.java:102)
    at org.hibernate.jpa.internal.QueryImpl.internalExecuteUpdate(QueryImpl.java:405)
    at org.hibernate.jpa.spi.AbstractQueryImpl.executeUpdate(AbstractQueryImpl.java:61)
    ... 34 more
Caused by: org.h2.jdbc.JdbcSQLException: Timeout trying to lock table ; SQL statement:
delete from word [50200-193]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
    at org.h2.message.DbException.get(DbException.java:168)
    at org.h2.command.Command.filterConcurrentUpdate(Command.java:307)
    at org.h2.command.Command.executeUpdate(Command.java:260)
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:160)
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:146)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
    ... 43 more
Caused by: org.h2.jdbc.JdbcSQLException: Concurrent update in table ""WORD"": another transaction has updated or deleted the same row [90131-193]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
    at org.h2.message.DbException.get(DbException.java:168)
    at org.h2.mvstore.db.MVTable.convertException(MVTable.java:898)
    at org.h2.mvstore.db.MVPrimaryIndex.remove(MVPrimaryIndex.java:168)
    at org.h2.mvstore.db.MVTable.removeRow(MVTable.java:677)
    at org.h2.command.dml.Delete.update(Delete.java:95)
    at org.h2.command.CommandContainer.update(CommandContainer.java:98)
    at org.h2.command.Command.executeUpdate(Command.java:258)
    ... 46 more
Caused by: java.lang.IllegalStateException: Entry is locked [1.4.193/101]
    at org.h2.mvstore.DataUtils.newIllegalStateException(DataUtils.java:765)
    at org.h2.mvstore.db.TransactionStore$TransactionMap.set(TransactionStore.java:1031)
    at org.h2.mvstore.db.TransactionStore$TransactionMap.remove(TransactionStore.java:989)
    at org.h2.mvstore.db.MVPrimaryIndex.remove(MVPrimaryIndex.java:162)
    ... 50 more
</code></pre>

<p>I've tried different manipulations with database URL, like adding <code>MVCC=TRUE</code>, but nothing changes.</p>

<p>Looks like my approach for unit-testing is wrong. Hot to do this the right way?</p>

<p>I don't use Spring Data, just simple JPA implementation. My DAO implementation:</p>

<pre><code>@Repository
public class TopicServiceJpaDao extends AbstractJpaDaoService implements TopicDao {
    private static final Logger LOGGER = LoggerFactory.getLogger(TopicServiceJpaDao.class);

    @Override
    public List&lt;Topic&gt; listAll() {
        EntityManager entityManager = emf.createEntityManager();

        return entityManager.createQuery(""FROM Topic"", Topic.class)
                            .getResultList();
    }

    @Override
    public Optional&lt;Topic&gt; getById(Long id) {
        EntityManager entityManager = emf.createEntityManager();

        return Optional.ofNullable(entityManager.find(Topic.class, id));
    }

    @Override
    public Topic saveOrUpdate(Topic unsavedTopic) {
        EntityManager entityManager = emf.createEntityManager();

        entityManager.getTransaction().begin();
        Topic savedTopic = entityManager.merge(unsavedTopic);
        entityManager.getTransaction().commit();
        return savedTopic;
    }

    @Override
    public void delete(Long id) {
        EntityManager entityManager = emf.createEntityManager();

        entityManager.getTransaction().begin();
        Topic entity = entityManager.find(Topic.class, id);
        if (entity == null) {
            LOGGER.error(""No such entity in the DB"");
            throw new EntityNotFoundException(""Topic id: "" + id);
        }
        entityManager.remove(entityManager.find(Topic.class, id));
        entityManager.getTransaction().commit();
    }

    @Override
    public void deleteAll() {
        EntityManager entityManager = emf.createEntityManager();

        entityManager.getTransaction().begin();
        entityManager.createQuery(""DELETE FROM Topic"").executeUpdate();
        entityManager.getTransaction().commit();
    }
}
</code></pre>
",https://stackoverflow.com/questions/41731644/proper-testing-of-jpa-dao-with-spring,"['java', 'spring', 'hibernate', 'unit-testing', 'jpa']",1789,TRUE,0,2
How to call a function that yields IEnumerable results?,"<p>Here is my server side code which is executing a SQL stored procedure and sending me some table results.</p>

<pre><code>public IEnumerable&lt;IDataRecord&gt; SomeFuncToCallDB(string pName, SqlParameter[] sqlParams, int commandTimeout = -1)
    {
        using (SqlConnection cn = GetNewConnection())
        using (SqlCommand cmd = cn.CreateCommand())
        {
            cmd.CommandText = pName;
            cmd.CommandType = CommandType.StoredProcedure;
            if (commandTimeout != -1) cmd.CommandTimeout = commandTimeout;
            if (sqlParams.Length &gt; 0) 
            { 
                FixNullParams(sqlParams); 
                cmd.Parameters.AddRange(sqlParams); 
            }
            cn.Open();
            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                while (dr.Read())
                {
                    yield return (IDataRecord)dr;
                }
                cn.Close();
            }
        }
    }
</code></pre>

<p>Here is the FixNullParams Function.</p>

<pre><code>        private void FixNullParams(SqlParameter[] parameters)
    {
        foreach (SqlParameter p in parameters) if (p.Value == null) p.Value = DBNull.Value;
    }
</code></pre>

<p>When, I call this function like this,</p>

<pre><code>                List&lt;SqlParameter&gt; parameters = new List&lt;SqlParameter&gt;();
            parameters.Add(new SqlParameter(""@AgencyFilter"", ""CountyPool""));
            IEnumerable&lt;IDataRecord&gt; dataFromDB = salesTax.SomeFuncToCallDB(""[Data].[uspSomeSQLProc]"", parameters.ToArray());
</code></pre>

<p>I get the following exception.</p>

<p><strong>""The SqlParameter is already contained by another SqlParameterCollection.""</strong></p>

<p>This happens at the line cmd.Parameters.AddRange.</p>

<p>At the same time, if I call the same function like this,</p>

<pre><code>List&lt;SqlParameter&gt; parameters = new List&lt;SqlParameter&gt;();
            parameters.Add(new SqlParameter(""@AgencyFilter"", ""CountyPool""));
            //IEnumerable&lt;IDataRecord&gt; dataFromDB = salesTax.SomeFuncToCallDB(""[Data].[uspAgenciesSelect]"", parameters.ToArray());
            foreach (IDataRecord eachRec in salesTax.SomeFuncToCallDB(""[Data].[uspSomeSQLProc]"", parameters.ToArray()))
            {
                int x = eachRec.FieldCount;

            }
</code></pre>

<p>Then it's working fine and looping through each record.</p>

<p>Here are my questions.</p>

<ol>
<li>Which is the right way to call this procedure ?</li>
<li>How is it not failing in the later call but fails in the former ?</li>
<li>If I have to write a Unit Test for this function, I just want to get IEnumerable and then assert the record count. But it looks like, I can't do this kind of test because of this Exception. So what's the right way for unit testing this function ?</li>
</ol>
",https://stackoverflow.com/questions/47731206/how-to-call-a-function-that-yields-ienumerable-results,"['c#', '.net', 'ienumerable', 'yield']",276,FALSE,0,1
Dependency injection in Umbraco or unit testing,"<p>I have made a project in Umbraco using backoffice completely.But Now I am trying to apply concept of dependency injection(which I may have used in past..but not by that specific name) in that project.
and after loads of searching.I now know the concept of dependency injection(I think),in which we are supposed to use classes and constructor to restrict the input supplied to a function in terms of type,value.</p>

<p>But how am I suppose to make that umbraco project from that.I once tried making a strongly typed.It looks much like that which I am supposed to do now.<br>
I also took reference from these articles.</p>

<p><a href=""https://stackoverflow.com/questions/24048127/is-it-possible-to-use-dependency-injection-with-umbraco-7-contentservice-event-h"">Is it possible to use dependency injection with Umbraco 7 ContentService event handlers?</a></p>

<p><a href=""https://stackoverflow.com/questions/14301389/why-does-one-use-dependency-injection"">Why does one use dependency injection?</a> </p>

<p>But still I am kind of stuck..Is there any other way to do unit testing in umbraco.</p>
",https://stackoverflow.com/questions/46235034/dependency-injection-in-umbraco-or-unit-testing,"['asp.net-mvc', 'unit-testing', 'razor', 'dependency-injection', 'umbraco']",319,TRUE,-2,1
How can I do C++ Unit Tests in Netbeans?,"<p>I attempted to follow the tutorial <a href=""https://netbeans.org/kb/docs/cnd/c-unit-test.html"" rel=""nofollow noreferrer"">here</a> to get Netbeans unit testing setup for C++. It talks about a ""Select Elements"" portion of the test setup wizard in which one selects the parts of the actual project that are available to the test. This stage in the wizard is absent with the wizard starting on ""Name and Location"":</p>

<p><a href=""https://i.stack.imgur.com/wOtYC.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/wOtYC.png"" alt=""Wizard Screenshot""></a></p>

<p>When I create a unit test without this part of the wizard, I am unable to include any headers from my project unless I include it in the format <code>#include ""../Header.h""</code> and, when I do that, g++ has problems linking the included header to the corresponding implementation. </p>

<p>What am I doing incorrectly and what do I need to do to have my unit tests work correctly?</p>

<p>NOTE: I am trying to use cppunit, but, the dialog is missing ""Select Elements"" for all 4 available testing formats (simple C, CUnit, simple C++, CPPUnit).</p>
",https://stackoverflow.com/questions/42194877/how-can-i-do-c-unit-tests-in-netbeans,"['c++', 'unit-testing', 'netbeans', 'cppunit']",1672,TRUE,0,1
How to debug TypeError &#39;str&#39; object is not callable python3 when implementing linkedList,"<p>I'm new to python3. When I run my code against unit testing on my python script, it shows me the following error:<br>
TypeError 'str' object is not callable python3 error output on terminal.
I keep getting this error. TypeError: 'str' object is not callable
I searched all my code and I don't even use the word str anywhere.</p>

<p>Error message shows up at Console. 
TypeError: 'int' object is not callable</p>

<p>I used python debugger, and it shows me that the code is giving me an error at when I call function find on line 106. ll.find('A'). After replacing my find function with another snippet below, it does not throw that TypeError anymore. I was wondering if anyone can help me out with my implementation. 
I include my original code here.</p>

<pre><code>#!python

#from __future__ import print_function


class Node(object):

    def __init__(self, data):
        """"""Initialize this node with the given data""""""
        self.data = data
        self.next = None

    def __repr__(self):
        """"""Return a string representation of this node""""""
        return 'Node({})'.format(repr(self.data))


class LinkedList(object):

    def __init__(self, iterable=None):
        """"""Initialize this linked list; append the given items, if any""""""
        self.head = None
        self.tail = None
        self.nodeCount = 0
        if iterable:
            for item in iterable:
                self.append(item)

    def __repr__(self):
        """"""Return a string representation of this linked list""""""
        return 'LinkedList({})'.format(repr(self.items()))

    def items(self):
        """"""Return a list of all items in this linked list""""""
        result = []
        current = self.head
        while current is not None:
            result.append(current.data)
            # result.append(current)
            current = current.next
        return result

    def is_empty(self):
        """"""Return True if this linked list is empty, or False""""""
        return self.head is None

    def length(self):
        """"""Return the length of this linked list by traversing its nodes""""""
        return self.nodeCount

    def append(self, item):
        """"""Insert the given item at the tail of this linked list""""""
        new_node = Node(item)
        self.nodeCount += 1

        if self.tail == None and self.head == None:
            self.tail = new_node
            self.head = new_node
        elif self.tail == self.head:
            self.tail = new_node
            self.head.next = new_node
        else:
            self.tail.next = new_node
            self.tail = new_node

    def prepend(self, item):
        """"""Insert the given item at the head of this linked list""""""
        new_node = Node(item)

        # if self.is_empty():
        #     self.tail = new_node
        #     self.head = new_node

        if self.head == None and self.tail == None:
            self.tail = new_node
            self.head = new_node
        elif self.head == self.tail:
            self.head = new_node
            self.head.next = self.tail
        else:
            new_node.next = self.head
            self.head = new_node

    def find(self, quality):
        """"""Return an item from this linked list satisfying the given quality""""""
        for item in self.items():
            if quality(item):
                return item

    def replace(self, quality, new_data):
        """"""replace an item from this linked list satisfying the given quality""""""
        current = self.head

        while current is not None:
            if quality(current.data):
                return
            current = current.next
        self.append(new_data)

def test_linked_list():
    ll = LinkedList()
    print(ll)
    ll.append('A')
    print(ll)
    ll.append('B')
    print(ll)
    ll.append('C')
    print(ll)
    print('head: ' + str(ll.head))
    print('tail: ' + str(ll.tail))
    print('length: ' + str(ll.length()))
    print(ll.length())

    # import pdb; pdb.set_trace()
    import pdb; pdb.set_trace()

    ll.delete('A')
    print(ll)
    ll.delete('C')
    print(ll)
    ll.delete('B')
    print(ll)
    print('head: ' + str(ll.head))
    print('tail: ' + str(ll.tail))
    print('length: ' + str(ll.length()))
    print(ll.length())


if __name__ == '__main__':
    test_linked_list()
</code></pre>

<p>I was able to get my code not to throw TypeError with the following code:</p>

<pre><code>#!python

#from __future__ import print_function


class Node(object):

    def __init__(self, data):
        """"""Initialize this node with the given data""""""
        self.data = data
        self.next = None
        self.previous = None

    def __repr__(self):
        """"""Return a string representation of this node""""""
        return 'Node({})'.format(repr(self.data))


class LinkedList(object):

    def __init__(self, iterable=None):
        """"""Initialize this linked list; append the given items, if any""""""
        self.head = None
        self.tail = None
        self.nodeCount = 0
        if iterable:
            for item in iterable:
                self.append(item)

    def __repr__(self):
        """"""Return a string representation of this linked list""""""
        return 'LinkedList({})'.format(repr(self.items()))

    def items(self):
        """"""Return a list of all items in this linked list""""""
        result = []
        current = self.head
        while current is not None:
            result.append(current.data)
            # result.append(current)
            current = current.next
        return result

    def is_empty(self):
        """"""Return True if this linked list is empty, or False""""""
        return self.head is None

    def length(self):
        """"""Return the length of this linked list by traversing its nodes""""""
        return self.nodeCount

    def append(self, item):
        """"""Insert the given item at the tail of this linked list""""""
        new_node = Node(item)
        self.nodeCount += 1

        if self.tail == None and self.head == None:
            self.tail = new_node
            self.head = new_node
        elif self.tail == self.head:
            self.tail = new_node
            self.head.next = new_node
        else:
            self.tail.next = new_node
            self.tail = new_node

    def prepend(self, item):
        """"""Insert the given item at the head of this linked list""""""
        new_node = Node(item)

        # if self.is_empty():
        #     self.tail = new_node
        #     self.head = new_node

        if self.head == None and self.tail == None:
            self.tail = new_node
            self.head = new_node
        elif self.head == self.tail:
            self.head = new_node
            self.head.next = self.tail
        else:
            new_node.next = self.head
            self.head = new_node

    def delete(self, item):
        """"""Delete the given item from this linked list, or raise ValueError""""""
        current = self.head
        previous = None
        while current is not None:
            if current.data == item:
                if current is not self.head and current is not self.tail:
                    previous.next = current.next
                    current.next = None
                    break
                if current is self.head:
                    self.head = current.next
                    current.next = None
                if current is self.tail:
                    if previous is not None:
                        previous.next = None
                    self.tail = previous
                return
            previous = current
            current = current.next
        raise ValueError('Item not found: {}'.format(item))


    def find(self, quality):
        """"""Return an item from this linked list satisfying the given quality""""""
        for item in self.items():
            if quality(item):
                return item

    def replace(self, quality, new_data):
        """"""replace an item from this linked list satisfying the given quality""""""
        current = self.head

        while current is not None:
            if quality(current.data):
                return
            current = current.next
        self.append(new_data)


    def replace(self, item, new_item):
        """"""replace an item with new_item by using the helper function finding the item""""""
        node = self.find_node(item)
        node.data = new_item

    def find_node(self, item):
        """"""Returns the first node it encounters where data is equal to item""""""
        current_node = self.head
        while current_node is not None:
            if current_node.data == item:
                return current_node
            current_node = current_node.next

def test_linked_list():
    ll = LinkedList()
    print(ll)
    ll.append('A')
    print(ll)
    ll.append('B')
    print(ll)
    ll.append('C')
    print(ll)
    print('head: ' + str(ll.head))
    print('tail: ' + str(ll.tail))
    print(ll.length())

    # import pdb; pdb.set_trace()
    ll.delete('A')
    print(ll)
    ll.delete('C')
    print(ll)
    ll.delete('B')
    print(ll)
    print('head: ' + str(ll.head))
    print('tail: ' + str(ll.tail))
    print(ll.length())

    ll.append('A')
    print(ll)
    ll.append('B')
    print(ll)
    ll.append('C')
    print(ll)
    import pdb; pdb.set_trace()

    ll.find_node('A')
    print(""___________________"")
    ll.replace('B', 'A')
    ll.replace('A', 'M')
    print(ll)

if __name__ == '__main__':
    test_linked_list()
</code></pre>

<p>output of the code:</p>

<pre><code>LinkedList([])
LinkedList(['A'])
LinkedList(['A', 'B'])
LinkedList(['A', 'B', 'C'])
head: Node('A')
tail: Node('C')
3
LinkedList(['B', 'C'])
LinkedList(['B'])
LinkedList([])
head: None
tail: None
3
LinkedList(['A'])
LinkedList(['A', 'B'])
LinkedList(['A', 'B', 'C'])
&gt; linkedlist.py(170)test_linked_list()
-&gt; ll.find_node('A')
(Pdb) c
TypeError: 'int' object is not callable
</code></pre>
",https://stackoverflow.com/questions/46656563/how-to-debug-typeerror-str-object-is-not-callable-python3-when-implementing-li,"['python-3.x', 'linked-list']",304,FALSE,0,0
Increasing the performance of setting of the class object while iterating throught the resultSet,"<p>I am implementing a GET REST API for faster retrieval of records</p>

<p>My Problem :
While iterating through the  resultSet consisting of 2500-5500 rows , it takes 1 minute 33 seconds to iterate, set the class objects. I want to decrease that time to under 3 seconds</p>

<p>Below given are my sample Table structure consisting of dummy data</p>

<pre><code>ID    A_ID     FIRST_NAME     LAST_NAME    ROLE_NAME

10    jb007      JAMES         BOND           ASSASIN
10    jb007      JAMES         BOND           SHARP-SHOOTER
10    jb007      JAMES         BOND           DOUBLE-AGENT
23    bs312      BOONIE        SMITH          Account Manager
23    bs312      BOONIE        SMITH          Change Manager
21    bb989      BLUNT         BORIS          DEVELOPER
21    bb989      BLUNT         BORIS          MANAGER
21    bb989      BLUNT         BORIS          SERVICE DELIVERY
34    ch201      CHRIS         HUNT           MANGER DEAL LEAD
34    ch201      CHRIS         HUNT           CEO
34    ch201      CHRIS         HUNT           COO
34    ch201      CHRIS         HUNT           MANAGER
</code></pre>

<p>As shown above i am having around  2500-5500 rows consisting of data</p>

<p>here is my actual expected response </p>

<pre><code>{
""UserSummary"": [{
        ""userId"": 10,
        ""a_id"": “jb007”,
        ""firstName"": “JAMES”,
        ""lastName"": “BOND”,
        ""roles"": “ASSASIN,SHARP-SHOOTER,DOUBLE-AGENT”
    }, {
        ""userId"": 23,
        ""a_id"": “bs312”,
        ""firstName"": “BOONIE”,
        ""lastName"": “SMITH”,
        ""roles"": “Account Manager,Change Manager”
    },
    {
        ""userId"": 21,
        ""a_id"": “bb989”,
        ""firstName"": “BLUNT”,
        ""lastName"": “BORIS”,
        ""roles"": “DEVELOPER,MANAGER,SERVICE DELIVERY”
    },
    {
        ""userId"": 34,
        ""a_id"": “ch201”,
        ""firstName"": “CHRIS”,
        ""lastName"": “HUNT”,
        ""roles"": “MANGER DEAL LEAD,CEO,COO,MANAGER”
    }
]
</code></pre>

<p>}</p>

<p>Below given is my POJO class</p>

<pre><code>public class UserSummaryResponse {
    private List&lt;UserSummary&gt; userSummary;
    public List&lt;UserSummary&gt; getSequenceUserSummary() {
        return SequenceUserSummary;
    }
    public void setSequenceUserSummary(List&lt;UserSummary&gt; sequenceUserSummary) {
        SequenceUserSummary = sequenceUserSummary;
    }   
}

public class UserSummary {

private Integer userId;
private String a_id;
private String firstName;
private String lastName;
private String Roles;
public Integer getUserId() {
    return userId;
}
public void setUserId(Integer userId) {
    this.userId = userId;
}
public String getA_id() {
    return a_id;
}
public void setA_id(String a_id) {
    this.a_id = a_id;
}
public String getFirstName() {
    return firstName;
}
public void setFirstName(String firstName) {
    this.firstName = firstName;
}
public String getLastName() {
    return lastName;
}
public void setLastName(String lastName) {
    this.lastName = lastName;
}
public String getRoles() {
    return Roles;
}
public void setRoles(String roles) {
    Roles = roles;
}


}
</code></pre>

<p>Below given is code logic that i have wrtten to iterate throught resultSet and to set the class Objects </p>

<pre><code>                UserSummaryResponse resp = new UserSummaryResponse();
                List&lt;UserSummary&gt; usLs = new ArrayList&lt;UserSummary&gt;();
                String temp = null;

                rs = ps.executeQuery();
                Integer olduserId = 0;
                temp=null;
                UserSummary usObj = new UserSummary();
                usObj=null;
                while (rs.next()) {
                            int userid = rs.getInt(1);
                            if (userid != olduserId) {
                                if (usObj != null) {
                                    if(temp != null)
                                        usObj.setRoles(temp);
                                usLs.add(usObj);
                                }
                        olduserId = userid;
                        usObj = new UserSummary();
                        usObj.setUserId(rs.getInt(1));
                        usObj.setA_id(rs.getString(2));
                        usObj.setFirstName(rs.getString(3));
                        usObj.setLastName(rs.getString(4));
                        temp = """";
                        }
                        if (temp.length() &gt; 0) {
                            temp += "","";
                            }
                        temp += rs.getString(5);
                        row_count++;
                        }
                        rs.close();
                        if (usObj != null) {
                                    if(temp != null)
                                        usObj.setRoles(temp);
                                usLs.add(usObj);
                                }
                        resp.setSequenceUserSummary(usLs);
                        return resp;
</code></pre>

<p>During Unit Testing , i had found that , its taking 1 minute 30-45 seconds to iterate through resultSet and Setting the class objects.
Is there any efficient way to increase the setting performance so that it takes less than 3 seconds and thereby increasing the GET API overall performance.</p>
",https://stackoverflow.com/questions/46627986/increasing-the-performance-of-setting-of-the-class-object-while-iterating-throug,"['java', 'spring-boot', 'jdbc', 'resultset']",42,FALSE,0,0
Howto do unittest for tornado + async def?,"<p>Environment: Python 3, tornado 4.4. The normal unittests cannot be used because methods are asynchronous. There is ttp://www.tornadoweb.org/en/stable/testing.html that explains how to do unit testing for asynchronous code. But that works with tornado coroutines ONLY. The classes I want to test are using the async def statements, and they cannot be tested this way. For example, here is a test case that uses ASyncHTTPClient.fetch and its callback parameter:</p>

<pre><code>class MyTestCase2(AsyncTestCase):
    def test_http_fetch(self):
        client = AsyncHTTPClient(self.io_loop)
        client.fetch(""http://www.tornadoweb.org/"", self.stop)
        response = self.wait()
        # Test contents of response
        self.assertIn(""FriendFeed"", response.body)
</code></pre>

<p>But my methods are declared like this:</p>

<p>class Connection:
    async def get_data(url, *args):
         # ....</p>

<p>And there is no callback. How can I ""await"" for this method from a test case?</p>

<p><strong>UPDATE:</strong> based on Jessie's answer, I created this MWE:</p>

<pre><code>import unittest

from tornado.httpclient import AsyncHTTPClient
from tornado.testing import AsyncTestCase, gen_test, main


class MyTestCase2(AsyncTestCase):
    @gen_test
    async def test_01(self):
        await self.do_more()

    async def do_more(self):
        self.assertEqual(1+1, 2)

main()
</code></pre>

<p>The result is this:</p>

<pre><code>&gt;py -3 -m test.py
E
======================================================================
ERROR: all (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute 'all'

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)
[E 170205 10:05:43 testing:731] FAIL
</code></pre>

<p>There is no traceback. But if I replace tornado.testing.main() with unittest.main() then it suddenly starts working.</p>

<p>But why? I guessed that for asnyc unit tests, I need to use tornado.testing.main ( <a href=""http://www.tornadoweb.org/en/stable/testing.html#tornado.testing.main"" rel=""nofollow noreferrer"">http://www.tornadoweb.org/en/stable/testing.html#tornado.testing.main</a> )</p>

<p>I'm confused.</p>

<p><strong>UPDATE 2:</strong> It is a bug in tornado.testing. Workaround:</p>

<pre><code>all = MyTestCase2
main()
</code></pre>
",https://stackoverflow.com/questions/42040248/howto-do-unittest-for-tornado-async-def,"['unit-testing', 'asynchronous', 'tornado', 'python-3.5', 'python-unittest']",2283,TRUE,4,1
SQL server unit test on TFS build,"<p>We has a solution which is being built by TFS and SQL server unit tests which should be run on each build. The tests part also consists of a Database project which should be deployed to localDB before tests are running. 
The config for SQL server unit test project is: </p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>&lt;configSections&gt;
        &lt;section name=""SqlUnitTesting"" type=""Microsoft.Data.Tools.Schema.Sql.UnitTesting.Configuration.SqlUnitTestingSection, Microsoft.Data.Tools.Schema.Sql.UnitTesting, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"" /&gt;
      &lt;section name=""entityFramework"" type=""System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" requirePermission=""false"" /&gt;
    &lt;!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --&gt;&lt;/configSections&gt;
  &lt;connectionStrings&gt;
    &lt;add name=""SnapDBContext"" connectionString=""Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=SampleDatabase;Integrated Security=SSPI;"" providerName=""System.Data.SqlClient"" /&gt;
  &lt;/connectionStrings&gt;
    &lt;SqlUnitTesting&gt;
        &lt;DatabaseDeployment DatabaseProjectFileName=""..\..\..\..\Database\SampleDatabase.sqlproj"" Configuration=""Debug"" /&gt;
        &lt;DataGeneration ClearDatabase=""true"" /&gt;
        &lt;ExecutionContext Provider=""System.Data.SqlClient"" ConnectionString=""Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=SampleDatabase;Integrated Security=True;Pooling=False"" CommandTimeout=""30"" /&gt;
        &lt;PrivilegedContext Provider=""System.Data.SqlClient"" ConnectionString=""Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=SampleDatabase;Integrated Security=True;Pooling=False"" CommandTimeout=""30"" /&gt;
    &lt;/SqlUnitTesting&gt;
  &lt;entityFramework&gt;
    &lt;defaultConnectionFactory type=""System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"" /&gt;
    &lt;providers&gt;
      &lt;provider invariantName=""System.Data.SqlClient"" type=""System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"" /&gt;
    &lt;/providers&gt;
  &lt;/entityFramework&gt;</code></pre>
</div>
</div>
</p>

<p>Everything work fine on my local machine but on TFS it fails with an error:</p>

<blockquote>
  <p>An error occurred while SQL Server unit testing settings were being read from the configuration file.  Click the test project, open the SQL Server Test Configuration dialog box from the SQL menu, add the settings to the dialog box, and rebuild the project.</p>
</blockquote>

<p>The guys assumes that the tests worked fine on TFS 2013 but after the upgrading to TFS 2015 we started to get this error. Tried different solutions found here and over the internet but nothing helps. What am I missing?
Thank you. </p>
",https://stackoverflow.com/questions/44367948/sql-server-unit-test-on-tfs-build,"['unit-testing', 'tfs']",408,FALSE,0,1
How to auth automatically with Google Drive Android SDK for instrumentation testing?,"<p>In order to improve app quality i'm working on testing: unit tests and UI tests. Since i'm having Google Drive support in the app with <a href=""https://developers.google.com/drive/android/"" rel=""nofollow noreferrer"">Android SDK</a> i'd like to test it and i need to auth to Google Drive account before testing (in my android app the users are able to save the files, read them, rename, etc - basic file routines).</p>

<p>In <a href=""https://developers.google.com/drive/android/auth"" rel=""nofollow noreferrer"">auth example</a> it's shown how auth is done:</p>

<pre><code>// 1. try connect
private void startAuthGoogleDrive() {
    GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
      .addApi(Drive.API)
      .addScope(Drive.SCOPE_FILE)
      .addConnectionCallbacks(this)
      .addOnConnectionFailedListener(this)
      .build();

    GoogleApiClientHolder.get().setClient(mGoogleApiClient);
    mGoogleApiClient.connect();
}

// 2. if failed - Google Drive auth intent is sent to Google Drive
// if already authorized - go to #4
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    if (connectionResult.hasResolution()) {
        Toast.makeText(this, R.string.Google_signin_required, Toast.LENGTH_LONG)
          .show();

        try {
            connectionResult.startResolutionForResult(this, ACTION_SIGNIN_GOOGLE_DRIVE); // sending intent to auth
        } catch (IntentSender.SendIntentException e) {
            // Unable to resolve, message user appropriately
        }
    } else {
        GooglePlayServicesUtil.getErrorDialog(connectionResult.getErrorCode(), this, 0).show();
    }
}

// 3. check result intent
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
...

// Google Drive signed in
    if (requestCode == ACTION_SIGNIN_GOOGLE_DRIVE &amp;&amp; resultCode == RESULT_OK) {
        // Google Drive does not provide token, just try to connect()
        // and get callback onConnected() instead
        GoogleApiClientHolder.get().getClient().connect();
    }

// 4. got connected callback
@Override
public void onConnected(Bundle bundle) {
... // ready
}
</code></pre>

<p>The problems are:</p>

<ol>
<li>No access token is returned (no possibility to auth another way (eg. manually in app activity) and just hardcode access token in the test</li>
<li>No possibility to auth right in the test as there is no possibility to interact with UI (Google Drive Auth activity)</li>
</ol>

<p>What can i do in order to automate unit testing for Google Drive?</p>

<p>I'd like to avoid moving the tests to UI tests with Espresso and keep it in instrumentation tests.</p>
",https://stackoverflow.com/questions/43620449/how-to-auth-automatically-with-google-drive-android-sdk-for-instrumentation-test,"['android', 'unit-testing', 'authentication', 'google-drive-api', 'google-drive-android-api']",260,TRUE,0,2
Using Rspec in one file like test/unit,"<p>When I have time I like to take on a challenge at <a href=""http://www.codewars.com"" rel=""nofollow noreferrer"">codewars</a>.
Until now I used <code>test/unit</code> to do my unit testing but I would like to use <code>Rspec</code> now without changing my way of working. These are small methods/files/tests so I like to keep everything together in one script.</p>

<p>I run almost all of my code using Sublime Text and get the result in a window at the bottom of the editor.</p>

<p>Here my working <code>test/unit</code> example</p>

<pre><code>require 'test/unit'

def anagrams(word, words)
  words.select { |w| w.chars.sort == word.chars.sort }
end

class MyTest &lt; Test::Unit::TestCase
  def test_fail
    assert_equal(['aabb', 'bbaa'], anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) )
    assert_equal(['carer', 'racer'], anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']) )
    assert_equal([], anagrams('laser', ['lazing', 'lazy',  'lacer']) )
  end
end
</code></pre>

<p>This gives in Sublime the following output</p>

<pre><code>Loaded suite C:/Users/.../codewars/anagram
Started
.

Finished in 0.001 seconds.
------
1 tests, 3 assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications
100% passed
------
1000.00 tests/s, 3000.00 assertions/s
[Finished in 0.3s]
</code></pre>

<p>And here what I tried for Rspec</p>

<pre><code>require 'rspec'

describe ""Anagrams"" do
  def anagrams(word, words)
    words.select { |w| w.chars.sort == word.chars.sort }
  end

  it ""should only match the anagrams"" do
    anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) == ['aabb', 'bbaa']
  end
end
</code></pre>

<p>In Sublime text, I get no output, just a empty black window with the time it took to execute the script, if I use the console and run <code>rspec anagram.rb</code> I get</p>

<pre><code>.

Finished in 0.001 seconds (files took 0.10601 seconds to load)
1 example, 0 failures
</code></pre>

<p>How do I have my code and test in the same file and do the test just by running the script in my Sublime Text editor (and get the output) and how could I better rephrase this test ?</p>
",https://stackoverflow.com/questions/41793847/using-rspec-in-one-file-like-test-unit,"['ruby', 'unit-testing', 'rspec', 'sublimetext3']",491,TRUE,4,2
Should functional tests in Intern (on React) generate coverage results?,"<p>I've set up Intern to test a React project created using <a href=""https://github.com/facebookincubator/create-react-app"" rel=""nofollow noreferrer"">create-react-app</a> in order to perform cross-browser testing with BrowserStack. Is it expected that this would generate code-coverage results as it isn't at the moment.</p>

<p>To be honest I wouldn't expect it to given that the transpilation and bundling of the source files through Webpack / Babel but I just wanted to verify if this was the case. </p>

<p>The tests themselves are running fine (which is the main thing) but obviously it would be useful to have a code coverage report. We're using Jest / Enzyme for primary unit testing (for which we do get coverage results). </p>

<p>I'm really just looking for a yes/no answer here to set my expectations, but if anyone has any suggestions on getting coverage results from functional testing with this setup then that would be really useful.</p>
",https://stackoverflow.com/questions/42961462/should-functional-tests-in-intern-on-react-generate-coverage-results,"['reactjs', 'intern']",197,TRUE,0,1
Intellij show intention actions [Alt + Enter] doesn&#39;t work,"<p>The problem occurred after I had added Groovy Unit Testing .jar to my project (it is sole activity I suppose which could 'damage' my Intellij but it is quite likely that the reason is something else because the problem is global - it appears in all projects).</p>
<p>For example I get message like this:</p>
<p><a href=""https://i.stack.imgur.com/syR4v.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/syR4v.png"" alt=""enter image description here"" /></a></p>
<p>but after I press <kbd>Alt</kbd>+<kbd>Enter</kbd> nothing happen.</p>
<p>If I append another keyboard shortcut for &quot;show intention actions&quot; it doesn't work either. However if I append Alt+Enter with another action then that another action works properly using this shortcut.</p>
<p>It is also interesting that shortcut <kbd>Alt</kbd>+<kbd>Enter</kbd> is reserved not only for action &quot;show intention actions&quot;, but if I remove another associations it still doesn't work.</p>
<p>Every intentions in Intellij are enabled and power save mode is disabled.</p>
<p>I have read
<a href=""https://stackoverflow.com/questions/43683313/intellij-altenter-doesnt-work"">IntelliJ, Alt+Enter doesnt work</a>
<a href=""https://stackoverflow.com/questions/43307532/auto-errors-detection-in-intellij-idea/43319356#43319356"">Auto errors detection in IntelliJ IDEA</a>
but it doesn't solve my problem.</p>
",https://stackoverflow.com/questions/44049421/intellij-show-intention-actions-alt-enter-doesnt-work,"['unit-testing', 'intellij-idea']",2578,TRUE,4,5
Running into c++ virtual template function issue due to interface based programming,"<p>We are designing a new system where we have created interfaces for most of our classes so that we can create mocks (google mocks) for them for unit testing. As a result, all the functions are virtual but the issue is that I am often running into template virtual function issue due to this. I have seen some examples on how to do multi dispatch but they all seem to be using some variation of templates, it doesn't seem straightforward. So does it mean that my entire codebase will now end up with templates making it difficult to read/use and debug? </p>

<p>Or am I not designing good interfaces. Here is a simple example where I am writing an interface for a message queue.</p>

<pre><code>Class IMessageQueue {

   Public:

    Virtual int send(const T &amp; value);  // I can't do this but this is exactly what I want to do, as send should be able to send any type 

};

Class MessageQueue : public IMessageQueue {
      Public:

       Virtual int send(const T &amp; value) { ... }
};

Class MockMQ : public IMessageQueue {
      Public: 
         Virtual int send(const T &amp; value) {
               // mock implementation
          }
};
</code></pre>

<p>How do I get around this problem? This is just one example but I run into lots of these type of issues due to interface based programming. </p>
",https://stackoverflow.com/questions/46620807/running-into-c-virtual-template-function-issue-due-to-interface-based-programm,"['c++', 'api-design', 'googlemock']",46,FALSE,0,1
Autofixture - GuardClauseException,"<p>I encountered a very strange exception while working with nunit and autofixture for unit testing. </p>

<p>I have different classes which all get objects as input and doing httprequest depending on those objects ( I'm formatting the objects to json and make requests )</p>

<p>In my unit test I do this:</p>

<pre><code>IFixture fixture = new Fixture().Customize(new AutoMoqCustomization());
var assertion = new GuardClauseAssertion(fixture);
</code></pre>

<p>Then with all my classes I do this:</p>

<pre><code>assertion.Verify(typeof(MyClass));
</code></pre>

<p>Every class until now passed the test but one not. The test throws the exception</p>

<pre><code>Message: Ploeh.AutoFixture.Idioms.GuardClauseException : A Guard Clause test was performed
on a method that may contain a deferred iterator block, but the test failed. See the inner
exception for more details. However, because of the deferred nature of the iterator block,
this test failure may look like a false positive. Perhaps you already have a Guard Clause
in place, but in conjunction with the 'yield' keyword (if you're using C#); if this is the
case, the Guard Clause is dormant, and will first be triggered when a client starts looping
over the iterator. This doesn't adhere to the Fail Fast principle, so should be addressed.
</code></pre>

<p>And this is the inner exception:</p>

<pre><code>----&gt; Ploeh.AutoFixture.Idioms.GuardClauseException : An attempt was made to assign the
value null to the parameter ""status"" of the method ""ChangeStatus"", and no Guard Clause
prevented this. Are you missing a Guard Clause?
Method Signature: System.String ChangeStatus(Interfaces.IProject, Status)
Parameter Type: Status, , Version=1.0.0.0
Culture=neutral, PublicKeyToken=bd4b9bc26bc147ff
Declaring Type: ReleaseRepository, 
Version=1.0.0.0, Culture=neutral, PublicKeyToken=bd4b9bc26bc147ff
Reflected Type: ReleaseRepository
Version=1.0.0.0, Culture=neutral, PublicKeyToken=bd4b9bc26bc147ff
  ----&gt; System.InvalidOperationException : The passed project has no valid name.
</code></pre>

<p>in the last method of my class which looks like this:</p>

<pre><code>if(string.IsNullOrEmpty(myObject.Name))
     throw new InvalidOperationException(""..."");
</code></pre>

<p>The Method mentionted in the inner exception is this:
(Status is an enum, but I got the error with other objects which wasnt enums)</p>

<pre><code>public string ChangeStatus(IObject1, IObject2, Status status)
{
// Here are the if clauses to check if something is null or not given
return client.Post(url, status);
}
</code></pre>

<p>I'm wondering because I do the same if clause in all my other classes with the same type of object and they pass.</p>

<p>(It's the same with this test:)</p>

<pre><code>assertion.Verify(typeof(myObject).GetMethods());
</code></pre>

<p>I have no idea what could be the reason.</p>
",https://stackoverflow.com/questions/45692465/autofixture-guardclauseexception,"['c#', 'unit-testing', 'autofixture']",851,TRUE,0,1
"Testing member function, by peeling pairs off variadic macro/template/function?","<p>(I'm using <code>catch</code> for unit testing, which unfortunately doesn't yet have what it's calling generators to do this sort of thing.)</p>

<p>In <code>c++17</code>, is there a way to reduce this:</p>

<pre><code>assert(""""  == String{""""  }.removeLeading(' '));
assert(""a"" == String{"" a"").removeLeading(' '));
assert(""a"" == String(""a"" }.removeLeading(' '));
assert(""a"" == String{""a ""}.removeLeading(' '));
</code></pre>

<p>With a macro, template, or function like this:</p>

<pre><code>#define MACRO(className, method, arg, ...) \
   for(auto [x, y] : { __VA_ARGS }) { \
      assert(x == className{y}.method(arg)); \
   }
</code></pre>

<p>So it's shorter like this:</p>

<pre><code>MACRO(String, removeLeading, ' ',
   { """", """" }, {""a"", "" a""}, {""a"", ""a""}, {""a"", ""a ""})

// or

MACRO(String, removeLeading, ' ',
   """", """",    ""a"", "" a"",    ""a"", ""a"",    ""a"", ""a "")
</code></pre>

<p>Assuming that all <code>...</code> arguments ""<code>auto</code>"" to the same type.</p>

<p>Basically with no limit on the number of <code>...</code> args.  (Maybe could go up to 100?)</p>

<p>Using the first <code>MACRO()</code> gives: <code>unable to deduce 'std::initializer_list&lt;auto&gt;&amp;&amp;' from...</code> (it also doesn't understand the semantics so strictly breaks apart on <code>,</code> tokens, but as long as it's put together correctly, doesn't matter.)</p>

<p>Using the second <code>MACRO()</code> gives: <code>cannot decompose non-array non-class type 'const char*'</code></p>

<hr>

<p>Trying templates:</p>

<pre><code>template&lt;typename T&gt;
void TEMP(T a, T b) {
    assert(a == String{ b }.removeLeading(' '));
}

template&lt;typename T, typename... Args&gt;
void TEMP(T a, T b, Args... args) {
    TEMP(a, b);
    TEMP(args...);
}

TEMP("""", """",    ""a"", "" "",    ""a"", ""a"",    ""a"", ""a "");
</code></pre>

<p>This at least works, but I don't want <code>className</code>, <code>method</code>, and <code>arg</code> to be hardcoded as <code>""String""</code>, <code>""removeLeading""</code>, and <code>"" ""</code>.</p>

<hr>

<p>I wonder if there's a way to pull this off with all the new type trait / ""meta"" templates (not sure what else to call them) that I haven't done much with.  (I look at some of the libraries available in the last year or two, and they almost look like a different language to me...)</p>
",https://stackoverflow.com/questions/46930431/testing-member-function-by-peeling-pairs-off-variadic-macro-template-function,"['c++', 'templates', 'variadic-templates', 'c++17', 'variadic-macros']",169,TRUE,3,2
Could not load file or assembly CrystalDecisions.ReportAppServer.CommLayer,"<p>I have a similar error than this <a href=""https://stackoverflow.com/q/10001310/196526"">one</a> or this <a href=""https://stackoverflow.com/q/38025601/196526"">one</a> but my question is different. I get the error on my local machine. This is a web application that need to print some reports. My error message is</p>

<blockquote>
  <p>Could not load file or assembly
  'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0,
  Culture=neutral, PublicKeyToken=692fbea5521e1304' or one of its
  dependencies. The system cannot find the file specified.</p>
</blockquote>

<p>I installed the <strong>Nuget package Crystal.Reports.Essentials</strong> by Jackes David but I didn't installed the <strong>Crystal report runtime</strong> for Visual Studio. I know installing the Crystal Report runtime will probably resolve my issue but I Don't want to install the Crystal report runtime because I want to be able to deploy my solution on cloud server and you canot always install third party exe on that kind of servers. I think It will be the same problem for unit testing. I cannot install the runtime each time I create a Virtual machine for testing.</p>

<p>Am I right or I must install this runtime?</p>
",https://stackoverflow.com/questions/46073843/could-not-load-file-or-assembly-crystaldecisions-reportappserver-commlayer,"['c#', 'crystal-reports', 'visual-studio-2017']",7761,FALSE,3,0
"Karma, Webpack, Tape &amp; Absolute path issue","<p>This is an interesting situation.</p>

<p>The puzzle is this:
The component's name is TODO</p>

<p><strong>Controller.js</strong></p>

<pre><code>import Component from 'component';
import View from 'app-folder/components/todo/view';

export default Component.extend({
 viewClass: View
});
</code></pre>

<p><strong>View.js</strong></p>

<pre><code>import {LayoutView} from 'backbone.marionette';
import template from 'app-folder/components/todo/template';

export default LayoutView.extend({
  template: template
});
</code></pre>

<p>I am using Karma, webpack &amp; tape to test out the components. I'm not putting all the functions within the view and component, because it is not necessary for this question. However the question is simple &amp; complex:
How do you deal with absolute path restrictions in an application for doing unit testing</p>

<p>so example:</p>

<pre><code>import test from 'tape';

import controller from 'app-folder/components/todo/controller'

test('testing something', (t) =&gt; {

  t.end();
});
</code></pre>

<p>It will return this type of error:</p>

<p><strong>ERROR in ./components/todo/tests/todo_spec.js</strong></p>

<p><strong><em>Module not found: Error: Cannot resolve module 'app-folder/components/todo/controller' in /Users/username/Documents/projects/app-folder/components/todo/tests</em></strong></p>

<p>Because of the path being all weird. Now I wish I could do relative pathing to solve this issue... but due to how it's built, its not possible.</p>

<p>I can't wrap my head around it and definitely having some trouble figuring this one out.</p>

<p>Thanks ahead of time for any advice given!</p>
",https://stackoverflow.com/questions/45145935/karma-webpack-tape-absolute-path-issue,"['unit-testing', 'karma-webpack', 'node.js-tape']",350,FALSE,3,0
Using Java8 lambda for argument matching on mocked class,"<p>The class I'm unit testing takes a dependency and calls a function on that dependency. That function takes a complex object as its argument and produces a result. Now, I would like to mock the dependency and have it return something based on the argument passed in. A simplified, working version is given below.</p>

<p>Can I use Java 8 lambda expressions in the <code>when</code> method to eliminate the <code>ArgHasNext</code> class? Something like the commented code below (which does not compile).</p>

<pre><code>class ArgHasNext implements ArgumentMatcher&lt;Arg&gt; {
    public boolean matches(Arg arg) {
        return arg.hasNext();
    }

    @Override
    public boolean matches(Object o) {
        return matches((Arg)o);
    }
}

@RunWith(MockitoJUnitRunner.class)
public class ArgumentMatcherTest {

    @Mock
    private Dependency dep = mock(Dependency.class);

    @Test
    public void test() {

        when(dep.func(argThat(new ArgHasNext()))).thenReturn(true);
        // when(dep.func(argThat((Arg a) -&gt; a.hasNext()))).thenReturn(true);
        // when(dep.func(argThat((Arg a) -&gt; !a.hasNext()))).thenReturn(false);
        Sut sut = new Sut(dep);
        assertEquals(sut.method(new Arg(true)), ""True"");
        assertEquals(sut.method(new Arg(false)), ""False"");
    }
}

class Arg {
    private boolean hasNext;

    public Arg(boolean hasNext) {
        this.hasNext = hasNext;
    }

    public boolean hasNext() {
        return this.hasNext;
    }
}

class Sut {
    private Dependency dep;

    public Sut(Dependency dep) {
        this.dep = dep;
    }

    public String method(Arg arg) {

        if (dep.func(arg)) {
            return ""True"";
        }
        else {
            return ""False"";
        }
    }

}

class Dependency {
    public boolean func(Arg arg) {
        if (arg.hasNext()) {
            return true;
        }
        return false;
    }
}
</code></pre>

<p>I'm using Mockito-core version 2.0.54-beta.</p>

<p><strong>EDIT</strong>
Okay, maybe I over-simplified the example. In the real case, the dependency <code>func</code> method returns paged query results that are processed in <code>SUT</code> before the tested method returns. Depending on <code>Arg</code>, I want the dependency <code>func</code> to return page 1 results the first time it's called and page 2 results the second time. I can only do this when I can have the mock return different values based on an argument passed to the function call. It this possible using lambdas in Mockito?</p>
",https://stackoverflow.com/questions/45993599/using-java8-lambda-for-argument-matching-on-mocked-class,"['java', 'unit-testing', 'lambda', 'mockito']",691,TRUE,2,3
How to unit test Hangfire implementation using Hangfire.MemoryStorage,"<p>To clarify what I'm trying to do, I have a method that creates/updates an item in my DB. When Testing as usual by asserting that the item is in the in-memory database always comes back as null. After reading the docs, it appears I need to be determining whether or not the correct job has been added to the Hangfire queue.</p>

<p>I've been going over the <a href=""http://docs.hangfire.io/en/latest/background-methods/writing-unit-tests.html"" rel=""nofollow noreferrer"">documentation</a> for unit testing a Hangfire implementation but can't seem to find a way to test against in-memory storage. </p>

<p>In the example, a mock is created and then passed into the constructor of the controller. However, I've been modeling my solution after <a href=""https://github.com/HangfireIO/Hangfire/pull/604"" rel=""nofollow noreferrer"">this example</a> where jobs are queued in the Configure method of the Startup class. This means I have no controller and I'm not passing anything into my methods that are queuing up my jobs.</p>

<p>So how should I be going about testing this?</p>

<p>Here's one of the methods I'm trying to test:</p>

<pre><code>public async Task SyncDeletedAccounts()
    {
        try
        {
            int pastMinutes = 90;
            var startDate = DateTime.Now.AddMinutes(0 - pastMinutes);
            var client = await this._forceDotComService.GetForceClient();

            var deletedIds = await this._forceDotComService.GetDeletedIds&lt;sf.Account&gt;(client, startDate);
            if (!deletedIds.Any())
            {
                this._logger.LogInformation(""No deleted accounts"");
                return;
            }

            foreach (var deletedId in deletedIds)
            {
                BackgroundJob.Enqueue&lt;InterconnectorServiceHelper&lt;sf.Account, ic.Account&gt;&gt;(i =&gt;
                    i.MarkDeleted(deletedId));
            }
        }
        catch (Exception e)
        {
            this._logger.LogError(e, ""AccountService.SyncDeletedAccounts"");
            throw;
        }
    }
</code></pre>
",https://stackoverflow.com/questions/46346864/how-to-unit-test-hangfire-implementation-using-hangfire-memorystorage,"['c#', 'unit-testing', 'asp.net-core', 'moq', 'hangfire']",1465,FALSE,2,0
Running Nunit Test in Administrator Mode,"<p>I am currently using VS 2015 professional and using Nunit Framework for unit testing. </p>

<p>I am using the same framework for integration testing as well. While doing so I realized, one of the <code>.dll</code> supplied by the hardware manufacturer requires Administrator Privileges for it to be used in an application or tests(my current issue lies here) I did some research and tried a few things mentioned below to use the <code>dll</code> in admin mode. </p>

<p><strong>1</strong> So I started the Visual Studio in Administrator mode for the test to run, but still the <code>dll</code> (functions) do not work. (running test in VS debug mode)</p>

<p><strong>2</strong> I just used normal debug without Nunit framework, then the <code>dll</code> worked.</p>

<p>My conclusion --> I think that the Nunit somehow is not elevated to Admin.</p>

<p>Questions and Problem</p>

<p>I need to use the dll in Admin mode for the integration testing(where i use Nunit Framework)</p>

<ol>
<li>Is it possible to do so?</li>
<li>If no, then why and if yes, then how</li>
</ol>

<p>Please provide your input</p>
",https://stackoverflow.com/questions/44537606/running-nunit-test-in-administrator-mode,"['c#', 'nunit', 'administrator']",771,FALSE,2,0
NUnit test for Xamarin.Forms ListViews with cell binding,"<p>I'm trying to write unit tests for a <code>ListView</code> with a custom <code>DataTemplate</code>. Although the cells are rendered as expected on iOS and Android, their bound properties are <code>null</code> when running NUnit tests.</p>

<p><strong>The setup</strong></p>

<p>To initiate Xamarin.Forms in an NUnit test project, I'm using <a href=""https://github.com/jonathanpeppers/Xamarin.Forms.Mocks"" rel=""nofollow noreferrer"">Xamarin.Forms.Mocks</a>. So the <code>TestFixture</code> looks as follows:</p>

<pre class=""lang-cs prettyprint-override""><code>using NUnit.Framework;
using Xamarin.Forms;
using Xamarin.Forms.Mocks;

namespace UnitTest
{
    [TestFixture]
    public class Test
    {
        [SetUp]
        public void SetUp()
        {
            MockForms.Init();
        }
</code></pre>

<p><strong>What works</strong></p>

<p>One test, which is working well, creates a new <code>DataTemplate</code> with a custom <code>StringCell</code> bound to a string ""foo"":</p>

<pre class=""lang-cs prettyprint-override""><code>        class StringCell : ViewCell
        {
            public StringCell()
            {
                var label = new Label();
                label.SetBinding(Label.TextProperty, ""."");
                View = label;
            }
        }

        [Test]
        public void ViewCellWithString()
        {
            var content = new DataTemplate(typeof(StringCell)).CreateContent();
            (content as Cell).BindingContext = ""foo"";

            Assert.That(((content as ViewCell).View as Label).Text, Is.EqualTo(""foo""));
        }
</code></pre>

<p>As expected, the rendered <code>content</code> is a <code>ViewCell</code> with a <code>View</code> of type <code>Label</code> with the <code>Text</code> ""foo"".</p>

<p><strong>What doesn't work</strong></p>

<p>A second test, however, fails: It creates a <code>DataTemplate</code> of type <code>ItemCell</code> bound to a custom object <code>Item</code> with a bindable property <code>Name</code> ""bar"".</p>

<pre class=""lang-cs prettyprint-override""><code>        class Item : BindableObject
        {
            public static readonly BindableProperty NameProperty = BindableProperty.Create(nameof(Name), typeof(string), typeof(Item), null);

            public string Name {
                get { return (string)GetValue(NameProperty); }
                set { SetValue(NameProperty, value); }
            }
        }

        class ItemCell : ViewCell
        {
            public ItemCell()
            {
                var label = new Label();
                label.SetBinding(Label.TextProperty, nameof(Item.NameProperty));
                View = label;
            }
        }

        [Test]
        public void ViewCellWithItem()
        {
            var content = new DataTemplate(typeof(ItemCell)).CreateContent();
            (content as Cell).BindingContext = new Item { Name = ""bar"" };

            Assert.That(((content as ViewCell).View as Label).Text, Is.EqualTo(""bar""));
        }
</code></pre>

<p>This test fails, because the Label's <code>Text</code> property is <code>null</code>.</p>

<p><strong>My question</strong></p>

<p>What am I doing wrong? Shouldn't the binding to a string via <code>"".""</code> behave similar to the binding to an <code>Item</code> via <code>NameProperty</code>? Or is there a better way to instantiate the view of a list view cell with binding properties for unit testing purposes?</p>
",https://stackoverflow.com/questions/45144350/nunit-test-for-xamarin-forms-listviews-with-cell-binding,"['listview', 'xamarin', 'view', 'xamarin.forms', 'nunit']",399,TRUE,2,1
How to pass environment-specific application configuration to Pytest,"<p>I am using Pytest for unit testing, and some of my tests need to use e.g. database connection information that varies depending on the environment (development vs staging vs production).</p>

<p>This is stuff that, during normal execution, gets read from application configuration files. In an ideal world, I'd just provide a command-line option to Pytest specifying e.g. my <code>development.ini</code> application config file, and my test code could provide that configuration info to the application code under test without me needing to duplicate that information in a test config file. Is this possible?</p>

<p>Two possibilities that strike me from the Pytest documentation are:</p>

<ol>
<li>put it in the <code>pytest.ini</code> as <code>addopts</code></li>
<li>pass it in via <a href=""http://docs.pytest.org/en/latest/example/simple.html"" rel=""nofollow noreferrer"">custom command-line options</a></li>
</ol>

<p>(If I understand the documentation correctly, both of the above approaches should use a custom test fixture. Please correct me if that is wrong.)</p>

<p>What is the conventional approach to providing environment-specific configuration information for use by my test code? Or, what are the pros and cons of the different approaches?</p>
",https://stackoverflow.com/questions/41491693/how-to-pass-environment-specific-application-configuration-to-pytest,"['python', 'unit-testing', 'configuration', 'pytest']",1844,TRUE,2,1
X509 certificate unit testing - I need to create a certificate and a CRL which has it,"<p>Ok, so I have a method which is able to be passed a CRL and a certificate. I used it to validate the certificates coming from vendors during the runtime of my application.</p>

<p>The hardest part of this has been unit testing the damn thing!</p>

<p>I need to create a certificate file, and a CRL file, which I can then distribute as resources with the application, and then pass them in during the unit test.</p>

<p>I have the unit test written also, but with hard coded values - But now I need to know how to create the following : </p>

<p>two X509 Certificates.
One CRL</p>

<p>I need the CRL to have an entry for one of the two X509 certs. This will allow me to test for revocation outcome, and also non-revocation. </p>

<p>I have tried the following guide, but security is far from my strong point - and I can't get it to work.</p>

<pre><code>https://blog.didierstevens.com/2013/05/08/howto-make-your-own-cert-and-revocation-list-with-openssl/
</code></pre>
",https://stackoverflow.com/questions/42635007/x509-certificate-unit-testing-i-need-to-create-a-certificate-and-a-crl-which-h,"['openssl', 'x509']",3440,TRUE,1,1
Spek access to Internal Visibility Kotlin Classes,"<p>I've put together a Maven-based project that uses Spek in the Junit 4 Runner for testing.</p>

<p>I configured the project in Codacy and got a useful suggestion to either document my public classes or reduce their visibility (great).</p>

<p>I've found that the Kotlin compiler seems to regard the tests as existing in a different module, which makes it very difficult to do effective unit testing given my project layout. The tests will not compile if the visibility of classes or interfaces are reduced to internal.</p>

<p>Please suggest a mechanism to fix this. Is it just not possible to use internal visibility modifier in this situation? Is there a useful compiler configuration or Spek configuration that can overcome the issue? I think the suggestion is indeed correct; I do not wish to document the classes because they are internal and may change in the future or the documentation is simply not worth the effort.</p>
",https://stackoverflow.com/questions/46700381/spek-access-to-internal-visibility-kotlin-classes,"['kotlin', 'codacy', 'spek']",153,TRUE,1,1
"Angular 2 Jasmine testing, Loading all components in app.component.ts?","<p>I'm working on a small test app to learn Angular 2 and unit testing in Angular 2 a bit better. Coming from a react - Jest background; it feels weird to include all components in the app.component.ts.</p>

<p>This is what the component Hierarchy looks like for what I have so far:</p>

<p>App.Component > Layout.Component > Header.Component > Nav.Component</p>

<p>When I run npm test, I get the error of </p>

<blockquote>
  <p>main-header' is not a known element:</p>
</blockquote>

<p>When I'd fix this by Importing and declaring the component bound to that selector in App.Component.spec.ts, I would just get the same error for the next component/selector inline.</p>

<p>Had this been a large app with many components; I could see App.Component's Test becoming large and unmaintainable. After several google searches that yielded AngularJS and Angular RC.X results.. I've hit a dead end. My Gut is telling me something is wrong and that this can't be the way Testing in Angular 2 is done.. but I could be wrong!</p>
",https://stackoverflow.com/questions/44811361/angular-2-jasmine-testing-loading-all-components-in-app-component-ts,"['angular', 'jasmine', 'karma-jasmine', 'angular-cli']",4044,TRUE,1,2
XSD - compounding simpleType validation,"<p>I have an XSD type that validates an IP address (simplified):</p>

<pre><code>&lt;xs:simpleType name=""ip-address""&gt;
  &lt;xs:restriction base=""xs:string""&gt;
    &lt;xs:pattern value=""[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"" /&gt;
  &lt;/xs:restriction&gt;
&lt;/xs:simpleType&gt;
</code></pre>

<p>I have an XSD type that validates an IP port</p>

<pre><code>&lt;xs:simpleType name=""ip-port""&gt;
  &lt;xs:restriction base=""xs:integer""&gt;
     &lt;xs:minInclusive value=""1025""/&gt;
     &lt;xs:maxInclusive value=""65535""/&gt;
  &lt;/xs:restriction&gt;
&lt;/xs:simpleType&gt;
</code></pre>

<p>And I have an XSD type that validates a channel within the IP data</p>

<pre><code>&lt;xs:simpleType name=""ip-channel""&gt;
  &lt;xs:restriction base=""xs:integer""&gt;
     &lt;xs:minInclusive value=""1""/&gt;
     &lt;xs:maxInclusive value=""1024""/&gt;
  &lt;/xs:restriction&gt;
&lt;/xs:simpleType&gt;
</code></pre>

<p>I now wish to add another type that is basically a compound of the above, but with <code>':'</code> separators between each field.
The result being that the XML can have an attribute that reads <code>239.0.0.1:15001:1</code>.
This is a common notation in our company documentation and XML configuration. We've only recently branched into XML validation as part of unit testing.</p>

<p>Mooted solution:</p>

<pre><code>&lt;xs:simpleType name=""pmc-source""&gt;
    &lt;xs:restriction base=""xs:string""&gt;
      &lt;!--&lt;xs:pattern value=""[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\:[0-9]{1,5}\:[0-9]{1,5}""/--&gt;
      &lt;xs:pattern value=""[ip-address]\:[ip-port]\:[ip-channel]""/&gt;
    &lt;/xs:restriction&gt;
&lt;/xs:simpleType&gt;
</code></pre>

<p>The commented out pattern works roughly, but isn't as strict as its sub-parts because it performs no range checking. Plus, it is duplication of validation effort, because the address, port and channel validations must exist for other unrelated validation.</p>

<p>Is it possible to express one XSD simpleType in terms of other simpleTypes in XSD?
If so, what is the correct syntax?</p>
",https://stackoverflow.com/questions/44650797/xsd-compounding-simpletype-validation,"['xml', 'validation', 'xsd']",350,FALSE,1,0
Does the value of unit tests decrease with the complexity of the unit test?,"<p>I'm at the point where I should write a unit test for the complex algorithm that my function does perform. The function takes two mandatory arguments at invocation. Based on the combination of both arguments the function does return something. </p>

<pre><code>function ReturnDesiredParagraphStyle(currParagraphStyle, nextParagraphStyle) 
{
    // logic
}
</code></pre>

<p>Now the problem is, to test any combination of inputs and the correctness of the desired output of the function I have to write a complex logic within the unit test, because there are so many possible inputs (approximately 50 for each argument). The complex logic would be a loop with the purpose that I do not have to type each combination of inputs manually in the unit test.</p>

<p>I do understand that most of the time to write this unit-test will provide an layer of safety, but doesen't it lead the concept of unit testing a bit ad absurdum (because the logic in the unit test will be so complex and nothing tests the logic in the unit test)? </p>
",https://stackoverflow.com/questions/45357254/does-the-value-of-unit-tests-decrease-with-the-complexity-of-the-unit-test,"['unit-testing', 'testing', 'architecture', 'theory', 'software-design']",230,TRUE,1,1
Angular Material 2 dialog with form test failing,"<p>I have a simple login dialog that is generated using Angular Material 2
and an Angular reactive form.<br>
The dialog box works as is should when used in a program but the unit testing for it doesn't reflect this.  The forms login button should be disabled until both the name and password fields pass the validation criteria set up in the component at which point the login button is enabled and available for clicking.<br>
However, when I run the test and set the name and input fields to valid content the login button remains disabled and the test fails.<br>
The relevant section of code for the test is as follows  </p>

<pre><code>  it('should enable the login button when a valid username and password are entered', fakeAsync(() =&gt; {
    (overlayContainerElement.querySelector('input[formcontrolname=""name""]') as HTMLInputElement).value = 'ABC';
    (overlayContainerElement.querySelector('input[formcontrolname=""password""]') as HTMLInputElement).value = '12345678';
    viewContainerFixture.detectChanges();
    tick();

    viewContainerFixture.detectChanges();
    const loginBtn = overlayContainerElement.querySelector('button[md-raised-button]');
    const nameInput = overlayContainerElement.querySelector('input[formcontrolname=""name""]');
    const passwordInput = overlayContainerElement.querySelector('input[formcontrolname=""password""]');
    console.log('Login Button is:', loginBtn.textContent);
    console.log('Login Button is:', loginBtn.getAttribute('ng-reflect-disabled'));

    expect((nameInput as HTMLInputElement).value).toEqual('ABC');
    expect((passwordInput as HTMLInputElement).value).toEqual('12345678');
    expect((overlayContainerElement.querySelector('button[md-raised-button]')).getAttribute('ng-reflect-disabled')).toBe('false');
  }));
</code></pre>

<p>I am obviously not refreshing the state of the login button but cannot see why this is so.  </p>

<p>Any help would be gratefully appreciated.</p>

<p><a href=""https://plnkr.co/edit/U1lpoa?p=info/%20Login%20Test%20Sample%22"" rel=""nofollow noreferrer"">https://plnkr.co/edit/U1lpoa?p=info</a> is a link to a plunker which shows the component and test suite and the code is reproduced below.</p>

<p><strong>Component</strong></p>

<pre><code>import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MdDialog, MdDialogRef } from '@angular/material';


@Component({
  selector: 'lpa-login-dialog',
  templateUrl: './login-dialog.component.html',
})
export class LoginDialogComponent implements OnInit {
  loginForm: FormGroup;

  constructor(
    private fb: FormBuilder,
    private dlgRef: MdDialogRef&lt;LoginDialogComponent&gt;
  ) {
    this.createForm()
  }

  ngOnInit() {
  }

  private createForm() {
    this.loginForm = this.fb.group({
      name: ['', [Validators.required, Validators.minLength(3)]],
      password: ['', [Validators.required, Validators.minLength(8)]]
    })
  }

  public login() {
    this.dlgRef.close(this.loginForm.value.name);
  }

}
</code></pre>

<p><strong>HTML</strong></p>

<pre><code>&lt;h1 class=""mdl-dialog-title"" style=""text-align: center""&gt;App Login&lt;/h1&gt;

&lt;form [formGroup]=""loginForm"" (ngSubmit)=""login()"" ngnovalidate&gt;
  &lt;div class=""mdl-dialog-content""&gt;
    &lt;div class=""form-group""&gt;
      &lt;md-input-container style=""width: 100%""&gt;
        &lt;input mdInput class=""form-control"" formControlName=""name"" placeholder=""Name""&gt;
      &lt;/md-input-container&gt;
    &lt;/div&gt;
    &lt;div class=""form-group""&gt;
      &lt;md-input-container style=""width: 100%""&gt;
        &lt;input mdInput type=""password"" class=""form-control"" formControlName=""password"" placeholder=""Password""&gt;
      &lt;/md-input-container&gt;
    &lt;/div&gt;
  &lt;/div&gt;

  &lt;div class=""mdl-dialog-actions"" style=""text-align: center""&gt;
    &lt;button md-raised-button color=""primary"" type=""submit"" [disabled]=""!loginForm.valid"" &gt;Login&lt;/button&gt;
    &lt;button md-button md-dialog-close=false color=""warn""&gt;Cancel&lt;/button&gt;
  &lt;/div&gt;
&lt;/form&gt;
</code></pre>

<p><strong>Unit Test (.spec)</strong></p>

<pre><code>import { inject, async, fakeAsync, flushMicrotasks, ComponentFixture, TestBed, tick, } from '@angular/core/testing';
import { NgModule, Component, Directive, ViewChild, ViewContainerRef, Injector, Inject, DebugElement } from '@angular/core';
import { By } from '@angular/platform-browser';
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';

import { NoopAnimationsModule } from '@angular/platform-browser/animations';

import { MaterialModule, MdDialogModule, MdDialog, MdDialogRef, MdButton, OverlayContainer } from '@angular/material';

import { Observable } from 'rxjs/Observable';
import { Subscriber } from 'rxjs/Subscriber';

import { LoginDialogComponent } from './login-dialog.component';

// helper classes
// tslint:disable-next-line:directive-selector
@Directive({ selector: 'dir-with-view-container' })
class DlgTestViewContainerDirective {
  constructor(public viewContainerRef: ViewContainerRef) { }
}

@Component({
  selector: 'lpa-arbitrary-component',
  template: `&lt;dir-with-view-container&gt;&lt;/dir-with-view-container&gt;`,
})
class DlgTestChildViewContainerComponent {
  @ViewChild(DlgTestViewContainerDirective) childWithViewContainer: DlgTestViewContainerDirective;

  get childViewContainer() {
    return this.childWithViewContainer.viewContainerRef;
  }
}

// Create a real (non-test) NgModule as a workaround for
// https://github.com/angular/angular/issues/10760
const TEST_DIRECTIVES = [
  DlgTestViewContainerDirective,
  DlgTestChildViewContainerComponent,
  LoginDialogComponent
];

@NgModule({
  imports: [
    MdDialogModule,
    ReactiveFormsModule,
    MaterialModule,
    NoopAnimationsModule
  ],
  exports: TEST_DIRECTIVES,
  declarations: TEST_DIRECTIVES,
  entryComponents: [
    LoginDialogComponent
  ]
})
class DialogTestModule { }

describe('Login Dialog Component', () =&gt; {

  let dialog: MdDialog;
  let dialogRef: MdDialogRef&lt;LoginDialogComponent&gt;;

  let overlayContainerElement: HTMLElement;

  let viewContainerFixture: ComponentFixture&lt;DlgTestChildViewContainerComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        DialogTestModule,
     ],
      declarations: [
      ],
      providers: [
        {
          provide: OverlayContainer, useFactory: () =&gt; {
            overlayContainerElement = document.createElement('div');
            return { getContainerElement: () =&gt; overlayContainerElement };
          }
        }
      ]
    })
      .compileComponents();
  }));

  beforeEach(inject([MdDialog], (d: MdDialog) =&gt; {
    dialog = d;
  }));

  beforeEach(() =&gt; {
    viewContainerFixture = TestBed.createComponent(DlgTestChildViewContainerComponent);
    viewContainerFixture.detectChanges();

    dialogRef = dialog.open(LoginDialogComponent);
    viewContainerFixture.detectChanges();

  });

  it('should be created', fakeAsync(() =&gt; {
    expect(dialogRef.componentInstance instanceof LoginDialogComponent).toBe(true, 'Failed to open');
    expect(overlayContainerElement.querySelector('h1').innerText).toEqual('App Login');

    dialogRef.close();
    tick(500);
    viewContainerFixture.detectChanges();
  }));

  it('should close and return false when cancel button pressed', async(() =&gt; {
    const afterCloseCallback = jasmine.createSpy('afterClose callback');

    dialogRef.afterClosed().subscribe(afterCloseCallback);
    (overlayContainerElement.querySelector('button[md-dialog-close=""false""]') as HTMLElement).click();
    viewContainerFixture.detectChanges();

    viewContainerFixture.whenStable().then(() =&gt; {
      expect(overlayContainerElement.querySelector('md-dialog-container')).toBeNull('Dialog box still open');
      expect(afterCloseCallback).toHaveBeenCalledWith('false');
    });
  }));

  describe('should disable login button', () =&gt; {
    it('without a user and password entry', fakeAsync(() =&gt; {

      const btn = overlayContainerElement.querySelector('button[md-raised-button]');
      expect(btn.getAttribute('ng-reflect-disabled')).toBe('true');

      dialogRef.close()
      tick(500);
      viewContainerFixture.detectChanges();
    }));

    it('with a user entry but without a password entry', async(() =&gt; {

      (overlayContainerElement.querySelector('input[formcontrolname=""name""]') as HTMLInputElement).value = 'DD';
      viewContainerFixture.detectChanges();

      viewContainerFixture.whenStable().then(() =&gt; {
        viewContainerFixture.detectChanges();
        const nameInput = overlayContainerElement.querySelector('input[formcontrolname=""name""]');
        const passwordInput = overlayContainerElement.querySelector('input[formcontrolname=""password""]');

        expect((nameInput as HTMLInputElement).value).toEqual('DD');
        expect((passwordInput as HTMLInputElement).value).toEqual('');
        expect((overlayContainerElement.querySelector('button[md-raised-button]')).getAttribute('ng-reflect-disabled')).toBe('true');
      });
    }));

    it('with a password but without a user entry', async(() =&gt; {

      (overlayContainerElement.querySelector('input[formcontrolname=""password""]') as HTMLInputElement).value = 'Password';
      viewContainerFixture.detectChanges();

      viewContainerFixture.whenStable().then(() =&gt; {
        viewContainerFixture.detectChanges();
        const nameInput = overlayContainerElement.querySelector('input[formcontrolname=""name""]');
        const passwordInput = overlayContainerElement.querySelector('input[formcontrolname=""password""]');

        expect((nameInput as HTMLInputElement).value).toEqual('');
        expect((passwordInput as HTMLInputElement).value).toEqual('Password');
        expect((overlayContainerElement.querySelector('button[md-raised-button]')).getAttribute('ng-reflect-disabled')).toBe('true');
      });
    }));

    it('with a valid user name but invalid password', async(() =&gt; {

      (overlayContainerElement.querySelector('input[formcontrolname=""name""]') as HTMLInputElement).value = 'ABC';
      (overlayContainerElement.querySelector('input[formcontrolname=""password""]') as HTMLInputElement).value = '1234567';
      viewContainerFixture.detectChanges();

      viewContainerFixture.whenStable().then(() =&gt; {
        viewContainerFixture.detectChanges();
        const nameInput = overlayContainerElement.querySelector('input[formcontrolname=""name""]');
        const passwordInput = overlayContainerElement.querySelector('input[formcontrolname=""password""]');

        expect((nameInput as HTMLInputElement).value).toEqual('ABC');
        expect((passwordInput as HTMLInputElement).value).toEqual('1234567');
        expect((overlayContainerElement.querySelector('button[md-raised-button]')).getAttribute('ng-reflect-disabled')).toBe('true');
      });
    }));

    it('with an invalid user name but with a valid password', async(() =&gt; {

      (overlayContainerElement.querySelector('input[formcontrolname=""name""]') as HTMLInputElement).value = 'AB';
      (overlayContainerElement.querySelector('input[formcontrolname=""password""]') as HTMLInputElement).value = '12345678';
      viewContainerFixture.detectChanges();

      viewContainerFixture.whenStable().then(() =&gt; {
        viewContainerFixture.detectChanges();
        const nameInput = overlayContainerElement.querySelector('input[formcontrolname=""name""]');
        const passwordInput = overlayContainerElement.querySelector('input[formcontrolname=""password""]');

        expect((nameInput as HTMLInputElement).value).toEqual('AB');
        expect((passwordInput as HTMLInputElement).value).toEqual('12345678');
        expect((overlayContainerElement.querySelector('button[md-raised-button]')).getAttribute('ng-reflect-disabled')).toBe('true');
      });
    }));
  });

  it('should enable the login button when a valid username and password are entered', fakeAsync(() =&gt; {
    (overlayContainerElement.querySelector('input[formcontrolname=""name""]') as HTMLInputElement).value = 'ABC';
    (overlayContainerElement.querySelector('input[formcontrolname=""password""]') as HTMLInputElement).value = '12345678';
    viewContainerFixture.detectChanges();
    tick();

    viewContainerFixture.detectChanges();
    const loginBtn = overlayContainerElement.querySelector('button[md-raised-button]');
    const nameInput = overlayContainerElement.querySelector('input[formcontrolname=""name""]');
    const passwordInput = overlayContainerElement.querySelector('input[formcontrolname=""password""]');
    console.log('Login Button is:', loginBtn.textContent);
    console.log('Login Button is:', loginBtn.getAttribute('ng-reflect-disabled'));

    expect((nameInput as HTMLInputElement).value).toEqual('ABC');
    expect((passwordInput as HTMLInputElement).value).toEqual('12345678');
    expect((overlayContainerElement.querySelector('button[md-raised-button]')).getAttribute('ng-reflect-disabled')).toBe('false');
  }));

  it('should enable the login button when a valid username and password are entered', async(() =&gt; {
    (overlayContainerElement.querySelector('input[formcontrolname=""name""]') as HTMLInputElement).value = 'ABC';
    (overlayContainerElement.querySelector('input[formcontrolname=""password""]') as HTMLInputElement).value = '12345678';
    viewContainerFixture.detectChanges();

    viewContainerFixture.whenStable().then(() =&gt; {
      viewContainerFixture.detectChanges();
      const loginBtn = overlayContainerElement.querySelector('button[md-raised-button]');
      const nameInput = overlayContainerElement.querySelector('input[formcontrolname=""name""]');
      const passwordInput = overlayContainerElement.querySelector('input[formcontrolname=""password""]');
      console.log('Login Button is:', loginBtn.textContent);
      console.log('Login Button is:', loginBtn.getAttribute('ng-reflect-disabled'));

      expect((nameInput as HTMLInputElement).value).toEqual('ABC');
      expect((passwordInput as HTMLInputElement).value).toEqual('12345678');
      expect((overlayContainerElement.querySelector('button[md-raised-button]')).getAttribute('ng-reflect-disabled')).toBe('false');
    });
  }));
});
</code></pre>
",https://stackoverflow.com/questions/45119274/angular-material-2-dialog-with-form-test-failing,"['angular', 'unit-testing', 'angular-material', 'dialog']",1351,TRUE,1,1
angular2 how to unit test pipe needing mock service,"<p>I'm trying to write a unit test for a Pipe that takes in an object as a parameter. This object is created from a mock service. </p>

<p>Is it possible to use a mock service when unit testing a pipe? Do I have to include the component that uses the pipe in the test?</p>

<p><strong>PIPE</strong> - this pipe basically takes in an object and a set of arguments. Based on the arguments it manipulates the object parameter and returns it.</p>

<pre><code>@Pipe({
  name: 'myPipe'
})
export class MyPipe implements PipeTransform {

  transform(myData: models.MyInfo, args: string[]): string { //stuff here }
}
</code></pre>

<p><strong>MOCK SERVICE</strong> - the mock service queries object array which is used in the parameter of the pipe.</p>

<pre><code>@Injectable()
export class MockMyService {
getMyInfo(){
//logic
}
</code></pre>

<p><strong>EXAMPLE OF PIPE USE IN COMPONENT</strong> - below is an example of how it's used</p>

<pre><code>this.xObj = this.realService.GetInfo();     
this.myList = this.myPipe.transform(this.xObj[0], ['a', 'b', 'c',]).split(',');
</code></pre>

<p><strong>UNIT TEST THAT I TRIED</strong> - I've tried a couple of things. the code below shows how I've tried to couple the Component and Pipe, and also trying to test the pipe without the component.</p>

<pre><code>//core dependencies
import { ComponentFixture, TestBed }  from ""@angular/core/testing"";
import { NO_ERRORS_SCHEMA }           from '@angular/core';
import { By }                         from '@angular/platform-browser';
import { DebugElement }               from '@angular/core';
import { RouterTestingModule }        from '@angular/router/testing';
import { HttpModule }                 from '@angular/http';
import { DatePipe }                   from '@angular/common';

//pipe, component being tested
import { MyPipe } from './path to pipe';
import { ComponentThatUsesPipe } from '../path to the component';

//models / other
import { MOCKEDOBJECT } from '..path'

//services
import { MockMyService } from '..path to service';
import { RealService } from '..path to real service';

describe('myPipe', () =&gt; {
  let pipe = new MyPipe();
  let component: ComponentThatUsesPipe ;

  var myDetailsArray: models.ObjDetails[] = MOCKEDOBJECT ;
  var myDetails: models.ObjDetails;
  var myList: string[] = [];


  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ComponentThatUsesPipe, MyPipe],
      providers: [{provide: RealService, useClass: MockMyService}]
    });
    component = TestBed.createComponent(ComponentThatUsesPipe ).componentInstance;
  });

  this.myList = pipe.transform(this.myDetails.m[0], ['a','b',1,2,3]);

  it('test1', () =&gt; {
     expect(this.myList.findIndex(s =&gt; s.trim() === 'Med') &gt; -1).toBe(true);
  });
});
</code></pre>

<p>My test return an error of 'cannot read property of m '. </p>

<p><strong>Edit - was able to resolve based on advice from 'estus' comments below</strong></p>

<pre><code>describe('myPipe', () =&gt; {
  let pipe = new myPipe();
  let myDetailsArray: models.ObjDetails[] = MOCKEDOBJECT;
  let myDetails: models.ObjDetails = myDetailsArray[0];
  let hasA: boolean = false;
  let hasB: boolean = false;
  let hasC: boolean = false;
  let myList: string[] = [];

  this.myList = pipe.transform(myDetails.member[0],[stuff here]).split(',');
  this.hasA = (this.myList.findIndex(s =&gt; s.trim() === 'M') &gt; -1);
  this.hasB = (this.myList.findIndex(s =&gt; s.trim() === 'P') &gt; -1);
  this.hasC = (this.myList.findIndex(s =&gt; s.trim() === 'D') &gt; -1);

  it('test myPipe hasA', () =&gt; {
     expect(this.hasA).toBe(true);
  });

  it('test myPipe hasB', () =&gt; {
     expect(this.hasB).toBe(true);
  });

  it('test myPipe hasC', () =&gt; {
     expect(this.hasC).toBe(false);
  });

});
</code></pre>
",https://stackoverflow.com/questions/44006709/angular2-how-to-unit-test-pipe-needing-mock-service,"['angular', 'unit-testing', 'karma-jasmine']",1684,FALSE,1,0
PHPUnit cannot mock __get function on mock object,"<p>I am trying to mock a mysqli object for my unit testing and therefore I have to either mock the property mysqli_result::__get() or mock the property mysqli_result::num_rows directly.
I already looked for a solution but the answers I found were just not working.</p>

<p>My Code looks like this:</p>

<pre><code>use PHPUnit\Framework\TestCase;

class Mocks extends TestCase{
    public function makeMysqliMock(array $queries): mysqli{
        // build mocked mysqli-object
        #$link = $this
        #   -&gt;getMockBuilder(""mysqli"")
        #   // set methods
        #   -&gt;setMethods(['__get', ""query"", ""real_escape_string""])
        #   -&gt;getMock();
        $link = $this-&gt;createMock(""mysqli"");
        // set method 'real_escape_string'
        $link-&gt;expects($this-&gt;any())
            -&gt;method(""real_escape_string"")
            -&gt;will($this-&gt;returnCallback(function($str){
                return addslashes($str); 
            }));
        // set method 'query'
        $link-&gt;expects($this-&gt;any())
            -&gt;method(""query"")
            -&gt;will($this-&gt;returnCallback(function(string $query) use ($queries){
                // pick the query result for the current test
                $data = isset($queries[$query]) ? $queries[$query] : null;
                // build mocked 'mysqli_result'
                if (is_array($data)){
                    $result = $this
                        -&gt;getMockBuilder(""mysqli_result"")
                        -&gt;setMethods([""fetch_assoc"", ""__get""])
                        -&gt;disableOriginalConstructor()
                        -&gt;getMock();
                    // build simulated fetch method
                    $result-&gt;expects($this-&gt;any())
                        -&gt;method(""fetch_assoc"")
                        -&gt;withAnyParameters()
                        -&gt;will($this-&gt;returnCallback(function() use ($data){
                            // set internal result pointer
                            static $index = 0;
                            // return current result - increment pointer
                            return isset($data[$index]) ? $data[$index++] : false;
                        }));
                    $result-&gt;expects($this-&gt;at(0))
                        -&gt;method(""__get"")
                        -&gt;with($this-&gt;equalTo(""mysqli_num_rows""))
                        -&gt;will($this-&gt;returnValue(count($data)));


                    return $result;
                }else {
                    return is_null($data) ? false : 1;
                }
            }));
        return $link;
    }
}
</code></pre>

<p>When I run that code phpunit gives me the following error message:</p>

<blockquote>
  <p>C:\xampp\htdocs\werimanage\php>php phpunit-6.0.11.phar tests
  PHPUnit 6.0.11 by Sebastian Bergmann and contributors.</p>
  
  <p>PHP Fatal error:  Method Mock_mysqli_result_d3aa5482::__get() must take exactly 1 argument in phar://C:/xampp/htdocs/werimanage/php/phpunit-6.0.11.phar/phpunit-mock-objects/Generator.php(263) : eval()'d code on line 53</p>
  
  <p>Fatal error: Method Mock_mysqli_result_d3aa5482::__get() must take exactly 1 argument in phar://C:/xampp/htdocs/werimanage/php/phpunit-6.0.11.phar/phpunit-mock-objects/Generator.php(263) : eval()'d code on line 53</p>
</blockquote>

<p>So I do not know what the error is or how to fix it. I would really appreciate your help. Thanks!</p>
",https://stackoverflow.com/questions/43138298/phpunit-cannot-mock-get-function-on-mock-object,"['php', 'unit-testing', 'mocking', 'phpunit']",1725,TRUE,1,2
How to test an action creator with a fetch API request,"<p>I have a create-react-app with Redux and Jest for testing. I am using fetch to make the API request from an action creator. As I am writing tests I found that for what ever reason – anyway I am trying to mock this request - it is still trying to make the actual request to the API and getting a Network Connection Error (so I get the catch from the request each time when test). It might be worth mentioning that this works fine in the browser. </p>

<pre><code>import fetch from 'isomorphic-fetch';
import { SUBMIT_SUCCESS, EMPLOYEE_DETAILS, ERROR } from './actionTypes';
import { API_URL } from '../../Constants';

 export function getEmployeeDetails(id) {
   return async dispatch =&gt; {
    try {
      let payload = await (await fetch(`${API_URL}/users/${id}`, {
        method: 'GET',
        headers: { jwt: localStorage.getItem('jwt') },
      })).json();

      dispatch(getEmployeeDetailsSuccess(payload.user));
    } catch (err) {
      dispatch(errorCatch(err));
    }
  };
}
</code></pre>

<p>I have tried this - <a href=""https://medium.com/@ferrannp/unit-testing-with-jest-redux-async-actions-fetch-9054ca28cdcd"" rel=""nofollow noreferrer"">https://medium.com/@ferrannp/unit-testing-with-jest-redux-async-actions-fetch-9054ca28cdcd</a></p>

<p>I have also tired this - <a href=""https://medium.com/@kellyrmilligan/testing-async-actions-in-redux-with-isomorphic-fetch-and-fetch-mock-35f98c6c2ee7"" rel=""nofollow noreferrer"">https://medium.com/@kellyrmilligan/testing-async-actions-in-redux-with-isomorphic-fetch-and-fetch-mock-35f98c6c2ee7</a></p>

<p>And basically spent a couple of days trying to work on this.</p>

<p>What am I doing wrong? Any chance to get a working example of how to test this action?</p>

<p>Thank you!</p>
",https://stackoverflow.com/questions/47043654/how-to-test-an-action-creator-with-a-fetch-api-request,"['reactjs', 'testing', 'redux', 'jestjs', 'create-react-app']",979,TRUE,1,1
Unable to test a controller for service call,"<p>I am trying to write a code to test the service call which is done in my controller . I am trying to unit test that particular function in controller which is doing the service call and bringing the data . Currently i am trying with local json , but it will actually do a service call . </p>

<p>I got to know that first i have create a spy object but i am getting the error as ""TypeError: jasmine.CreateSpyObj is not a function"" , i am new to unit testing . I am unable to create a spyobject so unable to proceed further .Pasting my code , request you to help me please.</p>

<p>Also i am not sure what exactly i have to do once i successfully create spyObject , i actually want to test if my service is getting hit fine and i am getting response from service.</p>

<p>Please help me i am stryggling in this from many days now.</p>

<p>Service code : </p>

<pre><code>//app is the module name
app.factory('appServices', ['$rootScope', '$http', function($rootScope, 
$http) {
var appServices = {};
appServices.getData = function(){
      return $http.get(scripts/services/data/unitTesting.json'); 
 };
</code></pre>

<p>unitTesting.json code : </p>

<pre><code>{
""name"":""unit testing"",
""countryCode"": ""EG"",
""countryName"": ""Egypt"",
""region"": ""Africa""
}
</code></pre>

<p>Controller Code : </p>

<pre><code>getData: function(){
        appServices.getData().then(function(response) {
            if (response &amp;&amp; response.data) {
                $scope.testVariable= response.data.name;
            }
        });
    },
</code></pre>

<p>Unit Test Code : </p>

<pre><code>  describe('myCtrl', function() {
      beforeEach(module('app'));

      var $controller;

      beforeEach(inject(function(_$controller_){
         $controller = _$controller_;
  }));

 describe('service call test', function() {
 var $http,$httpBackend,appServices,
 myService,$q,$rootScope,controller;

 var mockItem = 
       {
       ""name"":""unit testing"",
       ""countryCode"": ""EG"",
       ""countryName"": ""Egypt"",
       ""region"": ""Africa""
       }
 beforeEach(inject(function(_$http_,_$httpBackend_,appServices,_$q_, 
 _$rootScope_) {
   $http = _$http_;
   $httpBackend = _$httpBackend_; 
   appServices = appServices; 
   $rootScope = _$rootScope_;
   $q =_$q_;
   jasmine.spyOn(appServices, 'getData').and.returnValue($q.when(mockItem));
   controller = $controller('myCtrl', { $scope: $scope });
 }));
  it('Service call test ', function() {
  controller = $controller('myCtrl', { $scope: $rootScope.new() });
  controller.getData();
  expect(appServices.getData).toHaveBeenCalled();
 }); 
 });
 });
</code></pre>

<p>ERROR : </p>

<pre><code> TypeError: jasmine.spyOn is not a function
</code></pre>
",https://stackoverflow.com/questions/47871973/unable-to-test-a-controller-for-service-call,"['javascript', 'angularjs', 'karma-jasmine']",99,TRUE,1,1
"What is the official way to customize, extend and move the API Publisher and API Store out of the WSO2 API Manager server?","<p>WSO2 reached out to me in Twitter and told me to put a question here if I had one.</p>

<p>My client wants to customize (for now it only means changing the layout of things) the API Publisher and API Store from a WSO2 API Manager 2.0.0.</p>

<p>Since I know that inevitably we will get to the point where the changes are going to be profound and require external libraries for new functionality (we have a library of AngularJS code which I know they will want to use), I want to know:</p>

<p>What is the official, recommended way to customize and extend the web applications for the API Store and the API Publisher? I need to have version control, unit testing, etc.</p>

<p>Is there a way to move these web apps out of the APIM server and into their own server? All our UI applications are hosted in a specific server.</p>

<p>Realistically, how much change can I introduce before make making an awful mess? </p>

<p>Thank you.</p>
",https://stackoverflow.com/questions/42770346/what-is-the-official-way-to-customize-extend-and-move-the-api-publisher-and-api,"['wso2', 'wso2-api-manager']",81,TRUE,1,1
ASP.NET Generic method to mock EF6 DbSet,"<p>In my ASP.NET MVC5 web-app I'm using the EF (Model-first) for my database-communication. For unit-testing purposes, I created a generic method to generate Mock database sets. Unfortunately, I am unable to mock all the methods because when <code>.Where()</code>, <code>.Any()</code> and <code>.Find()</code> are used in my tested code, an exception is thrown. Can anyone help me on this? My code is below.
Unittest:</p>

<pre><code>[TestClass()]
public class MessagingServiceTests
{
    Mock&lt;BoatstersEntitiesContainer&gt; _mockContext;
    MessagingService _service;
    string _connectionId;
    Guid _userId;

    [TestInitialize()]
    public void TestInitialize()
    {
        _userId = Guid.Parse(""12345678-1234-1234-1234-123412344142"");
        _connectionId = ""abc123"";


        // Setup entities
        User user = new User { Id = _userId, CustomerId = 1 };
        Customer customer = new Customer { Id = 1, User = user, FirstName = ""TestFirstName"" };
        user.Customer = customer;
        Customer boatOwnerCustomer = new Customer { Id = 2, FirstName = ""BoatOwner"" };
        Boat boat = new Boat { Id = 1, Customer = boatOwnerCustomer, CustomerId = boatOwnerCustomer.Id };
        boatOwnerCustomer.Boats.Add(boat);


        // Init mocksets
        var userMockSet = MockDbSet.Build(new List&lt;User&gt; { user });
        var customerMockSet = MockDbSet.Build(new List&lt;Customer&gt; { customer, boatOwnerCustomer });
        var conversationMockSet = MockDbSet.Build(new List&lt;Conversation&gt;());
        var messageMockSet = MockDbSet.Build(new List&lt;Message&gt;());
        var boatMockSet = MockDbSet.Build(new List&lt;Boat&gt; { boat });
        var messagingHubConnectionMockSet = MockDbSet.Build(new List&lt;MessagingHubConnection&gt;());


        // Setup mockcontext
        _mockContext = new Mock&lt;BoatstersEntitiesContainer&gt;();
        _mockContext.Setup(m =&gt; m.Users).Returns(userMockSet.Object);
        _mockContext.Setup(m =&gt; m.Customers).Returns(customerMockSet.Object);
        _mockContext.Setup(m =&gt; m.Conversations).Returns(conversationMockSet.Object);
        _mockContext.Setup(m =&gt; m.Messages).Returns(messageMockSet.Object);
        _mockContext.Setup(m =&gt; m.Boats).Returns(boatMockSet.Object);
        _mockContext.Setup(m =&gt; m.MessagingHubConnections).Returns(messagingHubConnectionMockSet.Object);


        // Start service
        _service = new MessagingService(_mockContext.Object, _userId);
    }

    [TestMethod()]
    public void When_PartnerConnected_IsTrue()
    {
        Conversation conversation = new Conversation {
            Id = 1,
            Boat = _mockContext.Object.Boats.First(b =&gt; b.Id.Equals(1)),
            BoatId = _mockContext.Object.Boats.First(b =&gt; b.Id.Equals(1)).Id
        };
        conversation.Customers.Add(_mockContext.Object.Customers.First(b =&gt; b.Id.Equals(1)));
        conversation.Customers.Add(_mockContext.Object.Customers.First(b =&gt; b.Id.Equals(2)));

        MessagingHubConnection connection = new MessagingHubConnection
        {
            Id = 1,
            Connected = true,
            ConnectionId  = ""abc123"",
            Conversation = conversation,
            ConversationId = 1,
            Customer = _mockContext.Object.Customers.First(b =&gt; b.Id.Equals(2)),
            CustomerId = 2
        };
        conversation.MessagingHubConnections.Add(connection);

        _mockContext.Object.MessagingHubConnections.Add(connection);
        _mockContext.Object.Conversations.Add(conversation);

        var result = _service.IsPartnerConnected();
        Assert.IsTrue(result);

        // Clean up
        _mockContext.Object.Conversations.RemoveRange(_mockContext.Object.Conversations);
        _mockContext.Object.MessagingHubConnections.RemoveRange(_mockContext.Object.MessagingHubConnections);
    }
}
</code></pre>

<p>Generic mockset creator:</p>

<pre><code>public static class MockDbSet
{
    public static Mock&lt;DbSet&lt;TEntity&gt;&gt; Build&lt;TEntity&gt;(List&lt;TEntity&gt; data) where TEntity : class
    {
        var queryable = data.AsQueryable();
        var mockSet = new Mock&lt;DbSet&lt;TEntity&gt;&gt;();
        mockSet.As&lt;IQueryable&lt;TEntity&gt;&gt;().Setup(m =&gt; m.Provider).Returns(queryable.Provider);
        mockSet.As&lt;IQueryable&lt;TEntity&gt;&gt;().Setup(m =&gt; m.Expression).Returns(queryable.Expression);
        mockSet.As&lt;IQueryable&lt;TEntity&gt;&gt;().Setup(m =&gt; m.ElementType).Returns(queryable.ElementType);
        mockSet.As&lt;IQueryable&lt;TEntity&gt;&gt;().Setup(m =&gt; m.GetEnumerator()).Returns(queryable.GetEnumerator());
        mockSet.Setup(m =&gt; m.Add(It.IsAny&lt;TEntity&gt;())).Callback&lt;TEntity&gt;(data.Add);

        return mockSet;
    }
}
</code></pre>

<p>Messagingservice (which is being tested)</p>

<pre><code>public class MessagingService : BaseRepository&lt;Conversation&gt;
{
    private readonly Customer _customer;
    private MessagingHubConnection _connection;

    public MessagingService(BoatstersEntitiesContainer context, Guid userId) : base(context)
    {
        Context = context;
        _customer = Context.Customers.First(c =&gt; c.User.Id == userId);
    }


    public bool IsPartnerConnected()
    {
        // Check if partner is connected
        return Context.MessagingHubConnections.Any(c =&gt; c.ConversationId.Equals(_connection.ConversationId) &amp;&amp; c.Customer.Id != _customer.Id &amp;&amp; c.Connected);
    }
}
</code></pre>

<p>In MessagingService.IsPartnerConnected(), the following exception is thrown:</p>

<blockquote>
  <p>Test Name:    When_PartnerConnected_IsTrue
  Test FullName:  Boatsters.Sunshine.UnitTests.MessagingServiceTests.When_PartnerConnected_IsTrue
  Test Source:    C:\Users\Jelle\Source\Repos\Boatsters.Sunshine\Boatsters.Sunshine.UnitTests\MessagingServiceUnitTest.cs : line 94
  Test Outcome:   Failed
  Test Duration:  0:00:00,0289022
  Result StackTrace:<br>
  bij lambda_method(Closure , MessagingHubConnection )
     bij System.Linq.Enumerable.Any[TSource](IEnumerable<code>1 source, Func</code>2 predicate)
     bij lambda_method(Closure )
     bij System.Linq.EnumerableExecutor<code>1.Execute()
     bij System.Linq.EnumerableQuery</code>1.System.Linq.IQueryProvider.Execute[S](Expression expression)
     bij System.Linq.Queryable.Any[TSource](IQueryable<code>1 source, Expression</code>1 predicate)
     bij Boatsters.Services.MessagingService.IsPartnerConnected() in C:\Users\Jelle\Source\Repos\Boatsters.Sunshine\Boatsters.Services\MessagingService.cs:line 156
     bij xxx.MessagingServiceTests.When_PartnerConnected_IsTrue() in C:\xxx\MessagingServiceUnitTest.cs:line 118
  Result Message: 
  Test method
  xxx.UnitTests.MessagingServiceTests.When_PartnerConnected_IsTrue threw exception: 
  System.NullReferenceException: Object reference not set to an instance of an object</p>
</blockquote>
",https://stackoverflow.com/questions/43111482/asp-net-generic-method-to-mock-ef6-dbset,"['c#', 'entity-framework', 'unit-testing', 'generics', 'moq']",820,TRUE,1,1
C# Moq - alternatives to CallBase when mocking void function,"<p>CallBase is a function in <a href=""https://www.nuget.org/packages/Moq/"" rel=""nofollow noreferrer"">Moq </a> (a C# unit testing library), which allows for easily <strong>hooking into function calls with custom code, while also preserving the base function call</strong>. Its uses and limitations were noted on <a href=""https://stackoverflow.com/questions/2822947/when-mocking-a-class-with-moq-how-can-i-callbase-for-just-specific-methods"">this SO post answer</a>.</p>

<p>The primary limitation which that post mentions is that the CallBase function is <strong>not implemented for void functions</strong>.</p>

<p>For example, say we want to mock this Component class:</p>

<pre><code>public class Component
{
    public virtual void Do() { /* code */ }
}
</code></pre>

<p>then I want to use mock to call base AND run custom code...</p>

<pre><code>var mock = new Mock&lt;Component&gt;();
mock.Setup(m =&gt; m.Do())
    // preserve base call (NOT AN OPTION SINCE VOID FUNCTION!)
    .CallBase()
    .Callback(() =&gt; {/* custom test code */});

// if Do() was not a void function, this would be supported by the library
</code></pre>

<p>One unsatisfying alternative is to change the actual code structure we are testing by splitting the void function into two:</p>

<pre><code>public class Component
{
    public virtual void Do() { 
        this.DoInternal();
    }

    internal void DoInternal(){ /* code */ }
}
</code></pre>

<p>and then...</p>

<pre><code>var mock = new Mock&lt;Component&gt;();
mock.Setup(m =&gt; m.Do())
    .Callback(() =&gt; 
    {
        // my custom code...

        // then call base
        mock.Object.DoInternal();
    });
</code></pre>

<p>This is not ideal because it requires modifying actual code design/structure purely for testability purposes and is more work/code than would be required if CallBase was natively supported by Moq. Are there alternatives to this work-around? Perhaps implementing an extension to support this outside of the library :</p>

<pre><code>public static ICallbackResult&lt;TMock&gt; CallBase&lt;TMock&gt;(this ISetup&lt;TMock&gt; @this)
{
    // not implemented - seems difficult given how little Moq 
    // exposes the underlying implementations which it overrides

    // not sure about ICallbackResult&lt;TMock&gt; being what we'd want for return type...
    // the return type of the actual CallBase function is IReturnsResult&lt;TMock&gt;, but
    // that does not make much sense for a void function
}
</code></pre>

<p>Let me know your thoughts!</p>
",https://stackoverflow.com/questions/42962262/c-moq-alternatives-to-callbase-when-mocking-void-function,"['c#', '.net', 'unit-testing', 'mocking', 'moq']",1771,FALSE,1,2
"From a main app, how can a framework get its own bundle? (Localizable.strings)","<p>So I have a main iOS app which includes a framework I made.</p>

<p>In this framework, I created a Localizable helper as well as a Date helper.
The date helper has a function <code>timeAgo()</code> which can return ""8 hours ago"". And I want to localize this string. So I have something like this in my framework:</p>

<pre><code>public extension String {    
    public func localized(in bundle: Bundle) -&gt; String {
        if let path = bundle.path(forResource: Localize.currentLanguage(), ofType: ""lproj""),
            let bundle = Bundle(path: path) {
            return bundle.localizedString(forKey: self, value: nil, table: nil)
        }
        return self
    }
}

public extension Date {
    public func timeAgo(format: DateUnitFormat = .short) -&gt; String {
        let thisFrameworkBundle = Bundle(for: Localize.self) // Class declared in the framework
        //Whatever, just display a localized word
        return ""second"".localized(in: thisFrameworkBundle)
    }
}
</code></pre>

<p>When I run local test (unit testing inside the framework itself), the localize thing works. The bundle is found.</p>

<p>But when I call <code>timeAgo</code> from my main app, it doesn't work anymore.</p>

<p>I tried to change this line <code>let thisFrameworkBundle = Bundle(for: Localize.self)</code> into <code>let thisFrameworkBundle = Bundle(identifier: ""com.myIdentifier"")</code>, same thing (so it works within the framework, but won't work when called from the main app).</p>

<p><strong>EDIT:</strong></p>

<p>Okay, so I noticed that <code>Bundle(identifier: ""com.myIdentifier"")</code> won't work within the framework because I'm using Cocoapods and it overrides the framework identifier with a cocoapod one. However, I still don't understand why using <code>Bundle(for: FrameworkClass.self)</code> won't work from the main app (but works in the Unit Test of the framework)</p>
",https://stackoverflow.com/questions/43073096/from-a-main-app-how-can-a-framework-get-its-own-bundle-localizable-strings,"['ios', 'swift', 'internationalization', 'bundle']",569,FALSE,1,1
JUnit Testing EJB layer with embedded glassfish and Maven,"<p>I have an existing JEE Maven and Eclipse project:</p>

<pre><code>mainProject.ear
+--project1.war
+--project2.war
+--ejb-proj.jar
</code></pre>

<p>I would like to have a test profile for unit testing the EJB project, including read/write database with JPA.</p>

<p>I have added a dependency in my <code>pom.xml</code> like this:</p>

<pre><code>        &lt;!-- Embedded glassfish --&gt;
        &lt;plugin&gt;
            &lt;groupId&gt;org.glassfish&lt;/groupId&gt;
            &lt;artifactId&gt;maven-embedded-glassfish-plugin&lt;/artifactId&gt;
            &lt;version&gt;3.0-74b&lt;/version&gt;
            &lt;configuration&gt;
                &lt;goalPrefix&gt;embedded-glassfish&lt;/goalPrefix&gt;
                &lt;port&gt;8080&lt;/port&gt;
                &lt;autoDelete&gt;true&lt;/autoDelete&gt;
            &lt;/configuration&gt;
            &lt;dependencies&gt;
                &lt;dependency&gt;
                    &lt;groupId&gt;mysql&lt;/groupId&gt;
                    &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
                    &lt;version&gt;5.1.44&lt;/version&gt;
                &lt;/dependency&gt;
            &lt;/dependencies&gt;
</code></pre>

<p>Then I have created a test class:</p>

<pre><code>@Before
public void setup() {

    // instantiate container and context
    ejbContainer = EJBContainer.createEJBContainer();
    logger.info(""Opening the container"");
    ctx = ejbContainer.getContext();
}
</code></pre>

<p>These are the Maven goals, in Eclipse ""skip test"" is unflagged:</p>

<pre><code>clean compile package
</code></pre>

<p>Glassfish is correctly started but I get an error about missing jdbc driver.</p>

<pre><code>Class name is wrong or classpath is not set for : com.mysql.jdbc.jdbc2.optional.MysqlDataSource
</code></pre>

<p>So, these are the questions:</p>

<ol>
<li>Why is the mysql dependency in embedded glassfish ignored ? </li>
<li>Is it correct to start the embedded container from the test class ? Maybe it would be better to have it started during the test phases.</li>
<li>In the end I want the container to be initialized only for the ejb test, so I suppose I have to deploy the ejb jar only. How can I do that ?</li>
</ol>

<p>For completeness, the same maven goals with <code>skip test = true</code> just work. And the .ear deployed in a running container works too.</p>
",https://stackoverflow.com/questions/46211594/junit-testing-ejb-layer-with-embedded-glassfish-and-maven,"['java', 'maven', 'junit', 'glassfish', 'ejb']",326,FALSE,1,0
Android Testing Platform,"<p>First, I am not asking about Unit Testing.  I am asking about the construction of a testing platform like so many out there that can be found by Googling the topic.  </p>

<p>I would like to utilize VirtualBox to build an Android Testing Farm.  So for example, download a copy of the Sumsung Emulator for one of their phones and then build a VM on VirtualBox to run it.  </p>

<p>What are some of the considerations that I would need to take into account; also, any best practices would help.</p>

<p><strong>Edit</strong></p>

<p>Thank you to Ken Wolf for providing the link in the comments below to Google's Firebase Testing Platform.  </p>

<p>To user1050755's comment, thank you for the advice.  I guess the better question is how to automate the running for emulators.  Researching this, it appears <a href=""https://developer.android.com/studio/test/monkeyrunner/index.html"" rel=""nofollow noreferrer"">Android Studio has a guide</a> (Monekyrunner) to do just this. </p>

<p>If anyone has any other suggestion, please post below.</p>
",https://stackoverflow.com/questions/44461618/android-testing-platform,"['android', 'automated-tests']",24,FALSE,0,0
Should we split an interface if only some methods of the interface are needed,"<p>Imagine we have an interface like below:</p>

<pre><code>public interface ISome
{
    void MethodOne();
    int MethodTwo();
    string MethodThree();
}
</code></pre>

<p>A class implements the interface:</p>

<pre><code>public class Some : ISome
{
    // Implementation...
}
</code></pre>

<p>Here is how it may be used:</p>

<pre><code>public class App
{
    public App(ISome)
    {
        // This class needs the whole interface: All three methods
    }
}
</code></pre>

<p>I have a new requirement and it only needs one method from it: <code>MethodThree</code> and it can use the implementation provided by <code>Some</code>. Now I have 2 options:</p>

<ol>
<li>Use <code>ISome</code> in the new class, like <code>App</code> uses it. The problem with this is that the new class does not really depend on the whole interface but only one method.</li>
<li><p>Split the interface like this using inheritance:</p>

<pre><code>public interface INewSome
{
    string MethodThree();
}

public interface ISome : INewSome
{
    void MethodOne();
    int MethodTwo();
}
</code></pre></li>
</ol>

<p>The benefits of the 2nd option are:</p>

<ol>
<li>The new class will depend on <code>INewSome</code></li>
<li><code>Some</code> still implements the whole interface so existing code will not break.</li>
<li>Unit testing will be much clearer since we know we just need to mock/stub one method in <code>INewSome</code></li>
</ol>

<p><strong>Questions</strong></p>

<ol>
<li>I cannot think of a benefit for option 1 aside from not having to introduce a new interface. Do you know of a benefit with option 1?</li>
<li>Do you have another suggestion? </li>
<li>Am I overlooking anything and is this good/bad design?</li>
</ol>
",https://stackoverflow.com/questions/45201422/should-we-split-an-interface-if-only-some-methods-of-the-interface-are-needed,"['c#', 'oop']",65,TRUE,-6,1
return model instance from controller to test class in laravel,"<p>i am unit testing in laravel with Phpunit. The situation is i have to return a model instance from the controller back to the testing class. There i will use the attributes of that object to test an assertion. How can i achieve that? </p>

<p>Currently i am json encoding that instance into the response. And using it in a way that works but is ugly. Need a clearer way.</p>

<p>This is my test class:</p>

<pre><code>/** @test
*/
function authenticated_user_can_create_thread()
{
    //Given an authenticated user

    $this-&gt;actingAs(factory('App\User')-&gt;create());

    //and a thread

    $thread = factory('App\Thread')-&gt;make();

    //when user submits a form to create a thread

    $created_thread = $this-&gt;post(route('thread.create'),$thread-&gt;toArray());

    //the thread can be seen

    $this-&gt;get(route('threads.show',['channel'=&gt;$created_thread-&gt;original-&gt;channel-&gt;slug,'thread'=&gt;$created_thread-&gt;original-&gt;id]))
        -&gt;assertSee($thread-&gt;body);
}
</code></pre>

<p>and this is the controller method:</p>

<pre><code>public function store(Request $request)
{
    $thread = Thread::create([
        'user_id'=&gt;auth()-&gt;id(),
        'title'=&gt;$request-&gt;title,
        'body'=&gt;$request-&gt;body,
        'channel_id'=&gt;$request-&gt;channel_id,
    ]);

    if(app()-&gt;environment() === 'testing')
    {
       return response()-&gt;json($thread);   //if request is coming from phpunit/test environment then send back the creted thread object as part of json response
    }

    else 
        return redirect()-&gt;route('threads.show',['channel'=&gt;$thread-&gt;channel-&gt;slug,'thread'=&gt;$thread-&gt;id]);
}
</code></pre>

<p>As you can see in the test class, i am receiving the object returned from controller in the <strong>$created_thread</strong> variable. However, controller is returning an instance of <strong>Illuminate\Foundation\Testing\TestResponse</strong>, so the THREAD that is embedded in this response is not easy to extract. You can see i am doing 
 --> $created_thread-><strong>original</strong>->channel->slug,'thread'=>$created_thread-><strong>original</strong>->id]. But i am sure there is a better way of achieving the same thing.</p>

<p>Can anyone please guide me to the right direction?</p>
",https://stackoverflow.com/questions/46936701/return-model-instance-from-controller-to-test-class-in-laravel,"['phpunit', 'laravel-5.4', 'laravel-testing']",1640,FALSE,0,1
Pasted code over to another class and it doesnt work?,"<p>I have a piece of code </p>

<pre><code>string phoneMobileW = null;
string phoneMobileP = null;
string phoneMain = null;
string phoneWork = null;
string phoneHome = null;

if (coreData.ListOfAddress_0006 != null &amp;&amp; coreData.ListOfAddress_0006.Count() &gt; 0)
{
    var phoneqry = from list in coreData.ListOfAddress_0006
        .Where(a =&gt; a.Subtype.ID == ""1"")
        .OrderByDescending(a =&gt; a.StartDate)
        .Take(1)
        .Where(p =&gt; p.ListOfPhoneNumber_0006 != null)
        .SelectMany(p =&gt; p.ListOfPhoneNumber_0006)
        select list;

    if (phoneqry != null)
    {
        var phoneList = phoneqry.ToList();
        phoneMobileW = phoneList
            .Where(q =&gt; q.NumberType.ID == ""MOBW"")
            .Select(q =&gt; q.Number)
            .LastOrDefault();
    }
}
</code></pre>

<p>The phone numbers are contained inside the address. If the address is not empty get the last phone number. However I have coped and pasted this piece of code over to another class it and it longer works.
<a href=""https://i.stack.imgur.com/mxriH.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/mxriH.png"" alt=""enter image description here""></a></p>

<p>So where it works you can see the 'var' for phoneqry is interface System.Collections.Generic.Ienumerable</p>

<p>As I said I have copied it over to another class which is a unit testing class.
I am trying to populate the phone number.</p>

<p>When I hold the cursor over var, nothing appears to show me what object it is(is this because its in a unitTest class?)</p>

<p>anyway the error I get is for .Where in <code>var phoneqry = from list in coreData.ListOfAddress_0006.Where</code></p>

<blockquote>
  <p>Error 4   'System.Array' does not contain a definition for 'Where' and no extension method 'Where' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?) D:\MartinsCode\New folder\Trunk\BusinessLogic\SapEai.UnitTest\AdUnitTest.cs 166 73  RFS.BusinessLogic.SapEai.UnitTest</p>
</blockquote>
",https://stackoverflow.com/questions/47297533/pasted-code-over-to-another-class-and-it-doesnt-work,['c#'],41,TRUE,-1,1
Mocking imports with webpack 2 / karma,"<p>I am trying to figure out how to speed up the unit testing on my project. I am using webpack 2 and karma.</p>

<p>I have a custom npm module which I am bundling with my application. This has a lot of exports which have dependencies (using tree shaking in project).</p>

<p>For example index.js of my npm module ""Test"" looks like this:</p>

<pre><code>export Button from ""./Button""
export Unused1 from ""./Unused1""
export Unused2 from ""./Unused2""
...many more imports follow
</code></pre>

<p>My component tests will use ""Button"" from ""Test""</p>

<pre><code>import {Button} from ""Test""
</code></pre>

<p>I want to create a simple test which will be bundled by webpack and fed to karma/phantomjs. The test should only bundle/resolve what is needed, so for example it should only resolve ""Button"" in the above example.</p>

<p>I have tried mocking ""Test"" using
<a href=""https://github.com/plasticine/inject-loader"" rel=""nofollow noreferrer"">https://github.com/plasticine/inject-loader</a>
and
<a href=""https://github.com/speedskater/babel-plugin-rewire"" rel=""nofollow noreferrer"">https://github.com/speedskater/babel-plugin-rewire</a></p>

<p>Basically, I tried injecting ""Test"" : { Button}, where Button I imported from ""Test/Button"" in my test file. </p>

<p>They both seem to still bundle the whole index.js of ""Test"" which includes all the exports.</p>

<p>Any tips? Thanks!</p>
",https://stackoverflow.com/questions/44009842/mocking-imports-with-webpack-2-karma,"['javascript', 'node.js', 'unit-testing', 'webpack', 'karma-runner']",439,FALSE,0,1
VSTS not showing passing NUnit tests in results,"<p>I'm very new to powershell unit testing. I wrote my ""hello world"" tests below: </p>

<pre><code>[CmdletBinding()]
param()

Describe MyFailTest{
    Assert-Throws {
         throw ""I do nothing interesting.""
    } -MessagePattern ""Not that message because I want a failure""
}

Describe MyPassTest{
    Assert-Throws {
        throw ""I will pass""
    } -MessagePattern ""I will pass""
}
</code></pre>

<p>And that looks like I would expect when run locally, the first one fails as the message pattern did not match, and the second test passes.</p>

<p>Now I'm trying to run the test as part of a CI/CD pipeline. I'm using ""Pester Test Runner from Black Marble"" task to kick off my .tests.ps1 files. In my NUnit output I can see it marked my tests as passing and failing as expected.</p>

<p>So now we get to the odd part. I used the publish results task in VSTS and I only ever see failed tests. Why am I not seeing passing tests as well? Seems odd it reports that 1/1 tests failed if I have a successful test run. I don't see any options to change that. I tried setting the Outcome filter to ""All"" in the tests tab. Any ideas?</p>

<p>Pertinent log sections:</p>

<pre><code>Evaluating condition for step: 'Pester Test Runner'
Evaluating: succeeded()
Evaluating succeeded:
=&gt; (Boolean) True
Expanded: True
Result: True
##[section]Starting: Pester Test Runner
==============================================================================
Task         : Pester Test Runner from Black Marble
Description  : Run Pester tests without the need to install Pester in with the PMModule folder or in the source repo (Using Pester 3.4.3 or 4.0.8)
Version      : 6.0.9
Author       : Richard Fennell
Help         : Version: 6.0.9. [More Information](https://github.com/rfennell/vNextBuild/wiki/Pester-Task/)
==============================================================================
Preparing task execution handler.
Executing the powershell script: d:\a\_tasks\Pester_31ef0033-64e3-4c55-b888-f446541474a6\6.0.9\Pester.ps1
PowerShellHandler.Execute - AddCommand(d:\a\_tasks\Pester_31ef0033-64e3-4c55-b888-f446541474a6\6.0.9\Pester.ps1)
PowerShellHandler.Execute - Add inputParameters
PowerShellHandler.Execute - AddParameter(scriptFolder=d:\a\1\s\Tasks\XXXXTWStaging\Tests\)
PowerShellHandler.Execute - AddParameter(resultsFile=d:\a\1\s\Test-Pester.XML)
PowerShellHandler.Execute - AddParameter(CodeCoverageOutputFile=)
PowerShellHandler.Execute - AddParameter(tag=)
PowerShellHandler.Execute - AddParameter(excludeTag=)
PowerShellHandler.Execute - AddParameter(pesterVersion=4.0.8)
PowerShellHandler.Execute - AddParameter(run32Bit=False)
PowerShellHandler.Execute - AddParameter(moduleFolder=)
PowerShellHandler.Execute - Invoke
Running in AMD64 PowerShell
Loading Pester module from [D:\a\_tasks\Pester_31ef0033-64e3-4c55-b888-f446541474a6\6.0.9\4.0.8]
Loading module from path 'D:\a\_tasks\Pester_31ef0033-64e3-4c55-b888-f446541474a6\6.0.9\4.0.8\Pester.psd1'.
Loading module from path 'D:\a\_tasks\Pester_31ef0033-64e3-4c55-b888-f446541474a6\6.0.9\4.0.8\Pester.psm1'.
Processed: ##vso[task.setprogress value=-1;] 
Loading module from path 'D:\a\_tasks\Pester_31ef0033-64e3-4c55-b888-f446541474a6\6.0.9\4.0.8\lib\Gherkin.dll'.

    namespace Pester
    {
        using System;
        using System.Management.Automation;

        public static class ClosingBraceFinder
        {
            public static int GetClosingBraceIndex(PSToken[] tokens, int startIndex)
            {
                int groupLevel = 1;
                int len = tokens.Length;

                for (int i = startIndex + 1; i &lt; len; i++)
                {
                    PSTokenType type = tokens[i].Type;
                    if (type == PSTokenType.GroupStart)
                    {
                        groupLevel++;
                    }
                    else if (type == PSTokenType.GroupEnd)
                    {
                        groupLevel--;

                        if (groupLevel &lt;= 0) { return i; }
                    }
                }

                return -1;
            }
        }
    }

using System;

namespace Pester
{
    [Flags]
    public enum OutputTypes
    {
        None = 0,
        Default = 1,
        Passed = 2,
        Failed = 4,
        Pending = 8,
        Skipped = 16,
        Inconclusive = 32,
        Describe = 64,
        Context = 128,
        Summary = 256,
        Header = 512,
        All = Default | Passed | Failed | Pending | Skipped | Inconclusive | Describe | Context | Summary | Header,
        Fails = Default | Failed | Pending | Skipped | Inconclusive | Describe | Context | Summary | Header
    }
}
Exporting function 'Context'.
Exporting function 'Describe'.
Exporting function 'In'.
Exporting function 'It'.
Exporting function 'Mock'.
Exporting function 'Assert-VerifiableMock'.
Exporting function 'Assert-MockCalled'.
Exporting function 'Set-TestInconclusive'.
Exporting function 'Assert-VerifiableMocks'.
Exporting function 'InModuleScope'.
Exporting function 'Invoke-Mock'.
Exporting function 'New-Fixture'.
Exporting function 'Get-TestDriveItem'.
Exporting function 'Setup'.
Exporting function 'Should'.
Exporting function 'Invoke-Pester'.
Exporting function 'BeforeEach'.
Exporting function 'AfterEach'.
Exporting function 'BeforeAll'.
Exporting function 'AfterAll'.
Exporting function 'Set-DynamicParameterVariable'.
Exporting function 'Get-MockDynamicParameter'.
Exporting function 'New-PesterOption'.
Exporting function 'SafeGetCommand'.
Exporting function 'Invoke-Gherkin'.
Exporting function 'Find-GherkinStep'.
Exporting function 'Invoke-GherkinStep'.
Exporting function 'BeforeEachFeature'.
Exporting function 'AfterEachFeature'.
Exporting function 'BeforeEachScenario'.
Exporting function 'AfterEachScenario'.
Exporting function 'GherkinStep'.
Exporting alias 'Given'.
Exporting alias 'When'.
Exporting alias 'Then'.
Exporting alias 'And'.
Exporting alias 'But'.
Exporting function 'Add-AssertionOperator'.
Exporting function 'New-MockObject'.
Importing function 'Add-AssertionOperator'.
Importing function 'AfterAll'.
Importing function 'AfterEach'.
Importing function 'AfterEachFeature'.
Importing function 'AfterEachScenario'.
Importing function 'Assert-MockCalled'.
Importing function 'Assert-VerifiableMock'.
Importing function 'Assert-VerifiableMocks'.
Importing function 'BeforeAll'.
Importing function 'BeforeEach'.
Importing function 'BeforeEachFeature'.
Importing function 'BeforeEachScenario'.
Importing function 'Context'.
Importing function 'Describe'.
Importing function 'Find-GherkinStep'.
Importing function 'Get-MockDynamicParameter'.
Importing function 'Get-TestDriveItem'.
Importing function 'GherkinStep'.
Importing function 'In'.
Importing function 'InModuleScope'.
Importing function 'Invoke-Gherkin'.
Importing function 'Invoke-GherkinStep'.
Importing function 'Invoke-Mock'.
Importing function 'Invoke-Pester'.
Importing function 'It'.
Importing function 'Mock'.
Importing function 'New-Fixture'.
Importing function 'New-MockObject'.
Importing function 'New-PesterOption'.
Importing function 'SafeGetCommand'.
Importing function 'Set-DynamicParameterVariable'.
Importing function 'Set-TestInconclusive'.
Importing function 'Setup'.
Importing function 'Should'.
Importing alias 'And'.
Importing alias 'But'.
Importing alias 'Given'.
Importing alias 'Then'.
Importing alias 'When'.
Running Pester from [d:\a\1\s\Tasks\XXXXTWStaging\Tests\] output sent to [d:\a\1\s\Test-Pester.XML]
Exporting function 'EnterTestGroup'.
Exporting function 'LeaveTestGroup'.
Exporting function 'AddTestResult'.
Exporting function 'AddSetupOrTeardownBlock'.
Exporting function 'GetTestCaseSetupBlocks'.
Exporting function 'GetTestCaseTeardownBlocks'.
Exporting function 'GetCurrentTestGroupSetupBlocks'.
Exporting function 'GetCurrentTestGroupTeardownBlocks'.
Exporting function 'EnterTest'.
Exporting function 'LeaveTest'.
Exporting variable 'Strict'.
Exporting variable 'Show'.
Exporting variable 'TagFilter'.
Exporting variable 'ExcludeTagFilter'.
Exporting variable 'TestNameFilter'.
Exporting variable 'SessionState'.
Exporting variable 'CommandCoverage'.
Exporting variable 'InTest'.
Exporting variable 'TestResult'.
Exporting variable 'TotalCount'.
Exporting variable 'Time'.
Exporting variable 'PassedCount'.
Exporting variable 'FailedCount'.
Exporting variable 'SkippedCount'.
Exporting variable 'PendingCount'.
Exporting variable 'InconclusiveCount'.
Exporting variable 'IncludeVSCodeMarker'.
Exporting variable 'TestSuiteName'.
Exporting variable 'TestActions'.
Exporting variable 'TestGroupStack'.
Executing all tests in 'd:\a\1\s\Tasks\XXXXTWStaging\Tests\'




Executing script D:\a\1\s\Tasks\XXXXTWStaging\Tests\L0ValidateDestinationPath.tests.ps1


Importing module: TestHelpersModule
Stubbing command: Import-Module
Setting copyFilesToMachinesPath
Asserting script block should throw: {
   Validate-DestinationPath -value """" -environmentName $validEnvironmentName
}
Success. Matched exception message. Pattern: WFC_ParameterCannotBeNullorEmpty targetPath ; Message: WFC_ParameterCannotBeNullorEmpty targetPath
Asserting script block should throw: {
    Validate-DestinationPath -value $invalidTargetPath -environmentName $validEnvironmentName
}
Success. Matched exception message. Pattern: WFC_RemoteDestinationPathCannotContainEnvironmentVariables $env:abc\123 ; Message: WFC_RemoteDestinationPathCannotContainEnvironmentVariables $env:abc\123


Executing script D:\a\1\s\Tasks\XXXXTWStaging\Tests\L0ValidateSourcePath.tests.ps1


Importing module: TestHelpersModule
Invoking mock command: Import-Module
  Arguments: D:\a\1\s\Tasks\XXXXTWStaging\Tests\lib/TestHelpersModule -Verbose: False
  Command is stubbed.
Stubbing command: Import-Module
Mocking command: Test-Path
  ParametersEvaluator: { $LiteralPath -eq $invalidSourcePath }
  Func: { return $false }
Asserting script block should throw: {
    Validate-SourcePath -value """"
}
Success. Matched exception message. Pattern: WFC_ParameterCannotBeNullorEmpty sourcePath ; Message: WFC_ParameterCannotBeNullorEmpty sourcePath
Asserting script block should throw: {
    Validate-SourcePath -value ""$invalidSourcePath""
}
Invoking mock command: Test-Path
  Arguments: -LiteralPath Invalid
  Matching implementation found using parameters evaluator: { $LiteralPath -eq $invalidSourcePath }
  Invoking Func: { return $false }
Success. Matched exception message. Pattern: WFC_SourcePathDoesNotExist Invalid ; Message: WFC_SourcePathDoesNotExist Invalid


Executing script D:\a\1\s\Tasks\XXXXTWStaging\Tests\L0ValidInputSequentialCopy.tests.ps1


Importing module: TestHelpersModule
Invoking mock command: Import-Module
  Arguments: D:\a\1\s\Tasks\XXXXTWStaging\Tests\lib/TestHelpersModule -Verbose: False
  Command is stubbed.
Stubbing command: Import-Module
Setting copyFilesToMachinesPath
Mocking command: Test-Path
  ParametersEvaluator: { $LiteralPath -eq  $validSourcePackage }
  Func: { return $true }
Mocking command: Test-Path
  ParametersEvaluator: { $LiteralPath -eq $invalidSourcePath }
  Func: { return $false }
Mocking command: Invoke-Command
  Func: {  }
Mocking command: ConvertTo-SecureString
  Func: { return $password }
Mocking command: Get-VstsInput
  ParametersEvaluator: { $Name -eq  ""SourcePath"" }
  Func: { return $validSourcePackage }
Mocking command: Get-VstsInput
  ParametersEvaluator: { $Name -eq  ""TargetPath"" }
  Func: { return $validApplicationPath }
Mocking command: Get-VstsInput
  ParametersEvaluator: { $Name -eq  ""CleanTargetBeforeCopy"" }
  Func: { return $true }
Mocking command: Get-VstsInput
  ParametersEvaluator: { $Name -eq ""TechWintelDeployService"" }
  Func: { return ""TechWintelDeployService"" }
Mocking command: Get-VstsEndpoint
  ParametersEvaluator: { $Name -eq ""TechWintelDeployService"" }
  Func: { return $myVar }
Entering D:\a\1\s\Tasks\XXXXTWStaging\WindowsMachineFileCopy.ps1.
Invoking mock command: Get-VstsInput
  Arguments: -Name TechWintelDeployService -Require
  Matching implementation found using parameters evaluator: { $Name -eq ""TechWintelDeployService"" }
  Invoking Func: { return ""TechWintelDeployService"" }
Invoking mock command: Get-VstsEndpoint
  Arguments: -Name TechWintelDeployService -Require
  Matching implementation found using parameters evaluator: { $Name -eq ""TechWintelDeployService"" }
  Invoking Func: { return $myVar }
Invoking mock command: Get-VstsInput
  Arguments: -Name SourcePath -Require
  Matching implementation found using parameters evaluator: { $Name -eq  ""SourcePath"" }
  Invoking Func: { return $validSourcePackage }
Invoking mock command: Get-VstsInput
  Arguments: -Name TargetPath -Require
  Matching implementation found using parameters evaluator: { $Name -eq  ""TargetPath"" }
  Invoking Func: { return $validApplicationPath }
Invoking mock command: Get-VstsInput
  Arguments: -Name AdditionalArguments
  Command is stubbed.
Invoking mock command: Get-VstsInput
  Arguments: -Name CleanTargetBeforeCopy
  Matching implementation found using parameters evaluator: { $Name -eq  ""CleanTargetBeforeCopy"" }
  Invoking Func: { return $true }
Importing VSTSLocStrings
Invoking mock command: Test-Path
  Arguments: -LiteralPath C:\Windows\Test
  Matching implementation found using parameters evaluator: { $LiteralPath -eq  $validSourcePackage }
  Invoking Func: { return $true }
Invoking mock command: ConvertTo-SecureString
  Arguments: Password -AsPlainText -Force
  Invoking Func: { return $password }
Invoking mock command: Invoke-Command
  Arguments: -ScriptBlock 
param (
    [string]$fqdn, 
    [string]$sourcePath,
    [string]$targetPath,
    [object]$credential,
    [string]$cleanTargetBeforeCopy,
    [string]$additionalArguments,
    [string]$scriptRoot
    )

    Import-Module ""$scriptRoot\..\ps_modules\VstsTaskSdk"" 
    Import-VstsLocStrings -LiteralPath $scriptRoot/Task.json

    Write-Verbose ""Entering script RobocopyJob.ps1""
    Write-Verbose ""fqdn = $fqdn""
    Write-Verbose ""sourcePath = $sourcePath""
    Write-Verbose ""targetPath = $targetPath""
    Write-Verbose ""credential = $credential""
    Write-Verbose ""cleanTargetBeforeCopy = $cleanTargetBeforeCopy""
    Write-Verbose ""additionalArguments = $additionalArguments""

    $sourcePath = $sourcePath.Trim().TrimEnd('\', '/')
    $targetPath = $targetPath.Trim().TrimEnd('\', '/')    

    $isFileCopy = Test-Path -Path $sourcePath -PathType Leaf
    $doCleanUp = $cleanTargetBeforeCopy -eq ""true""

    $sourceDirectory = $sourcePath
    $filesToCopy = """"
    if($isFileCopy)
    {
        $sourceDirectory = Split-Path $sourcePath
        $filesToCopy = Split-Path $sourcePath -Leaf
    }

    function ThrowError
    {
        param(
            [string]$errorMessage,
            [string]$fqdn
        )

        $failMessage = (Get-VstsLocString -Key ""WFC_CopyingFailedForResource"" -ArgumentList $fqdn)
        throw ""$failMessage`n$errorMessage""
    }

    function Validate-Null(
        [string]$value,
        [string]$variableName
        )
    {
        $value = $value.Trim()    
        if(-not $value)
        {
            ThrowError -errorMessage (Get-VstsLocString -Key ""WFC_ParameterCannotBeNullorEmpty"" -ArgumentList $variableName)
        }
    }

    function Validate-Credential(
        [object]$credential)
    {
        if($credential)
        {
            Validate-Null $credential.UserName ""Username""
            Validate-Null $credential.Password ""Password""                        
        }
        else
        {
            ThrowError -errorMessage (Get-VstsLocString -Key ""WFC_ParameterCannotBeNullorEmpty"" -ArgumentList ""credential"")
        }   
    }

    function Get-DownLevelLogonName(
        [string]$fqdn,
        [string]$userName
        )
    {
        if($userName  -like '.\*') {
            $userName = $userName.replace("".\"",""\"")
            $userName = $fqdn+$userName
        }
        return $userName
    }

    function Replace-First(
        [string]$text,
        [string]$search, 
        [string]$replace
        )
    {
        $pos = $text.IndexOf($search);
        if ($pos -le 0)
        {
            return $text;
        }

        return $text.Substring(0, $pos) + $replace + $text.Substring($pos + $search.Length);
    }

    function Get-DestinationNetworkPath(
        [string]$targetPath,
        [string]$machineShare
    )
    {
        if(-not $machineShare)
        {
            return $targetPath
        }

        $targetSpecificPath = Replace-First $targetPath "":"" '$'    
        return [io.path]::Combine($machineShare, $targetSpecificPath)    
    }    

    function Get-RoboCopyParameters(
        [string]$additionalArguments,
        [switch]$fileCopy,
        [switch]$clean)
    {
        $robocopyParameters = ""/COPY:DAT""

        if(-not $fileCopy.IsPresent)
        {
            if($clean.IsPresent)
            {
                $robocopyParameters += "" /MIR""
            }
            else
            {
                $robocopyParameters += "" /E""
            }
        }       

        if (-not [string]::IsNullOrWhiteSpace($additionalArguments))
        {
            $robocopyParameters += "" $additionalArguments""
        }

        return $robocopyParameters.Trim()
    }

    function Get-MachineShare(
        [string]$fqdn,
        [string]$targetPath
        )
    {
        if([bool]([uri]$targetPath).IsUnc)
        {
            return $targetPath
        }
        if($fqdn)
        {
            return [IO.Path]::DirectorySeparatorChar + [IO.Path]::DirectorySeparatorChar + $fqdn
        }

        return """"
    }

    function Get-NetExeCommand
    {
        $netExePath = Join-Path -path (get-item env:\windir).value -ChildPath system32\net.exe
        if(Test-Path $netExePath)
        {
            Write-Verbose ""Found the net exe path $netExePath. Net command will be $netExePath""
            return $netExePath
        }

        Write-Verbose ""Unable to get the path for net.exe. Net command will be 'net'""
        return 'net'
    }

    $machineShare = Get-MachineShare -fqdn $fqdn -targetPath $targetPath    
    $destinationNetworkPath = Get-DestinationNetworkPath -targetPath $targetPath -machineShare $machineShare

    Validate-Credential $credential
    $userName = Get-DownLevelLogonName -fqdn $fqdn -userName $($credential.UserName)
    $password = $($credential.Password) 

    $netExeCommand = Get-NetExeCommand

    if($machineShare)
    {
        $command = ""$netExeCommand use `""$machineShare`""""
        if($userName)
        {
            $command += "" /user:`'$userName`' `'$($password -replace ""['`]"", '$&amp;$&amp;')`'""
        }
        $command += "" 2&gt;&amp;1""

        $dtl_mapOut = iex $command
        if ($LASTEXITCODE -ne 0) 
        {
            $errorMessage = (Get-VstsLocString -Key ""WFC_FailedToConnectToPathWithUser"" -ArgumentList $machineShare, $($credential.UserName)) + $dtl_mapOut
            ThrowError -errorMessage $errorMessage -fqdn $fqdn
        }
    }

    try
    {
        if($isFileCopy -and $doCleanUp -and (Test-Path -path $destinationNetworkPath -pathtype container))
        {
            Get-ChildItem -Path $destinationNetworkPath -Recurse -force | Remove-Item -force -recurse;
            $output = Remove-Item -path $destinationNetworkPath -force -recurse 2&gt;&amp;1
            $err = $output | ?{$_.gettype().Name -eq ""ErrorRecord""}
            if($err)
            {
                Write-Verbose -Verbose ""Error occurred while deleting the destination folder: $err""
            }
        }

        $robocopyParameters = Get-RoboCopyParameters -additionalArguments $additionalArguments -fileCopy:$isFileCopy -clean:$doCleanUp

        $command = ""robocopy `""$sourceDirectory`"" `""$destinationNetworkPath`"" `""$filesToCopy`"" $robocopyParameters""                
        Invoke-Expression $command        

        if ($LASTEXITCODE -ge 8)
        {
            $errorMessage = Get-VstsLocString -Key ""WFC_CopyingFailedConsultRobocopyLogsForMoreDetails""            
            ThrowError -errorMessage $errorMessage -fqdn $fqdn            
        }
        else
        {            
            $message = (Get-VstsLocString -Key ""WFC_CopyingRecurivelyFrom0to1MachineSucceed"" -ArgumentList $sourcePath, $targetPath, $fqdn)
            Write-Output $message            
        }        
    }
    finally
    {
        if($machineShare)
        {            
            $dtl_deleteMap = iex ""$netExeCommand use `""$machineShare`"" /D /Y"";  
        }
    }
 -ArgumentList System.Object[]
  Invoking Func: {  }
Leaving D:\a\1\s\Tasks\XXXXTWStaging\WindowsMachineFileCopy.ps1.
Asserting was-called: Invoke-Command
  Expected times: 1
  Actual times: 1


Executing script D:\a\1\s\Tasks\XXXXTWStaging\Tests\MyFailTest.tests.ps1




  Describing MyFailTest


Invoking mock command: Test-Path
  Arguments: TestDrive:\
  Command is stubbed.
Asserting script block should throw: {
        throw ""I do nothing interesting.""
    }
    [-] Error occurred in Describe block 
778ms


      RuntimeException: Actual exception message does not match expected pattern. Expected: Not that message because I want a failure ; Actual: I do nothing interesting.


      at Assert-Throws, D:\a\1\s\Tasks\XXXXTWStaging\Tests\lib\TestHelpersModule\PublicFunctions.ps1: line 67


      at &lt;ScriptBlock&gt;, D:\a\1\s\Tasks\XXXXTWStaging\Tests\MyFailTest.tests.ps1: line 5


      at DescribeImpl, D:\a\_tasks\Pester_31ef0033-64e3-4c55-b888-f446541474a6\6.0.9\4.0.8\Functions\Describe.ps1: line 161




  Describing MyPassTest


Invoking mock command: Test-Path
  Arguments: TestDrive:\
  Command is stubbed.
Asserting script block should throw: {
        throw ""I will pass""
    }
Success. Matched exception message. Pattern: I will pass ; Message: I will pass
Tests completed in 778ms


Tests Passed: 0, 
Failed: 1, 
Skipped: 0, 
Pending: 0, 
Inconclusive: 0 


Perform operation 'Enumerate CimInstances' with following parameters, ''namespaceName' = root\cimv2,'className' = Win32_OperatingSystem'.
Operation 'Enumerate CimInstances' complete.
##[error]Microsoft.PowerShell.Commands.WriteErrorException: Pester returned errors
Processed: ##vso[task.logissue type=error;]Microsoft.PowerShell.Commands.WriteErrorException: Pester returned errors
##[error]PowerShell script completed with 1 errors.
##[section]Finishing: Pester Test Runner


Evaluating condition for step: 'Publish Test Results Test-Pester.XML'
Evaluating: succeededOrFailed()
Evaluating succeededOrFailed:
=&gt; (Boolean) True
Expanded: True
Result: True
##[section]Starting: Publish Test Results Test-Pester.XML
==============================================================================
Task         : Publish Test Results
Description  : Publish Test Results to VSTS/TFS
Version      : 2.0.1
Author       : Microsoft Corporation
Help         : [More Information](https://go.microsoft.com/fwlink/?LinkID=613742)
==============================================================================
agent.workFolder=d:\a
loading inputs and endpoints
loading ENDPOINT_AUTH_PARAMETER_SYSTEMVSSCONNECTION_ACCESSTOKEN
loading ENDPOINT_AUTH_SCHEME_SYSTEMVSSCONNECTION
loading ENDPOINT_AUTH_SYSTEMVSSCONNECTION
loading INPUT_MERGETESTRESULTS
loading INPUT_PUBLISHRUNATTACHMENTS
loading INPUT_SEARCHFOLDER
loading INPUT_TESTRESULTSFILES
loading INPUT_TESTRUNNER
loaded 8
testRunner=NUnit
testResultsFiles=Test-Pester.XML
mergeTestResults=true
platform=null
configuration=null
testRunTitle=null
publishRunAttachments=true
searchFolder=d:\a\1\s
testRunner: NUnit
testResultsFiles: Test-Pester.XML
mergeResults: true
platform: null
config: null
testRunTitle: null
publishRunAttachments: true
defaultRoot: 'd:\a\1\s'
findOptions.followSpecifiedSymbolicLink: 'true'
findOptions.followSymbolicLinks: 'true'
matchOptions.debug: 'false'
matchOptions.nobrace: 'true'
matchOptions.noglobstar: 'false'
matchOptions.dot: 'true'
matchOptions.noext: 'false'
matchOptions.nocase: 'true'
matchOptions.nonull: 'false'
matchOptions.matchBase: 'false'
matchOptions.nocomment: 'false'
matchOptions.nonegate: 'false'
matchOptions.flipNegate: 'false'
pattern: 'Test-Pester.XML'
findPath: 'd:\a\1\s\Test-Pester.XML'
statOnly: 'true'
found 1 paths
applying include pattern
adjustedPattern: 'd:\a\1\s\Test-Pester.XML'
1 matches
1 final results
Reading test results from file 'd:\a\1\s\Test-Pester.XML'
Processed: ##vso[results.publish type=NUnit;mergeResults=true;publishRunAttachments=true;resultFiles=d:\a\1\s\Test-Pester.XML;]
task result: Succeeded
Processed: ##vso[task.complete result=Succeeded;]
##[section]Async Command Start: Publish test results
Publishing test results to test run '17948'
Test results remaining: 1. Test run id: 17948
Published Test Run : https://XXXX.visualstudio.com/DevOps/_TestManagement/Runs#runId=17948&amp;_a=runCharts
##[section]Async Command End: Publish test results
##[section]Finishing: Publish Test Results Test-Pester.XML
</code></pre>
",https://stackoverflow.com/questions/47423489/vsts-not-showing-passing-nunit-tests-in-results,"['unit-testing', 'powershell', 'nunit', 'azure-pipelines']",343,FALSE,0,1
Data doesn&#39;t match to original data after converting to TFRecord,"<blockquote>
  <p><strong>TL: DR;</strong></p>
</blockquote>

<p>After converting my data to TFRecord it doesn't match with original data </p>

<blockquote>
  <p><strong>Description:</strong></p>
</blockquote>

<p>I made a <a href=""https://gist.github.com/niyamatalmass/b4e8f14d0a853b109035cc0973c03189"" rel=""nofollow noreferrer"">method</a> that will read TFRecord data. And I want to test that method that the method is working as I expected. So I create a <a href=""https://gist.github.com/niyamatalmass/160207d687cd07d20bede12d8092f429"" rel=""nofollow noreferrer"">Tensorflow test case</a> where I create a fake TFRecord file given some random input data. And pass that data to that method. The results get from that method and the original data, I pass them to the assertAllEqual() method for unit testing. But the test failed. </p>

<p>Here is test error</p>

<pre><code>AssertionError: 
Arrays are not equal

(mismatch 66.66666666666666%)
x: array([[[ 0.,  0.,  0.],
    [ 0.,  0.,  0.],
    [ 0.,  0.,  0.],...
y: array([[[  0,   0,   0],
    [  0,   0,   0],
    [  0,   0,   0],...

not equal where =  (array([10, 10, 10, ..., 31, 31, 31]), array([21, 21, 22, ..., 31, 31, 31]), array([1, 2, 0, ..., 0, 1, 2]))
not equal lhs =  [128 128 128 ..., 255 255 255]
not equal rhs =  [ 0.  0.  0. ...,  0.  0.  0.]
</code></pre>

<p><em>Shape of the fake data (3, 32, 32, 3)</em> </p>

<blockquote>
  <p><strong>Tried Solutions:</strong></p>
</blockquote>

<ol>
<li>Tried different input</li>
<li>Tried RandomSuffleQueue instead of FIFOQueue </li>
<li><strong>Check if test on labels is pass or not. Yes! test on labels passed!</strong></li>
</ol>

<blockquote>
  <p><strong>My Question:</strong></p>
</blockquote>

<ol>
<li>What's going wrong?</li>
<li>Is there any problem in the first method that is used for reading TFRecord file?</li>
<li>Am I doing anything wrong in my test case?</li>
</ol>
",https://stackoverflow.com/questions/46933324/data-doesnt-match-to-original-data-after-converting-to-tfrecord,['tensorflow'],118,FALSE,0,1
Using MagicMock to test the inner components of a method,"<p>I'm new to using the mock library and unit testing in general.  I think I understand how the mock library works, but I think there is something wrong with my approach.</p>

<p>Lets say I have a class <code>Foo</code> that has a method <code>addFoo(bar1, bar2)</code> and <code>addFoo</code> calls other 'private' methods within foo, but can also raise exceptions at various parts in the code... i.e.</p>

<pre><code>class Foo:
    def __init__(self):
         # This creates lots of dependencies

    def _inner1(self, bar):
        if this_doesnt_work:
           return None
        return modified_bar1

    def _inner2(self, bar2):
        if this_doesnt_work:
           return None
        return modified_bar2

    def addFoo(bar1, bar2):
        if self._inner1(bar1) and self._inner2(bar2):
           #do something
        else:
           raise SomeException
</code></pre>

<p>When I unit test, what I currently do is mock out <code>Foo.__init__</code> in my unit test setup and set <code>return_value</code> to None.  This works and allows me to run tests against my methods in the class without all the external dependencies and just mock any class attributes with my mocked <code>Foo.__init__</code> instance. </p>

<p>After that is done if I wanted to unit test <code>addFoo</code> I would do the following (skipping a bunch of steps):</p>

<pre><code>@patch.object(Foo, '_inner2')
@patch.object(Foo, '_inner1')
def test_inner1_exception(self, mock_inner1, mock_inner2):
    mock_inner1.side_effect = Exception
    # then do some asserts to make sure it worked
</code></pre>

<p><strong>QUESTION</strong>
How do I test an exception in <code>addFoo</code> if the code looks like this:</p>

<pre><code>def addFoo(bar1, bar2):
    bars = self._getBars() #something that returns a list
    my_modified_bar_list = []
    for bar in bars:
        my_modified_bar_list.append(self._inner1(bar))

    if len(my_modified_bar_list) == 0:
        raise SomeException
</code></pre>

<p>In this instance how do I test <code>SomeException</code> when it is dependent upon the values produced by some array within my method?</p>
",https://stackoverflow.com/questions/44935867/using-magicmock-to-test-the-inner-components-of-a-method,"['python', 'python-2.7', 'unit-testing', 'mocking']",475,FALSE,0,1
Testing Field Injection VS Constructor Injection,"<p>I try to replace field injection by constuctor injection in my controller because it seems to be a best practice.
When I run the application, it works with both solution.</p>

<p>My issue is with the unit testing of my Controller.
I write the test class for the Controller where I use field injection.
It works fine.
Now I replace field injection by constuctor injection. The test fail.</p>

<p>Here is my initial Controller (with field injection) :</p>

<pre><code>@Controller
public class DashboardController {

    @Autowired
    private MyService myService;

    @RequestMapping(""/"")
    public String index(Model model) {
        MyPojo myPojo = myService.getMyPojo();
        model.addAttribute(""myPojo"", myPojo);
        return ""dashboard"";
    }

}
</code></pre>

<p>Now the new Controller (with constuctor injection) :</p>

<pre><code>@Controller
public class DashboardController {

    private final MyService myService;

    @Autowired
    public DashboardController(MyService myService) {
        this.myService = myService;
    }

    @RequestMapping(""/"")
    public String index(Model model) {
        MyPojo myPojo = myService.getMyPojo();
        model.addAttribute(""myPojo"", myPojo);
        return ""dashboard"";
    }

}
</code></pre>

<p>And the test class :</p>

<pre><code>@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {MyApplication.class})
@WebAppConfiguration
@TestPropertySource(locations = ""classpath:/application.properties"")
public class DashboardControllerUnitTests {

    @InjectMocks
    private DashboardController dashboardController;

    @Mock
    private MyService myService;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders
                .standaloneSetup(dashboardController)
                .build();
    }

    @Test
    public void getDashboard() throws Exception {
        doReturn(new MyPojo()).when(myService).getMyPojo();
        mockMvc.perform(get(""/""))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(model().attribute(""myPojo"", equalTo(new MyPojo()))); // The test fail here
        verify(myService).getMyPojo();
    }

}
</code></pre>

<p>If I run the test with the initial version of my Controller, it works fine.
But if I run the same test with the new version of the Controller (with constructor injection), myPojo is null and the test fail.</p>

<p>It seems like mockito doesn't mock the service if it is constructor injected.
Do you have any idea why I have the issue and how to solve it ?</p>
",https://stackoverflow.com/questions/47203169/testing-field-injection-vs-constructor-injection,"['java', 'unit-testing', 'spring-mvc', 'dependency-injection', 'mockito']",963,TRUE,0,1
Python coverage - skip or mock input method,"<h1>Context</h1>

<p>I have a python application that I'm unit testing. Half the application is working and I have a very high test accuracy.</p>

<p>The application requires one-time user input for installation purposes.</p>

<p>This means that, if you run the code, there has to be interaction with a user.</p>

<hr>

<h1>Problem</h1>

<p><a href=""https://coverage.readthedocs.io/en/coverage-4.4.2/"" rel=""nofollow noreferrer"">Coverage</a> is a Python plugin for coverage reports. I use coverage with this command:</p>

<pre><code>coverage run application.py
</code></pre>

<p>Coverage runs my application, goes through my tests, and delivers a coverage report.</p>

<p>The problem is that the command to run those tests, executes my application and I have to provide input. That's not that big of a deal, but I cannot do that on my CI server using Jenkins (or can I?).</p>

<hr>

<h1>Question</h1>

<p>I want to run the coverage tool without user input. In my tests, the <code>input</code> function is mocked out. Running all my tests without coverage works fine. How can I prevent coverage from requiring user input?</p>
",https://stackoverflow.com/questions/47237373/python-coverage-skip-or-mock-input-method,"['python', 'bash', 'unit-testing', 'jenkins', 'coverage.py']",911,TRUE,0,1
Java - JpaRepository SQL Error,"<p>I use hibernate for O/R mapping and further I use the JpaRepository for my DAOs.</p>

<p>I want to compare two java.util.date objects if they have the same day. Currently I'm using this query, which is not working:</p>

<pre><code>@Query(value = ""SELECT e FROM Event e WHERE day(e.startDate) = day(?1)"")
public Set&lt;Event&gt; findEventsByDate(Date date);
</code></pre>

<p>This was also recommended here:
<a href=""https://stackoverflow.com/questions/25680237/date-compare-in-hql-without-timestamp"">Date Compare in HQL without timestamp</a></p>

<p>Unfortunately I get the following error:</p>

<p><strong>org.springframework.dao.invaliddataaccessresourceusageexception: could not prepare statement</strong></p>

<p>and</p>

<p><strong>org.hsqldb.HsqlException: data type cast needed for parameter or null literal</strong></p>

<p>It seems like it has something to do with the parameter ""?1"" from the DAO method. Because if I try the following, it works like a charm:</p>

<pre><code>SELECT e FROM Event e WHERE day(e.startDate) = day(e.startDate)
</code></pre>

<p>(I use HSQLDB)</p>

<p><strong>UPDATE</strong></p>

<p>Here is the stacktrace:</p>

<pre><code>    org.springframework.dao.InvalidDataAccessResourceUsageException: could not prepare statement; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:261)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:491)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy118.findEventsByDate(Unknown Source)
    at *.service.impl.EventServiceImpl.findEventsByDate(EventServiceImpl.java:331)
    at *.service.impl.EventServiceImpl$$FastClassBySpringCGLIB$$f6beca54.invoke(&lt;generated&gt;)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:721)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:656)
    at *.service.impl.EventServiceImpl$$EnhancerBySpringCGLIB$$d66b254.findEventsByDate(&lt;generated&gt;)
    at *.EventServiceImplTest.findEventsByStartDate(EventServiceImplTest.java:347)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.hibernate.exception.SQLGrammarException: could not prepare statement
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:182)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:148)
    at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1929)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1898)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1876)
    at org.hibernate.loader.Loader.doQuery(Loader.java:919)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336)
    at org.hibernate.loader.Loader.doList(Loader.java:2617)
    at org.hibernate.loader.Loader.doList(Loader.java:2600)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2429)
    at org.hibernate.loader.Loader.list(Loader.java:2424)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:501)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:371)
    at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1326)
    at org.hibernate.internal.QueryImpl.list(QueryImpl.java:87)
    at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:606)
    at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:483)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution$CollectionExecution.doExecute(JpaQueryExecution.java:118)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:82)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:116)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:482)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:460)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    ... 48 more
Caused by: java.sql.SQLSyntaxErrorException: data type cast needed for parameter or null literal
    at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
    at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
    at org.hsqldb.jdbc.JDBCPreparedStatement.&lt;init&gt;(Unknown Source)
    at org.hsqldb.jdbc.JDBCConnection.prepareStatement(Unknown Source)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:146)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:172)
    ... 79 more
Caused by: org.hsqldb.HsqlException: data type cast needed for parameter or null literal
    at org.hsqldb.error.Error.error(Unknown Source)
    at org.hsqldb.error.Error.error(Unknown Source)
    at org.hsqldb.FunctionSQL.resolveTypes(Unknown Source)
    at org.hsqldb.FunctionCustom.resolveTypes(Unknown Source)
    at org.hsqldb.ExpressionLogical.resolveTypes(Unknown Source)
    at org.hsqldb.QuerySpecification.resolveExpressionTypes(Unknown Source)
    at org.hsqldb.QuerySpecification.resolveTypesPartOne(Unknown Source)
    at org.hsqldb.QueryExpression.resolve(Unknown Source)
    at org.hsqldb.ParserDQL.compileCursorSpecification(Unknown Source)
    at org.hsqldb.ParserCommand.compilePart(Unknown Source)
    at org.hsqldb.ParserCommand.compileStatement(Unknown Source)
    at org.hsqldb.Session.compileStatement(Unknown Source)
    at org.hsqldb.StatementManager.compile(Unknown Source)
    at org.hsqldb.Session.execute(Unknown Source)
    ... 83 more
</code></pre>

<p><strong>UPDATE 2</strong></p>

<p>I don't know why but it works perfectly when I use a mysql database. But nevertheless it would be great if someone could explain why this does not work with hsqldb because I use this in-memory-database for unit testing and I want to keep that updated and as good as possible.</p>
",https://stackoverflow.com/questions/43135533/java-jparepository-sql-error,"['java', 'spring', 'hibernate', 'spring-data-jpa']",908,FALSE,0,1
Java: ArrayList says index 0 doesn&#39;t exist unless I include a String in the parent loop,"<p>I am in class, and am trying to complete a chapter exercise, but am having some troubling difficulties.</p>
<p>The assignment requests:</p>
<blockquote>
<p>Modify the existing <code>ArrayList</code>'s contents, by erasing 200, then inserting 100 and 102 in the shown locations. Use <code>ArrayList</code>'s <code>remove()</code> and <code>add()</code> only. Sample output of below program:</p>
<pre><code>100 101 102 103
</code></pre>
</blockquote>
<p>Here is the program it provides, with my part included:</p>
<pre><code>import java.util.ArrayList;

public class ArrayListADT {

 public static void printArray(ArrayList&lt;Integer&gt; numsList, int numOfElem) {
   int i = 0;

   for (i = 0; i &lt; numOfElem; ++i) {
      System.out.print(numsList.get(i));
      System.out.print(&quot; &quot;);
   }

   System.out.println(&quot;&quot;);
 }

 public static void main (String [] args) {
   ArrayList&lt;Integer&gt; numsList = new ArrayList&lt;Integer&gt;();
   int numOfElem = 4;

   numsList.add(new Integer(101));
   numsList.add(new Integer(200));
   numsList.add(new Integer(103));

// I can only access code below this point---------------------------
   int j = 0;
  
   try {
      for (j = 0; j &lt; numOfElem; j++) {
         if (numsList.get(j).equals(200)) {
         numsList.remove(j);

         numsList.add(1, new Integer(102));
         numsList.add(0, new Integer(100));
         }
      
         printArray(numsList, numOfElem);
      }  
   } catch (Exception e) {
      // Catch whatever exception our code is producing
      // Print the error and see what happens.

      System.out.println(e);
   }

// I can only access code above this point---------------------------

    printArray(numsList, numOfElem);

    return;
  }
}
</code></pre>
<p>When I run this code, the program gives me the right input and passes, but gives me an exception:</p>
<pre><code>100 101 102 103

Runtime error (commonly due to an invalid array/vector access, divide by 0, etc.).
</code></pre>
<p>I've used the good ol power of unit testing to discover that the culprit is:</p>
<pre><code>numsList.add(0, new Integer(100));
</code></pre>
<p>I don't know why! In case it was a syntax error on my part, I tried to switch its position with the other <code>add()</code> in the statement block, but it still only reacted to my attempt to <code>add()</code> to 0. What did I do wrong? I've tried fixing it with a similar problem's solution and changed <code>++j</code> to <code>j++</code>, but got no solution from this.</p>
<p>OUTPUT AFTER RUNNING UPDATE 1:</p>
<pre><code>✖   Runtime error (commonly due to an invalid array/vector access, divide by 0, etc.).
</code></pre>
<p>It doesn't seem to like the try/catch.</p>
",https://stackoverflow.com/questions/43060951/java-arraylist-says-index-0-doesnt-exist-unless-i-include-a-string-in-the-pare,"['java', 'arraylist', 'methods', 'runtime-error']",655,TRUE,0,2
How do you test Vuejs Components when using Vuex,"<p>I am writing unit tests for my vuejs components in a larger application.  My application state is all in the vuex store, so almost all of my components pull data from vuex.</p>

<p>I can't find a working example for writing unit test for this. I have found </p>

<p><a href=""https://forum-archive.vuejs.org/topic/3823/how-to-test-a-component-that-contains-vuex-getters/4"" rel=""noreferrer"">Where Evan You says:</a></p>

<blockquote>
  <p>When unit testing a component in isolation, you can inject a mocked store directly into the component using the store option.</p>
</blockquote>

<p>But I can't find a good example of how to test these components.  I have tried a bunch of ways. Below is the only way I have seen people do it. <a href=""https://stackoverflow.com/questions/43151339/how-do-you-get-the-this-variable-defined-in-a-vuejs-component-unit-test"">stackoverflow question and answer</a></p>

<p>Basically it looks like the </p>

<p>test.vue:</p>

<pre><code> &lt;template&gt;
    &lt;div&gt;test&lt;div&gt;
 &lt;/template&gt;
 &lt;script&gt;
 &lt;script&gt;
    export default {
        name: 'test',
        computed: {
            name(){
                return this.$store.state.test;
            }
        }
    }
  &lt;/script&gt;
</code></pre>

<p>test.spec.js</p>

<pre><code>import ...

const store = new Vuex.Store({
  state: {
    test: 3
  }
});
describe('test.vue', () =&gt; {

  it('should get test from store', () =&gt; {

    const parent = new Vue({
      template: '&lt;div&gt;&lt;test ref=""test""&gt;&lt;/test&gt;&lt;/div&gt;',
      components: { test },
      store: store
    }).$mount();

    expect(parent.$refs.test.name).toBe(3);
  });
}
</code></pre>

<p>Note the ""ref"" this example doesn't work without it.</p>

<p>Is this really the right way to do this?  It seems like it will get messy fast, because it requires adding the props into the template as a string.</p>

<p>Evan's quote seems to imply that the store can be added directly to the child component (ie not the parent like the example). </p>

<p>How do you do that?  </p>
",https://stackoverflow.com/questions/43495306/how-do-you-test-vuejs-components-when-using-vuex,"['unit-testing', 'vue.js', 'components', 'vuex']",2091,TRUE,8,1
(Node.js/mocha/chai) Sending parameters in request object in a HTTP POST,"<p>I'm trying to test someone else's POST route (using mocha/chai/sinon) and I'm running into a wall.  Here's what works so far:  Most of the information grabbed in the post route is retrieved from req.body as illustrated in this snippet. </p>

<pre><code>  var participants = JSON.parse(req.body.participantList);
  var scenarioId = req.body.scenarioId;
</code></pre>

<p>I'm able to send up these variables using the test code below because .send() places parameters into the body.</p>

<pre><code>chai.request(server)
  .post('/viewer/add-exercise-participants')
  .send({""scenarioId"": 9999, ""user"": {""id"": 1234}, 'participantList': '['
      + '{""user_id"": 1111, ""role_id"": [4444]},'
      + '{""user_id"": 2222, ""role_id"": [1111]},'
      + '{""user_id"": 4444, ""role_id"": [3333, 4444]}'
    + ']'
  })
  .end(function(err, res){
    console.log(res.body);
    done();
  });
</code></pre>

<p>So just to be clear, what I have above is working so far.  Here is where I run into issue.   Later down within the same route, they want a req.user.id which is throwing me off.  Since req.user.id is not inside of body I don't know how to send that with my HTTP POST request.  </p>

<pre><code>var requserid = req.user.id;
</code></pre>

<p>How do I set this req.user.id variable when I call make a request to this route? The project is in node.js and I'm testing unit testing using the mocha/chai/sinon packages.</p>

<p>Here is an example of how the route is called somewhere else in the project.  </p>

<pre><code>  $.post('/viewer/add-exercise-participants', {
  scenarioId: scenarioId,
  participantList: JSON.stringify(selected_users)
}).done(function(data) {
  noty({
    layout: 'topCenter',
    text: data,
    theme: 'relax',
    type: 'alert',
    timeout: 3000,
    animation: {
      open: {
        height: 'toggle'
      },
      close: {
        height: 'toggle'
      },
      easing: 'swing',
      speed: 500
    }
  });
});
</code></pre>
",https://stackoverflow.com/questions/43948075/node-js-mocha-chai-sending-parameters-in-request-object-in-a-http-post,"['node.js', 'http', 'express', 'mocha.js', 'sinon']",2585,FALSE,0,0
Service Fabric Unit Tesitng a Reliable Actor Method which reads config info from Settings.xml and App.Config,"<p>I am currently working on a Service Fabric project, where in one of our reliable actors we make calls to a SOAP service. For these calls we read a couple of parameters from the Actor's Settings.xml and also - the SOAP endpoint address and binding information from the App.config file (actually the latter is done implicitly by the generated service proxy class for the SOAP service).</p>

<p>Now I am trying to get the unit testing work with xUnit + ServiceFabric.Mocks. To test an Actor specific method I go through:
1) Creating a ""MockCodePackageActivationContext""
2) Creating a ""StatefulServiceContext"" using the instance of the activation context in step 1.
3) Instantiate the Actor with the code below</p>

<pre><code>MyActor target = new MyActor(
                new ActorService(
                    context: serviceContext,
                    actorTypeInfo: ActorTypeInformation.Get(typeof(MyActor)),
                    stateManagerFactory: (actorBase, stateProvider) =&gt; new MockActorStateManager()
                ),
                new ActorId(Guid.NewGuid())
            );
</code></pre>

<p>4) I call target.MyMethod() which breaks due to inability to read config info either from the Settings.xml or the App.config file </p>

<p>I made a test where target.MyMethod_Test() does not read anything from config and it was successful.</p>

<p>Anyone who stumbled upon similar thing? How did you solve it?</p>
",https://stackoverflow.com/questions/41468995/service-fabric-unit-tesitng-a-reliable-actor-method-which-reads-config-info-from,"['unit-testing', 'azure-service-fabric', 'xunit']",268,TRUE,0,1
Telrik JustMock integration with VSTS build hosted agent,"<p>I am using Telrik JustMock to mock in the unit testing. Locally it works well but while I try to integrate it with VSTS builds based on Asp.net build template, it ends with errors.
The stacktrace for the errors are as following:</p>

<pre><code> Failed   ValidateNodeRegisteredReturnsTrue
2017-08-04T08:24:12.0452600Z Error Message:
2017-08-04T08:24:12.0452600Z    Assert.IsFalse failed. 
2017-08-04T08:24:12.0452600Z Stack Trace:
2017-08-04T08:24:12.0452600Z    at 

 xxx.UnitTests.TemplateManagerUnitTests.ValidateNodeRegisteredReturnsTrue() in d:\a\1\s\Dev\TSys Project\8. Unit 
</code></pre>

<p>Tests\XXX.WebMVC.Tests\UnitTests\ManagerUnitTests.cs:line 36</p>

<pre><code>2017-08-04T08:24:12.0462606Z 
2017-08-04T08:24:12.0462606Z Failed   ValidateExtractPackageOnLocalServer
2017-08-04T08:24:12.0462606Z Error Message:
2017-08-04T08:24:12.0462606Z    Test method 
 xxx.UnitTests.ManagerUnitTests.ValidateExtractPackageOnLocalServer threw exception: 

2017-08-04T08:24:12.0462606Z Telerik.JustMock.Core.ElevatedMockingException: Cannot mock 'TemplateCreationService.TemplateUtility'. The profiler must be enabled to mock, arrange or execute the specified target.
2017-08-04T08:24:12.0462606Z Detected active third-party profilers:
2017-08-04T08:24:12.0462606Z * Visual Studio 2015 Code Coverage/IntelliTrace (from process environment)
2017-08-04T08:24:12.0462606Z Disable the profilers or link them from the JustMock configuration utility. Restart the test runner and, if necessary, Visual Studio after linking.
2017-08-04T08:24:12.0462606Z Stack Trace:
2017-08-04T08:24:12.0462606Z     at Telerik.JustMock.Core.ProfilerInterceptor.ThrowElevatedMockingException(MemberInfo member)
2017-08-04T08:24:12.0462606Z    at Telerik.JustMock.Core.MocksRepository.InterceptStatics(Type type, IEnumerable`1 mixins, IEnumerable`1 supplementaryBehaviors, IEnumerable`1 fallbackBehaviors, Boolean mockStaticConstructor)
2017-08-04T08:24:12.0462606Z    at Telerik.JustMock.MockBuilder.InterceptStatics(MocksRepository repository, Type type, Nullable`1 behavior, Boolean mockStaticConstructor)
2017-08-04T08:24:12.0462606Z    at Telerik.JustMock.Mock.&lt;&gt;c__DisplayClass34_0.&lt;SetupStatic&gt;b__0()
2017-08-04T08:24:12.0462606Z    at Telerik.JustMock.Core.ProfilerInterceptor.GuardInternal(Action guardedAction)
2017-08-04T08:24:12.0462606Z    at Telerik.JustMock.Mock.SetupStatic(Type staticType)
2017-08-04T08:24:12.0462606Z    at xxx.UnitTests.ManagerUnitTests.ValidateExtractPackageOnLocalServer() in d:\a\1\s\Dev\TSys Project\8. Unit Tests\xxx.WebMVC.Tests\ServiceUnitTests\ManagerUnitTests.cs:line 44

2017-08-04T08:24:12.0462606Z 
2017-08-04T08:24:12.0462606Z Error Message:
2017-08-04T08:24:12.0462606Z    Test method 
xxx.UnitTests.ManagerUnitTests.ShouldAssertCustomValueForDateTimeNow threw exception: 
2017-08-04T08:24:12.0462606Z Telerik.JustMock.Core.ElevatedMockingException: Cannot mock 'System.DateTime'. The profiler must be enabled to mock, arrange or execute the specified target.
2017-08-04T08:24:12.0462606Z Detected active third-party profilers:
2017-08-04T08:24:12.0462606Z * Visual Studio 2015 Code Coverage/IntelliTrace (from process environment)
2017-08-04T08:24:12.0462606Z Disable the profilers or link them from the JustMock configuration utility. Restart the test runner and, if necessary, Visual Studio after linking.
2017-08-04T08:24:12.0462606Z Stack Trace:
2017-08-04T08:24:12.0462606Z     at 
</code></pre>

<p>Telerik.JustMock.Core.ProfilerInterceptor.ThrowElevatedMockingException(MemberInfo member)
    2017-08-04T08:24:12.0462606Z    at Telerik.JustMock.Core.MocksRepository.InterceptStatics(Type type, IEnumerable<code>1 mixins, IEnumerable</code>1 supplementaryBehaviors, IEnumerable<code>1 fallbackBehaviors, Boolean mockStaticConstructor)
    2017-08-04T08:24:12.0462606Z    at Telerik.JustMock.MockBuilder.InterceptStatics(MocksRepository repository, Type type, Nullable</code>1 behavior, Boolean mockStaticConstructor)
    2017-08-04T08:24:12.0462606Z    at Telerik.JustMock.Core.MocksRepository.ConvertExpressionToCallPattern(Expression expr, CallPattern callPattern)
    2017-08-04T08:24:12.0462606Z    at Telerik.JustMock.Core.MocksRepository.Arrange[TMethodMock](Expression expr, Func<code>1 methodMockFactory)
    2017-08-04T08:24:12.0462606Z    at Telerik.JustMock.Mock.&lt;&gt;c__DisplayClass1_0</code>1.b__0()
    2017-08-04T08:24:12.0462606Z    at Telerik.JustMock.Core.ProfilerInterceptor.GuardInternal[T](Func<code>1 guardedAction)
     2017-08-04T08:24:12.0462606Z    at Telerik.JustMock.Mock.Arrange[TResult](Expression</code>1 expression)
    2017-08-04T08:24:12.0462606Z    at </p>

<pre><code> xxx.UnitTests.ManagerUnitTests.ShouldAssertCustomValueForDateTimeNow() in d:\a\1\s\Dev\TSys Project\8. Unit Tests\xxx.WebMVC.Tests\ServiceUnitTests\ManagerUnitTests.cs:line 57

 2017-08-04T08:24:12.0472600Z Failed   ShouldAssertCustomValueForDateTimeNow
</code></pre>

<p>Can anyone share if have the knowledge for Telrik JustMock integration with VSTS asp.net build template.</p>

<p>I was able to findout the link for running Telrik JustMock using XAML based build template here:
<a href=""http://docs.telerik.com/help/justmock/integration-tfs-2013.html"" rel=""nofollow noreferrer"">http://docs.telerik.com/help/justmock/integration-tfs-2013.html</a></p>

<p>Also I am using Test Run task of Asp.Net build template.</p>
",https://stackoverflow.com/questions/45505242/telrik-justmock-integration-with-vsts-build-hosted-agent,"['asp.net', 'unit-testing', 'telerik', 'azure-pipelines', 'justmock']",715,FALSE,0,1
How do I pass SQLite Cursor from MVP Model to View without breaking Presenter?,"<p>I have an app implementation using the MVP design, and I want to use a SQLlite database to source data data to the UI <code>View</code>. I don't want/need to use a <code>ContentProvider</code> as the data is only required by my app alone. </p>

<p>I know that the <code>View</code> should be 'dumb' and any 'business' logic should go in the <code>Presenter</code> and the <code>Model</code>. Yet the <code>Presenter</code> should contain no Android code in order to allow for standalone unit testing. </p>

<p>So how do I perform the transportation of SQLite data from the <code>Model</code> back to the <code>Presenter</code> and then the <code>View</code> if I can't use a <code>cursor</code> in the <code>Presenter</code>? </p>

<p>I can use a callback but is the 'correct' way to create my own data structure, load the data into that and then pass a list in the callback? </p>

<p>I'd like to stay true to the <code>MVP</code> design.
I've Googled this to death and whilst there's plenty of stuff on handling the <code>Context</code> in the <code>Presenter</code> there's not a lot about using other Android data structures. </p>
",https://stackoverflow.com/questions/46827403/how-do-i-pass-sqlite-cursor-from-mvp-model-to-view-without-breaking-presenter,"['android', 'android-sqlite', 'mvp', 'android-cursor', 'android-mvp']",922,FALSE,0,1
TypeError: Cannot read property &#39;unmask&#39; of undefined at Receiver.unmask,"<p>Launch karma in chrome browser and abru[tly close itself with an Error while running karma for unit testing in angular 2 : </p>

<blockquote>
  <p>19 04 2017 19:14:27.848:ERROR [karma]: TypeError: Cannot read property 'unmask' of undefined<br>
      at Receiver.unmask (C:\Projects\Git Repo\TDP\switchmanager\src\SwitchDesigner\node_modules\engine.io\node_modules\ws\lib\Receiver.js:306:46)<br>
      at Receiver.finish (C:\Projects\Git Repo\TDP\switchmanager\src\SwitchDesigner\node_modules\engine.io\node_modules\ws\lib\Receiver.js:505:25)<br>
      at Receiver.expectHandler (C:\Projects\Git Repo\TDP\switchmanager\src\SwitchDesigner\node_modules\engine.io\node_modules\ws\lib\Receiver.js:493:33)<br>
      at Receiver.add (C:\Projects\Git Repo\TDP\switchmanager\src\SwitchDesigner\node_modules\engine.io\node_modules\ws\lib\Receiver.js:103:24)
      at Socket.realHandler (C:\Projects\Git Repo\TDP\switchmanager\src\SwitchDesigner\node_modules\engine.io\node_modules\ws\lib\WebSocket.js:825:20)<br>
      at emitOne (events.js:96:13)<br>
      at Socket.emit (events.js:188:7)<br>
      at readableAddChunk (_stream_readable.js:176:18)<br>
      at Socket.Readable.push (_stream_readable.js:134:10)<br>
      at TCP.onread (net.js:548:20)<br></p>
</blockquote>

<p>Any help?</p>
",https://stackoverflow.com/questions/43501766/typeerror-cannot-read-property-unmask-of-undefined-at-receiver-unmask,"['angular', 'karma-runner', 'karma-jasmine', 'angular-cli']",1768,FALSE,0,1
How to get correct length of a tuple whose constituent elements include list objects?,"<p><strong>Question: How can I return the expected length of a tuple when its constituent element is a list object?</strong></p>

<p>I wrote a very basic unit testing class in Python to begin learning TDD. I want to allow my class to dynamically assign the test case inputs (stored as tuples) depending on how many elements that tuple has. However, when I check the length of a tuple whose only element is a list object the length returned is that of the list object - not the tuple.</p>

<p>Expected functionality: </p>

<pre><code>a = (['a', 'b', 'c'])
len(a) # 1 - one element in the tuple
</code></pre>

<p>Actual functionality:</p>

<pre><code>a = (['a', 'b', 'c'])
len(a) # 3 - which appears to be returning len(a[0]) 
</code></pre>

<p>Now in the case of a tuple which has <strong>multiple</strong> elements (including list objects) it does return the expected tuple length. So my issue appears to only crop up when the <strong>only element</strong> in the tuple is a list object. </p>

<p>Here is the simple unit tester class I wrote. Right now I am getting around this issue by using an <strong>else clause on line 13</strong>. This doesn't seem like the correct way to handle this. </p>

<pre><code>class Unit_Tester:
  def __init__(self, function, tests):
    self.function_to_test = function
    self.test_list = tests

  def unit_test(self, function_to_test, test_input, expected_output):
      try:
          number_of_inputs = len(test_input)
          print(number_of_inputs)
          if number_of_inputs == 1: function_output = function_to_test(test_input)
          elif number_of_inputs == 2: function_output = function_to_test(test_input[0], test_input[1])
          elif number_of_inputs == 3: function_output = function_to_test(test_input[0], test_input[1], test_input[2])
          else: function_output = function_to_test(test_input)
      except Exception as error:
          print(""Error occurred with test input: [{0}] value: {1}\nError Message: {2}\nCorrect the error and try again.\n""
          .format(type(test_input), test_input, error))
      else:
        try:
            assert function_output == expected_output
            print(self.unit_test_response(True, test_input, function_output, expected_output))
        except AssertionError:
            print(self.unit_test_response(False, test_input, function_output, expected_output))

  def unit_test_response(self, correct, test_input, function_output, expected_output): 
      score = ""Test Passed"" if correct else ""Test Failed"" 
      return ""{0}\nInput: {1}\nExpected Output: {2}\nFunction Output: {3}\n"".format(score, test_input, expected_output, function_output)

  def run_unit_tests(self, function_to_test, test_list):  
      for test_tuple in test_list:
          test_input, expected_output = test_tuple
          self.unit_test(function_to_test, test_input, expected_output)

  def run(self):
    self.run_unit_tests(self.function_to_test, self.test_list)
</code></pre>
",https://stackoverflow.com/questions/47024260/how-to-get-correct-length-of-a-tuple-whose-constituent-elements-include-list-obj,"['python-3.x', 'tuples']",19,FALSE,0,0
trouble with makefile C++ Linux,"<p>I am trying to set up a template folder for future projects.  I am going to incorporate google tests for my unit testing.  The issue I'm having is my makefile is not doing what I expect.  any help is greatly appreciated!</p>

<p>Here is my project structure:</p>

<p><code>project_root
    Makefile
    /test &lt;-- contains google test files
    /src  &lt;-- my cpp files</code></p>

<p>Here is my Makefile:</p>

<pre><code># Google Test location
GTEST_DIR = test

# Where to find user code.
USER_DIR = src

# Flags passed to the preprocessor.
CPPFLAGS += -isystem $(GTEST_DIR)/include

# Flags passed to the C++ compiler.
CXXFLAGS += -g -Wall -Wextra -pthread

# All tests produced by this Makefile.  Remember to add new tests you
# created to the list.
TESTS = sample1_unittest

.PHONY : all
all: $(EXE)

clean :
    rm -f $(TESTS) gtest.a gtest_main.a *.o

# All Google Test headers.  Usually you shouldn't change this
# definition.
GTEST_HEADERS = $(GTEST_DIR)/include/gtest/*.h \
                $(GTEST_DIR)/include/gtest/internal/*.h

# Builds gtest.a and gtest_main.a.
GTEST_SRCS_ = $(GTEST_DIR)/src/*.cc $(GTEST_DIR)/src/*.h $(GTEST_HEADERS)

gtest-all.o : $(GTEST_SRCS_)
    $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \
            $(GTEST_DIR)/src/gtest-all.cc

gtest_main.o : $(GTEST_SRCS_)
    $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \
            $(GTEST_DIR)/src/gtest_main.cc

gtest.a : gtest-all.o
    $(AR) $(ARFLAGS) $@ $^

gtest_main.a : gtest-all.o gtest_main.o
    $(AR) $(ARFLAGS) $@ $^

# Builds a sample test.  A test should link with either gtest.a or
# gtest_main.a, depending on whether it defines its own main()
# function.

### these next few lines would do the job, but i'm trying to automate
### things a bit so they are commented out

#sample1.o : $(USER_DIR)/sample1.cc $(USER_DIR)/sample1.h $(GTEST_HEADERS)
#   $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample1.cc
#
#sample1_unittest.o : $(USER_DIR)/sample1_unittest.cc \
#                     $(USER_DIR)/sample1.h $(GTEST_HEADERS)
#   $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample1_unittest.cc
#
#sample1_unittest : sample1.o sample1_unittest.o gtest_main.a
#   $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@


# here is where my trouble begins:
SRC = $(USER_DIR)/sample1.cc $(USER_DIR)/sample1_unittest.cc
OBJ=$(SRC:.cc=.o)
EXE=go

%.o : %.cc $(GTEST_HEADERS)
    $(CXX) $(CPPFLAGS) $(CXXFLAGS) -o $@ -c $&lt;


$(EXE): $(OBJ) gtest_main.a
    $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $&lt; -o $@
</code></pre>

<p>could you review the section under the comment ""<code># here is where my trouble begins</code>""</p>

<p>When I run <code>$ make</code> i get the following error:</p>

<blockquote>
  <p>make: Nothing to be done for 'all'.</p>
</blockquote>

<p>I've been using a similar makefile for quite a while, but now that I've addapted it for unittesting and moved the src files into their own folder it has broken.</p>

<p>I will be using this for all future builds so I'd really like to get this setup well now.</p>

<p>Thank you in advance for any assistance you can provide.</p>

<p><strong>Thank you for the fix.</strong></p>

<p>I moved the the following 3 lines above .phony : all</p>

<pre><code>SRC = $(USER_DIR)/sample1.cc $(USER_DIR)/sample1_unittest.cc
OBJ=$(SRC:.cc=.o)
EXE=go
</code></pre>

<p>I also had an error at the end, the vary last line should have been:</p>

<pre><code>$(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@
</code></pre>
",https://stackoverflow.com/questions/45405775/trouble-with-makefile-c-linux,"['c++', 'linux', 'makefile', 'gnu-make']",60,TRUE,0,1
How to prevent pushing &quot;stupid test code&quot; to master with Unit Tests?,"<p>Currently my app does not have any type of Test Driven Development or Behaviour Driven Development. I didn't prioritise beforehand and I would like to get some information about where to go from here. </p>

<p>My app is currently a: </p>

<ul>
<li>Ruby </li>
<li>Rails</li>
<li><code>html.erb</code> views   </li>
<li>PSQL</li>
</ul>

<p>For now, the primary concern is the front end of things. For example, when I am building up views, I will add things like </p>

<pre><code>.some_div_container { 
  background: red;
  border 1px dashed green;
}
</code></pre>

<p>but I will forget to take it out. I guess I can specifically test to make sure a div does not have a red background, but... what if I do something like orange, blue, etc...</p>

<p>Also for things like debuggers, binding.prys and console.log. Is there a test case for when I have something like </p>

<pre><code>&lt;button type=""button"" onclick=""doStuff""&gt;Kanye West&lt;/button&gt;

function doStuff() {
  console.log(""I am the number one most impactful artist of our generation!"")
}
</code></pre>

<p>I guess you can kind of get the idea of how stupid this can look when it's on master, and what I can do prevent this and/or how I can go about Unit Testing. </p>
",https://stackoverflow.com/questions/44244268/how-to-prevent-pushing-stupid-test-code-to-master-with-unit-tests,"['ruby-on-rails', 'unit-testing']",24,FALSE,0,0
Possible to run mocha test with chai in console and browser within a single test file?,"<p>I have set-up a little test environment for a project. It should use <code>mocha</code> and <code>chai</code> for unit testing. I've set up a <code>html</code> file as test runner:</p>

<pre><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Mocha Tests&lt;/title&gt;
    &lt;link rel=""stylesheet"" href=""node_modules/mocha/mocha.css""&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;div id=""mocha""&gt;&lt;/div&gt;
    &lt;script src=""node_modules/mocha/mocha.js""&gt;&lt;/script&gt;
    &lt;script src=""node_modules/chai/chai.js""&gt;&lt;/script&gt;
    &lt;script&gt;mocha.setup('bdd')&lt;/script&gt;
    &lt;script src=""test/chaiTest.js""&gt;&lt;/script&gt;
    &lt;script&gt;mocha.run();&lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>The <code>chaiTest.js</code> file continas this simple test:</p>

<pre><code>let assert = chai.assert;

describe('simple test', () =&gt; {
    it('should be equal', () =&gt; {
        assert.equal(1, 1);
    });
});
</code></pre>

<p>When I now call the test runner in my browser, the results are shown correctly. It works fine. But when I run <code>mocha</code> on console, it tells me that <code>chai is not defined</code>.</p>

<p>So to get this working in console, I just add a <code>require</code> of <code>chai</code> in the fist line of the test file.</p>

<pre><code>let chai = require('chai');
</code></pre>

<p>Now the test runs fine in console, but when I execute tests in the browser, it tells me that <code>require</code> is <code>undefined</code>.</p>

<p>I know, these errors totally makes sense here! They are undefined. But is there a way to write tests with <code>mocha</code> and <code>chai</code> and let them execute in browser and console?</p>

<p>I know I could create two test files, for browser and console. But that would be hard to maintain. So I would like to write a single test file, executing correctly in both environments ...</p>
",https://stackoverflow.com/questions/42857544/possible-to-run-mocha-test-with-chai-in-console-and-browser-within-a-single-test,"['javascript', 'unit-testing', 'mocha.js', 'chai', 'test-runner']",998,TRUE,0,1
Cannot access a disposed object when calling callback method,"<p>I've a Duplex TCP IP WCF service. I'm currently unit-testing it.</p>

<p>In everyone of my test, I setup a new server, create a new ChannelFactory, create the InstanceContext and do the call.</p>

<p>Then I trigger the event(it's a Mock on the server side), and the server give me this exception when it tries to reach the client:</p>

<blockquote>
  <p>Exception thrown: 'System.ObjectDisposedException' in mscorlib.dll
  Additional information: Cannot access a disposed object.</p>
</blockquote>

<p>Important point, this happens ONLY when I run all the tests in a row(sequentially executed but in the same execution).</p>

<p>There is nothing special about my service:</p>

<pre><code>[ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof(IMyServiceCallback))]
public interface IMyService{
    [OperationContract]
    void SomeVariousMethods();
} 

[ServiceContract]
public interface IMyServiceCallback
{
    [OperationContract]
    void HandleMessageFromServer(String message);
}


[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class MyService : IMyService{
    public MyService(ISomeServerComponent component){
        component.OnMessage += OnMessageReceived;
    }

    public void SomeVariousMethods(){
        //...
    }

    private void OnMessageReceived(object sender, EventArgs&lt;String&gt; e){
        IMyServiceCallback callback = OperationContext.Current.GetCallbackChannel&lt;IMyServiceCallback&gt;();
        callBack.HandleMessageFromServer(e.Data);//Crash here
    }
}
</code></pre>

<p>And here is how I'm currently UnitTesting it(not exactly, I've a lot of this that has been extracted in some helpers:</p>

<pre><code>[TestFixture]
public class MyServiceTest:IMyServiceCallback{

    private Mock&lt;ISomeServerComponent&gt; _mock;

    [OneTimeSetUp]
    public void Setup(){
        //... Creating a mock for the ISomeServerComponent that the MyService receives
    }

    [Test]
    public void TestSomeVariousMethods(){
        string serviceName = nameof(TestSomeVariousMethods);
        using(ServiceHost host = CreateServer(_mock.Object,serviceName)){
            using (IMyService service = CreateClient(serviceName, this)){
                service.SomeVariousMethods();
            }
        }
    }

    [Test]
    public void TestCallback(){
        string serviceName = nameof(TestSomeVariousMethods);
        using(ServiceHost host = CreateServer(_mock.Object,serviceName)){
            using (IMyService service = CreateClient(serviceName, this)){
                _mock.TriggerCallBack();
                //Assert-that-the-flag-has-been-set
            }
        }
    }

    public void HandleMessageFromServer(String msg){
        //Flag that this method has been called
    }




    private ServiceHost CreateServer(ISomeServerComponent mock, string serviceName){
        UnityServiceHost serviceHost = new UnityServiceHost(m_container);//This extends ServiceHost to be able to inject some objects to my services
        NetTcpBinding binding = new NetTcpBinding(SecurityMode.None);
        binding.ReliableSession.Enabled = true;
        binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;
        binding.MaxBufferPoolSize = Int64.MaxValue;
        binding.MaxBufferSize = Int32.MaxValue;
        binding.MaxReceivedMessageSize = Int32.MaxValue;

        Uri uri = new Uri(String.Format(""net.tcp://{0}:{1}/{2}"", IPAddress.Any, 9999, serviceName));

        ServiceEndpoint serviceEndpoint = new ServiceEndpoint(ContractDescription.GetContract(typeof(IMyService)), binding, uri);
        serviceEndpoint.EndpointBehaviors.Add(new ProtoEndpointBehavior());

        serviceHost.AddServiceEndpoint(serviceEndpoint);
        return serviceHost;
    }

    private IMyService CreateClient(string serviceName, IMyServiceCallback callback){
        UnityServiceHost serviceHost = new UnityServiceHost(m_container);//This extends ServiceHost to be able to inject some objects to my services
        NetTcpBinding binding = new NetTcpBinding(SecurityMode.None);
        binding.ReliableSession.Enabled = true;
        binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;
        binding.MaxBufferPoolSize = Int64.MaxValue;
        binding.MaxBufferSize = Int32.MaxValue;
        binding.MaxReceivedMessageSize = Int32.MaxValue;

        Uri uri = new Uri(String.Format(""net.tcp://{0}:{1}/{2}"", IPAddress.Loopback, 9999, serviceName));


        InstanceContext context = new InstanceContext(callBack);
        DuplexChannelFactory channelFactory = new DuplexChannelFactory&lt;T&gt;(context, binding, new EndpointAddress(uri));
        return channelFactory.CreateChannel()
    }
}
</code></pre>

<p>Funny part is that all of this works when I'm ONLY running <code>TestCallback</code> test, but if I run all the test of the class, it fails, like if the second time, the <code>InstanceContext</code> was not creating properly the callback.</p>

<p>Any idea how to avoid this?</p>
",https://stackoverflow.com/questions/45350331/cannot-access-a-disposed-object-when-calling-callback-method,"['c#', 'wcf', 'duplex']",995,TRUE,0,1
Testing class that extends abstract class,"<p>I need to write a test for a class that extends an abstract class. Problem starts when I need to test a method that has <code>super</code> reference. So the code looks something like this:</p>

<pre><code>public abstract class AbstractClass{
    public String someMethod();
}

public class MyClass extends AbstractClass {
    methodToTest(){
        //somecode
        super.someMethod();
    }
}
</code></pre>

<p>Any idea how should I get around it?</p>

<p>EDIT:
I'm sorry, I am still new to unit testing and just a moment ago figured out why exactly this is not working as I would like to. MyClass in the example above actually contains a initialization block that sets some fields declared in AbstractClass that are used by someMethod so <code>new AbstractClass.someMethod()</code> didn't give me the same results as <code>super.someMethod</code>. And, as I cannot initialize the AbstractClass it would be impossible to get desired results. I figured that I would need to mock it somehow but as I said I am new to this and have no idea how to do that</p>

<pre><code>public abstract class AbstractClass{
    String fieldA;
    public String someMethod(){
        //does something with fieldA
    }
} 

public class MyClass extends AbstractClass {
    {
        setFieldA(""something"");
    }
    methodToTest(){
        //some code
        super.someMethod();
        //returns some string based on the fieldA value
   }
}
</code></pre>

<p><strong>UPDATE</strong> Here is updated version of my code. Please help me with writing test for that. I would probably be able to get it from there:</p>

<pre><code>public abstract class AbstractClass{
    String fieldA;
    public String someMethod(){
        fieldA = ""String"" + fieldA;
    }
} 

public class MyClass extends AbstractClass {
    {
        setFieldA(""Another String"");
    }
    methodToTest(){
        fieldA = fieldA + ""Yet Another String"";
        super.someMethod();
        return fieldA;
   }
}
</code></pre>
",https://stackoverflow.com/questions/44781026/testing-class-that-extends-abstract-class,"['testing', 'junit', 'abstract-class']",706,FALSE,0,1
How to design and unit test a VBA class module for adding formatted tables to document,"<p>The motivation for this question is to obtain a concrete example of what good, unit testable code would look like for modifying a document. By way of background I appreciate that classes are great for defining and validating things, like for example:</p>

<ul>
<li>shapes - <a href=""https://codereview.stackexchange.com/questions/172224/understanding-classes-in-vba-help-improve-these-comments"">https://codereview.stackexchange.com/questions/172224/understanding-classes-in-vba-help-improve-these-comments</a></li>
<li>user input - <a href=""https://github.com/rubberduck-vba/Rubberduck/wiki/Unit-Testing#example"" rel=""nofollow noreferrer"">https://github.com/rubberduck-vba/Rubberduck/wiki/Unit-Testing#example</a></li>
</ul>

<p>Whether or not class modules are suitable for modifying a document seems to 'depend' (see Mat's Mug answer here: <a href=""https://stackoverflow.com/questions/45025168/in-vba-should-code-that-modifies-document-be-avoided-in-a-class-module"">In VBA should code that modifies document be avoided in a class module</a>)  And I'm unable to find many examples where unit testing is used for code that modifies a document <em>(perhaps there is a good reason for this?)</em>. </p>

<p>At any rate, based on my limited understanding of things I think that, <em>for a word Add-In that 'adds formatted tables to documents'</em>, a Class Module provides the basis for a reasonable approach to adding a formatted table to a document... <em>(let me know if I'm wrong)</em>.</p>

<p>Although I've tagged VBA-Excel I really am more interested in MS Word examples (which are so lacking) so by way of a fairly trivial example for MS Word, lets say I have code that adds formatted tables to documents at specified ranges. </p>

<p><strong>For the purpose of a example lets assume:</strong> </p>

<ul>
<li>basic order of events is: 

<ul>
<li>add default table to document</li>
<li>subsequently format it in accordance with an INI file</li>
</ul></li>
<li>formatting specified for all tables is:

<ul>
<li>table border line color</li>
<li>table row1 shading color</li>
</ul></li>
<li>there are several tables specified by the INI file

<ul>
<li>tbl1-Border=wdRed</li>
<li>tbl2-Border=wdGreen</li>
<li>tbl1-Shading=wdRed</li>
<li>tbl1-Shading=wdGreen</li>
</ul></li>
</ul>

<p><strong>So my next questions are:</strong></p>

<ul>
<li>how many classes should I plan for?

<ul>
<li>1 for adding and formatting tables</li>
<li>1 for reading INI file data</li>
</ul></li>
<li>what would the structure of each class module look like?</li>
<li><em>should</em> I (can I) unit test code that: 

<ul>
<li>modifies a document (add a table)?</li>
<li>reads INI files?</li>
</ul></li>
</ul>

<p>I'm not expecting anyone to provide actual working code; but pseudo code, general advise and perhaps a few specific pointers would be much appreciated.</p>

<p><em>NOTE: If this question is too broad I'd be happy enough to split into separate questions</em></p>
",https://stackoverflow.com/questions/45538672/how-to-design-and-unit-test-a-vba-class-module-for-adding-formatted-tables-to-do,"['vba', 'excel', 'ms-word', 'rubberduck']",971,TRUE,0,1
Can&#39;t run xctest on macOS app - couldn’t be loaded because it is damaged or missing necessary resources,"<p>Please do help me on this scenario. I saw several post related to this, but could not able to resolve the issue with my <strong>mac App</strong> <strong>without pods</strong>.</p>

<p>Project is several years old, developed in <strong>macOS(Objective C)</strong>. Now I am trying with XCTest for unit testing. Using Xcode 7.3.1, I am not able to run tests classes.</p>

<p>This project is to create frame work. Project is working fine, only issue is with the testing. We are not supposed to do Pods or some other alternatives. </p>

<p>Console window shows below points:</p>

<p>xctest[35530:345970] The bundle “BaseLibTests” couldn’t be loaded because it is damaged or missing necessary resources. Try reinstalling the bundle. xctest[35530:345970]dlopen_preflight(/Users/12345678/Documents/Modify/Cocoa/Projects/BaseLib/build/Debug/BaseLibTests.xctest/Contents/MacOS/BaseLibTests): Library not loaded: @executable_path/../Frameworks/FreeTDS.framework/Versions/A/FreeTDS
Referenced from: /Users/12345678/Documents/Modify/Cocoa/Projects/BaseLib/build/Debug/BaseLib.framework/Versions/Current/BaseLib
Reason: no suitable image found. Did find:
/Library/Frameworks/FreeTDS.framework/Versions/A/FreeTDS: no matching architecture in universal wrapper)
Program ended with exit code: 82</p>
",https://stackoverflow.com/questions/44844166/cant-run-xctest-on-macos-app-couldn-t-be-loaded-because-it-is-damaged-or-miss,"['objective-c', 'macos', 'xctest', 'xctestcase']",722,TRUE,5,1
robolectric - how to mock and inject a business class while creating Activity object,"<p>My task is to write Unit Test for existing Android activity and the code was not written to comply with unit testing (tight coupling). </p>

<p><strong>Scenario</strong>:  I have a class StroageManager, which is getting instantiated inside MyActivity onCreate method. </p>

<pre><code>@Override
protected void onCreate(Bundle savedInstanceState) 
{            
 StorageManager storagemanager = GetStorageManager(); // return new object of stroage manager
 super.onCreate(savedInstanceState);.....
    ...
}
</code></pre>

<p>In order to create the instance of activity through Robolectric, I need to mock it inside my test before setting up the MyActivity.</p>

<p><strong>Problem</strong>: How to mock and inject this mock object while creating myActivity object through robolectric</p>

<p>Note: This is existing Activity and I don't have much freedom to modify the Activity code to large extend. Also, we are using Mockito framework for mocking so it would be great if you give example using Mockito.</p>

<p>Here is my sample code where I try to use Robolectric with Mockito but it fails to work:</p>

<pre><code>@RunWith(RobolectricTestRunner.class)
public class myActivityTest {

    @Mock
    private StorageManager storageManager;

    @InjectMocks
    MyActivity myActivity;

    @Before
    public void setUp() {
        ActivityController&lt;MyActivity&gt; activityController = Robolectric.buildActivity(MyActivity.class);
        myActivity = activityController.get();
       // when(registrationActivity.GetMetricManager()).thenReturn(mock(MetricsManager));
        initMocks(this);
        activityController.setup();         
    }
</code></pre>

<p>}</p>

<hr>

<p>I have tried the solution suggested below but now I am getting this error:</p>

<p>I have modified my code as you suggested and it is throwing below error. while executing this line ActivityController activityController = Robolectric.buildActivity(TestMyActivity.class);                                                                                                   </p>

<p>java.lang.RuntimeException: java.lang.NoSuchMethodException: Tests$TestMyActivity.()</p>

<pre><code>at org.robolectric.util.ReflectionHelpers.callConstructor(ReflectionHelpers.java:233)
    at org.robolectric.util.ActivityController.of(ActivityController.java:27)
    at org.robolectric.Robolectric.buildActivity(Robolectric.java:42)
    at  Tests$TestMyActivity.setUp(RegistrationTest.java:89)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
</code></pre>
",https://stackoverflow.com/questions/41994767/robolectric-how-to-mock-and-inject-a-business-class-while-creating-activity-ob,"['android', 'unit-testing', 'mockito', 'android-testing', 'robolectric']",2651,TRUE,5,1
PageControl in Xcode UITest,"<p>I have an app where a Page Control is used to indicate multiple of screens. When the user taps the page control (for example: to the right the of the current selected page), the scroll view scrolls to the following screen. It works fine.</p>

<p>I wanted to write a UI Test for this scenario. I found out that I cannot tap a specific page control ""dot"" to trigger that action. What I can check is that the Page Control exists and the current selected page. </p>

<p>Another issue is that even if I am able to do so, how can I check that the scroll view has scrolled already? I can only access the frame of the scroll view, not its bounds. </p>

<p>I have just started using Xcode UITest and it's letting me down. I thought it would be powerful by now (it was introduced by Xcode 7 and it was available before as UI Automation), but it seems it's not yet. </p>

<p>I will revert back to Unit Testing + manual functional testing. If anyone has other thoughts, please share it.</p>
",https://stackoverflow.com/questions/47239274/pagecontrol-in-xcode-uitest,"['ios', 'xcode-ui-testing']",1995,TRUE,4,2
How to prove the correctness of a given grammar?,"<p>I am wondering how programming langauge developers validate and prove that their grammar is correct. Suppose that I created a new grammar for a new langauge. I can test my grammar with a unit test tool by providing different kinds of test programs. However, I will never 100% ensure that my grammar is correct. How do language developers ensure that their grammar is correct in real world?</p>

<p>Let's say I created a grammar for a new language using pencil and paper. However, I did a mistake and my grammar accepts the expressions that end with a + like 2+2+. I will implement my language using this incorrect grammar, if I don't find the mistake in it. After implementation and unit testing, I can find the error. Is it possible to find it before starting any implementation?</p>

<p>Definitely, I can try my grammar with some sample inputs using pencil and paper (derivation etc.), but I may miss some corner cases. Is there a better approach or how in the real language developers test their grammar?</p>
",https://stackoverflow.com/questions/43322176/how-to-prove-the-correctness-of-a-given-grammar,"['programming-languages', 'grammar', 'context-free-grammar', 'formal-verification', 'context-free-language']",1167,FALSE,4,1
Is it bad practice to have unit tests run in a loop?,"<p>I am writing some unit tests in C# using nunit. Consider the following code:</p>

<pre><code>    [Test ()]
    public void TestCarCost () {
        for (int i = 0; i &lt; Examples.exampleCount; i++) {
            Car car = new Car(Examples[i]);
            Assert.AreEqual (car.getCost (), Examples[i].cost, ""Test "" + (i + 1) + "" failed"");
        }
    }
</code></pre>

<p>Let's say Examples is a class with some static data for testing different possible input for car types, as you can see I am trying to test for any bugs in the car.getCost() function. Now having this in a loop feels wrong somehow, since for instance when any of the asserts fails it always sends you to the same line of code. Moreover, as far as I can tell whenever an assert fails in a [Test ()] nunit immediately terminates the rest of the test code. Which means if I have everything inside a loop and assert nr 1 fails, I don't get to see whether the other asserts failed. Writing explicitly all of the tests is essentially writing copypasted code, so it also doesn't feel right. What would be considered good practice in this situation? Is it ok to have a ton of similar code in unit testing? Is there some elegant solution that I am missing?</p>
",https://stackoverflow.com/questions/42636124/is-it-bad-practice-to-have-unit-tests-run-in-a-loop,"['c#', 'unit-testing', 'nunit']",2599,TRUE,4,2
Sinon calledWith and calledWithMatch fail for objects EDIT: Sinon spy on object constructor,"<p>I am new to unit testing and am using Mocha, Sinon and Chai to test NodeJs code. The problem is that my expectation for stub.calledWith() always fails when it is an object, even though the test error shows two objects which are syntactically identical. </p>

<p>I am using Sinon to stub a mongoose model's save method, and checking that this stub is called with the correct details. </p>

<p><strong>The function I am testing:</strong></p>

<pre><code>async function createGroup(details) {
        'use strict';
        Logger.info(`create group called`);
        const group   = new UserGroup(this.formatGroup(details));
        const result = await group.save();
        Logger.verbose(`results of save: ${JSON.stringify(result)}`);
        return result;
}
</code></pre>

<p><strong>Unit test</strong></p>

<pre><code>describe('object creation', function () {
        'use strict';
        const saveStub   = sinon.stub(UserGroup.prototype, 'save');
        mongoose.Promise = Promise;
        beforeEach(function (done) {
            saveStub.reset();
            return done();
        });
        after(function (done) {
            saveStub.restore();
            return done();
        });
        it('creates an object without error', async function () {
            const correctDetailsIn   = {
                name: 'stark',
                foo: 'bar',
                bar: 'baz',
                users: [{
                    email: 'eddard@stark.com',
                    firstName: 'eddard',
                    surname: 'stark'
                }]
            };
            const persistableDetails = {
                name: 'stark',
                users: [{
                    email: 'eddard@stark.com',
                    firstName: 'eddard',
                    surname: 'stark'
                }]
            };
            const expectedDetailsOut = {
                _id: 'someidhere',
                name: 'stark',
                users: [{
                    email: 'eddard@stark.com',
                    firstName: 'eddard',
                    surname: 'stark'
                }]
            };
            saveStub.resolves(expectedDetailsOut);
            const res = await userGroupService.createGroup(correctDetailsIn);
            expect(res).to.equal(expectedDetailsOut);
            //I tried the four variations below.
            expect(saveStub).to.be.calledWithMatch(persistableDetails);
            //expect(saveStub).to.be.calledWith(persistableDetails);
            //sinon.assert.calledWithMatch(saveStub, persistableDetails)
            //sinon.assert.calledWith(saveStub, persistableDetails)
        })
    })
</code></pre>

<p>The four methods I have tried all fail with some variation of: </p>

<pre><code>AssertionError: expected save to have been called with arguments matching {
  name: ""stark"",
  users: [{ email: ""eddard@stark.com"", firstName: ""eddard"", surname: ""stark"" }]
}
{
  name: ""stark"",
  users: [{ email: ""eddard@stark.com"", firstName: ""eddard"", surname: ""stark"" }]
}
</code></pre>

<p>I feel like I'm missing something simple to get this working.</p>

<p><strong>EDIT:</strong></p>

<p>So it was something simple (and so blindingly obvious that, of course, I missed it) <code>Model.save()</code> is an instance method, so it's called without parameters. It must be something to do with the Sinon assertions that display the expectation twice, as opposed to expectation and reality. </p>

<p>What I really need to do is figure out how to stub/spy on the <code>Model</code> constructor to ensure that it is called with the right parameters. If anyone knows how to do that, I could reallly do with the help.</p>
",https://stackoverflow.com/questions/45947589/sinon-calledwith-and-calledwithmatch-fail-for-objects-edit-sinon-spy-on-object,"['javascript', 'node.js', 'unit-testing', 'sinon', 'sinon-chai']",3901,FALSE,4,0
Unit test not showing as covering method,"<p>In one of my unit test classes, I'm doing several tests that test the response of a method. They're very similar tests, so I've created a private method to avoid writing out basically the same test multiple times (I'm lazy).</p>

<p>The problem is, in Visual Studio, the ""passing"" information above the method itself isn't showing the coverage from those unit tests that call the private method.</p>

<p><strong>Example method</strong></p>

<p><a href=""https://i.stack.imgur.com/4nI5D.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/4nI5D.png"" alt=""Simple example method""></a></p>

<p><strong>Example unit tests</strong></p>

<p><a href=""https://i.stack.imgur.com/6ZWeo.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/6ZWeo.png"" alt=""enter image description here""></a></p>

<p>As you can see, the unit tests all call MethodForTesting1, though only the first unit test, the one that calls it directly, is seen to cover the method.</p>

<p>Is there any way around this, or do the Visual Studio testing tools just not like private methods in unit tests?</p>

<p><strong>EDIT</strong>
Quick addition, I'm new to unit testing, so for bonus points, is there a better way to gauge code coverage when looking through a class?</p>

<p><strong>EDIT 2</strong>
To address those quick answers who points out that I forgot the <code>[TestMethod]</code> above the last method, it still doesn't show code coverage</p>

<p><a href=""https://i.stack.imgur.com/dy0Hj.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/dy0Hj.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/46885362/unit-test-not-showing-as-covering-method,"['c#', 'unit-testing', 'visual-studio-2015']",3850,TRUE,3,3
Assert.ThrowsException test fails when it does throw exception,"<p>I'm using <code>Microsoft.VisualStudio.TestTools.UnitTesting</code> for unit testing.</p>

<p>I have this test which asserts that an exception was thrown and it is failing</p>

<pre><code>[TestMethod]
public async Task ShouldThrowHttpExceptionIfPassedObjectIsNull()
{
    _mockLogger = new Mock&lt;ILogger&lt;DataService&gt;&gt;();

    // setup memoryCache
    object expected = null;
    _mockNullMemoryCache = MockMemoryCacheService.GetNullMemoryCache(expected);
    _mockSessionManagementService = new MockSessionManagementService();

    _ds = new DataService(
        _mockLogger.Object,
        _mockNullMemoryCache.Object,
        _mockSessionManagementService
    );
    Assert.ThrowsException&lt;HttpException&gt;(() =&gt; _ds.RetrieveFileData&lt;object&gt;(_incorrectFilePath, false));
}
</code></pre>

<p>When I debug it, the last line of code to run before it errors out and fails is this:</p>

<p><a href=""https://i.stack.imgur.com/NkmWi.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/NkmWi.png"" alt=""enter image description here""></a></p>

<p>The exception <code>ex</code> is a <code>system.invalidOperationException</code> but that shouldn't matter because it throws an HttpException not matter what. Why is the test failing with the reason:</p>

<blockquote>
  <p>Test Name:    ShouldThrowHttpExceptionIfPassedObjectIsNull Test
  FullName: xxx.xxx.xxx.xxx.ShouldThrowHttpExceptionIfPassedObjectIsNull
  Test
  Source:   C:\Users\xxx\xxx.cs
  : line 88 Test Outcome:   Failed Test Duration:   0:04:35.5251661</p>
  
  <p>Result StackTrace:     at
  xxxxxx.d__10.MoveNext()
  in
  C:\Users\xxx\xxx\xxx.cs:line
  101
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) Result Message: Assert.ThrowsException failed. No exception
  thrown. HttpException exception was expected.</p>
</blockquote>

<p><strong>EDIT</strong>
The code then moves into this code block after the image:</p>

<pre><code>else
                {
                    // Parsing issue
                    _logger.LogError(string.Format(""Id={0}, Could not retrieve data from {1} : Malformed source data"", _sessionManagementService.SessionId, url));
                    throw new HttpException(HttpStatusCode.InternalServerError, ""Malformed source data"", true);
                }
</code></pre>

<p>As it is throwing the HttpException above, it throws a DllNotFoundException.</p>

<blockquote>
  <p>Exception thrown: 'System.DllNotFoundException' in
  System.Private.CoreLib.ni.dll</p>
  
  <p>Additional information: Unable to load DLL 'combase.dll': The
  specified module could not be found. (Exception from HRESULT:
  0x8007007E)</p>
</blockquote>
",https://stackoverflow.com/questions/42424575/assert-throwsexception-test-fails-when-it-does-throw-exception,"['c#', 'unit-testing', 'visualstudio.testtools']",6063,TRUE,3,1
@EntityListeners Injection + jUnit Testing,"<p>I use <code>@EntityListeners</code> to make operations before I save in my Db and after I load.
Inside my Listener class I make a call to an <code>Ecryptor</code> (which needs to fetch info from configuration file), so the encryptor can't be called statically and need to be injected in my Listener. Right?</p>

<p>Well, injections in EntityListeners can't be done straight away, but you have some methods to do that, like using <code>SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);</code> or even the method showed here. <a href=""https://guylabs.ch/2014/02/22/autowiring-pring-beans-in-hibernate-jpa-entity-listeners/"" rel=""noreferrer"">https://guylabs.ch/2014/02/22/autowiring-pring-beans-in-hibernate-jpa-entity-listeners/</a></p>

<p>Cool, the problem is: None of the solutions support unit testing! When running tests that encryptor I had injected in my model Listener is always <code>null</code>.</p>

<p>Here <a href=""https://stackoverflow.com/questions/25922956/springbeanautowiringsupport-does-not-inject-beans-in-junit-tests"">SpringBeanAutowiringSupport does not inject beans in jUnit tests</a> There is a solution to create this context and pass to a instantiated object, but it does not solve my problem since I have the ""Injection"" to add to it.</p>

<p>Any way to create a context in my tests and somehow pass it to my listeners?
If not, any way I can create a static method to my Encryptor and still have access to the Environment API to read my properties?</p>

<p>Package Listener:</p>

<pre><code>public class PackageListener{
   @Autowired
   Encryptor encryptor;

   @PrePersist
   public void preSave(final Package pack){
      pack.setBic(encryptor.encrypt(pack.getBic()));
   }
   ...
</code></pre>

<p>My test</p>

<pre><code> @Test
 @WithuserElectronics
 public void testIfCanGetPackageById() throws PackageNotFoundException{
     Package pack = packagesServiceFactory.getPackageService().getPackage(4000000002L);
 }
</code></pre>

<p>Package service</p>

<pre><code>  public Package getPackage(Long id) throws PackageNotFoundException{
    Package pack = packageDao.find(id);

    if (pack == null) {
        throw new PackageNotFoundException(id);
    }

    return pack;
}
</code></pre>

<p>Encryptor:</p>

<pre><code>public class Encryptor{
    private String salt;

    public Encryptor(String salt){
        this.salt = salt;
    }

    public String encrypt(String string){
        String key = this.md5(salt);
        String iv = this.md5(this.md5(salt));
        if (string != null) {
            return encryptWithAesCBC(string, key, iv);
        }
        return string;
    }
    ...
</code></pre>
",https://stackoverflow.com/questions/47590917/entitylisteners-injection-junit-testing,"['java', 'spring-mvc', 'junit', 'dependency-injection', 'entitylisteners']",3770,TRUE,10,2
How do I use Codeception unit tests with Slim Framework 3?,"<p>I have run into a few problems trying to make Codeception work with my Slim Framework project.</p>
<p>First, I cannot call a service/repository/model from a unit class without it being in the same namespace. When the tests are run, the following code block results in:</p>
<blockquote>
<p>[Error] Class 'OMIS\Services\UserService' not found`</p>
</blockquote>
<pre><code>// tests
public function testUser()
{
   $userService = new UserService();

   $this-&gt;tester-&gt;assertNotNull($userService-&gt;find(1));
}
</code></pre>
<p>Secondly, I am trying to get Codeception to interact with a testing database I have set up. Because I am using Laravel's Eloquent ORM I thought that enabling the Laravel ORM module for Codeception in <code>unit.suite.yml</code> might work as there is no Slim module available for unit testing, but I get the following error when running the tests:</p>
<blockquote>
<p>ExampleTest: UserPHP Fatal error:  Class 'Symfony\Component\HttpKernel\Client' not found in /Users/me/dev/project/vendor/codeception/codeception/src/Codeception/Lib/Connector/Laravel5.php on line 13</p>
<p>Fatal error: Class 'Symfony\Component\HttpKernel\Client' not found in /Users/Me/dev/project/vendor/codeception/codeception/src/Codeception/Lib/Connector/Laravel5.php on line 13</p>
</blockquote>
<p>Here is the relevant part of my <code>bootstrap/app.php</code> file</p>
<pre><code>session_start();
require __DIR__ . '/../vendor/autoload.php';

// Load environment variables
$dotenv = new Dotenv(__DIR__.'/../');
$dotenv-&gt;load();

$container = require __DIR__.'/../config/container.php';

$app = $container-&gt;get(App::class);

$config = new Config(__DIR__.'/../config/database.php');
$db = $config-&gt;get('db');

$capsule = new Capsule();
$capsule-&gt;addConnection($db);

$capsule-&gt;setAsGlobal();
$capsule-&gt;bootEloquent();

require __DIR__.'/../config/dependencies.php';
require __DIR__.'/../config/services.php';
require __DIR__.'/../config/controllers.php';

require __DIR__ . '/../app/routes.php';

// Middleware
</code></pre>
",https://stackoverflow.com/questions/42390993/how-do-i-use-codeception-unit-tests-with-slim-framework-3,"['php', 'laravel', 'eloquent', 'slim', 'codeception']",565,FALSE,2,0
How to handle static elements with cmocka?,"<p>I am using cmocka to do some unit testing on my C-Project and I am wondering how to handle static emelents.</p>

<p>Static elements are for me:</p>

<ol>
<li>Functions declared as static</li>
<li>Variables inside functions which are declared as static</li>
</ol>

<p>So let the function <code>fut</code> be our function under test, and <code>foo</code> be an other function. Both placed in the file <code>bar.c</code>:</p>

<pre><code>static int fut(int add) {
  static int sum = 0;
  sum += add;
  return sum;
} 

int foo(int someVar){
  //Some calculation on someVar...
  someVar = someVar * 42;

  //call subRoutine
  return fut(someVar);
 }
</code></pre>

<p>And let foo.h  look like this:</p>

<pre><code>extern int foo(int someVar);
</code></pre>

<p>So lets go on I'll show the problem. I would like to test the function under test by two undepended tests which pass some random values for <code>add</code>. The testroutines are placed in main.c and are looking like this:</p>

<pre><code>void fut_test_1(void **state) {
  int ret;
  ret = fut(15);
  assert_int_equal(ret, 15);
  ret = fut(21);
  assert_int_equal(ret, 36);
}

void fut_test_2(void **state) {
  int ret;
  ret = fut(32);
  assert_int_equal(ret, 32);
  ret = fut(17);
  assert_int_equal(ret, 49);
}
</code></pre>

<p>Now I could try to compile the unit test with something like:
    gcc main.c foo.c -Icmocka</p>

<p>There are now two problems: </p>

<ol>
<li><p>The function declared as static cannot be accessed from <code>main.c</code>, so the linker will stop during the build process.</p></li>
<li><p>The variable inside the function which are declared as static will not be reset between the two tests. So the <code>fut_test_2</code> will fail.</p></li>
</ol>

<p>How to handle these problems with the mentioned static elements?</p>
",https://stackoverflow.com/questions/42138037/how-to-handle-static-elements-with-cmocka,"['c', 'unit-testing', 'gcc', 'static', 'cmocka']",1523,TRUE,2,1
How to use VSTS to build a .NET solution that contains a .NET Standard project and a .NET 4.7 project?,"<p>I have a .NET solution which has 2x projects:</p>

<ul>
<li>.NET Standard 1.6</li>
<li>.NET 4.7 xUnit project</li>
</ul>

<p>Unfortunately, I'm using a package in the xUnit project that doesn't work in a .NET Core xUnit project, which is why I'm using a .NET 4.7 project for unit testing.</p>

<p>So, i'm not sure how to do this with Visual Studio Team Services.</p>

<p>Previously, I've just had a .NET Standard Project and a .NET Core xUnit project and have the following:</p>

<ul>
<li>Get Sources (GIT)</li>
<li>Restore (.NET Core)</li>
<li>Build (.NET Core)</li>
<li>Pack (.NET Core)</li>
<li>NuGet Push</li>
</ul>

<p>So - how do I :</p>

<ul>
<li>restore + build a .NET Core project </li>
<li>and then the .NET 4.7 project </li>
<li>and then run the xunit tests for the .NET 4.7 project</li>
<li>and finally pack/nuget push the .NET Standard 1.6 project.</li>
</ul>

<p>please?</p>

<hr>

<p>EDIT:</p>

<p>here's what it looks like on my LOCALHOST machine when i try and do a normal <code>dotnet restore</code></p>

<p>Notice:
- <code>Hornet.Services.csproj</code> is restored.
- <code>Hornet.Services.Tests.csproj</code> is not located or restored.
- Both projects are in my sln, as shown above with the screen shot above.</p>

<pre><code>c:\Projects\Personal\Hornet\Hornet.Services&gt;dotnet restore
  Restoring packages for c:\Projects\Personal\Hornet\Hornet.Services\src\Hornet.Services\Hornet.Services.csproj...
  Generating MSBuild file c:\Projects\Personal\Hornet\Hornet.Services\src\Hornet.Services\obj\Hornet.Services.csproj.nuget.g.props.
  Writing lock file to disk. Path: c:\Projects\Personal\Hornet\Hornet.Services\src\Hornet.Services\obj\project.assets.json
  Restore completed in 1.42 sec for c:\Projects\Personal\Hornet\Hornet.Services\src\Hornet.Services\Hornet.Services.csproj.

  NuGet Config files used:
      c:\Projects\Personal\Hornet\Hornet.Services\NuGet.Config
      C:\Users\Pure Krome\AppData\Roaming\NuGet\NuGet.Config
      C:\Program Files (x86)\NuGet\Config\Microsoft.VisualStudio.Offline.config

  Feeds used:
      https://api.nuget.org/v3/index.json
      https://purekrome.pkgs.visualstudio.com/_packaging/Hornet-Dev/nuget/v3/index.json

c:\Projects\Personal\Hornet\Hornet.Services&gt;
</code></pre>
",https://stackoverflow.com/questions/45650209/how-to-use-vsts-to-build-a-net-solution-that-contains-a-net-standard-project-a,"['.net', 'azure-devops', 'azure-pipelines', '.net-standard']",1213,TRUE,2,1
"How to unit test against a dynamic date/time with Mocha, Chai, Sinon","<p>I'm new to unit testing, and I need to test a function that measures the time elapsed since a reddit post was created. Hard coding the arguments works right now, but the tests will fail as time moves along.</p>

<p>For instance, a test that outputs ""1 day ago"" with a hard-coded argument will pass today, but won't pass tomorrow, as it then will have been 2 days since the post. Same concept applies when measuring hours.</p>

<p>Here's my function that converts the <code>created_utc</code> timestamp (a number like <code>1488420682</code>) to a human-readable amount of time elapsed:</p>

<p><strong>PostCluster.js</strong></p>

<pre><code>getElapsedHours(created_utc) {
  const seconds = created_utc;
  const epoch = new Date(1970, 0, 1);
  const timeStamp = new Date(epoch.setSeconds(seconds));
  const now = new Date();
  const delta = timeStamp - now;
  const currentTimeZoneOffsetInHours = now.getTimezoneOffset() / 60;
  const hoursElapsed = Math.floor(Math.abs((delta / 1000) / 3600) + currentTimeZoneOffsetInHours);

  if (hoursElapsed &gt; 24) {
    const days = Math.floor(hoursElapsed / 24);
    if (hoursElapsed &gt; 48) {
      return `${days} days`;
    } return '1 day';
  } else {
    if (hoursElapsed === 1) {
      return '1 hour';
    } else if (hoursElapsed &lt; 1) {
      return 'less than 1 hour';
    } else {
      return `${hoursElapsed} hours`;
    }
  }
}
</code></pre>

<p><a href=""https://i.stack.imgur.com/PHPbR.png"" rel=""nofollow noreferrer"">Here's an example of the outputs displayed in action</a></p>

<p>The test below passes as is, because the time elapsed since that timestamp will always be greater than 48 hours. BUT... how would I write the tests to check for the outputs ""1 day, 1 hour, x hours, less than 1 hour"" and have them pass <strong>every time</strong> they run in the future?</p>

<p><strong>postcluster.spec.js</strong></p>

<pre><code>describe('&lt;PostCluster /&gt;', () =&gt; {

  it(""ensures getElapsedHours returns 'x days' when greater than 48 hours"", () =&gt; {
    const days = PostCluster.prototype.getElapsedHours(1488420682).split(' ')[1];
    expect(days).to.equal('days');
  });

});
</code></pre>

<p>I've seen MockDate used, but not sure how that can apply here.</p>
",https://stackoverflow.com/questions/42841908/how-to-unit-test-against-a-dynamic-date-time-with-mocha-chai-sinon,"['javascript', 'unit-testing', 'mocha.js', 'sinon', 'chai']",5746,TRUE,2,2
Jest: &quot;SyntaxError: Unexpected token {&quot;,"<p>This is a very simple alteration of the jest tutorial example for react DOM unit testing. I have a counter component and I want to test that it works. You can see my commit at the bottom.</p>

<p>Error:
<code>SyntaxError: Unexpected token {</code></p>

<p>There's only 2 { in the .test.js file and when I remove the <code>jsx ={1}</code> replacing it with =""1"" , it doesn't remove the error. The other { is in the function call <code>() =&gt; {</code></p>

<p><strong>Update 1 (Response to Answer)</strong></p>

<p>I have changed the .test.js file to test.tsx , and made a change to the counter component to allow strings removing the jsx {} and the only other <code>{</code> besides the function constructor.</p>

<p><a href=""https://github.com/Falieson/react15-meteor1.5-typescript2.4/commit/36a327e79700b5532258f7fb8a171122ed260329"" rel=""nofollow noreferrer"">https://github.com/Falieson/react15-meteor1.5-typescript2.4/commit/36a327e79700b5532258f7fb8a171122ed260329</a></p>

<p><strong>Update 2</strong></p>

<p>I've discovered through trying to expose this issue that this error is only happening on my work machine, and not my personal developer machine. Here's the code that works on my machine but not on my work machine.
<a href=""https://github.com/Falieson/react-typescript-meteor"" rel=""nofollow noreferrer"">https://github.com/Falieson/react-typescript-meteor</a></p>

<p><strong>Update 3</strong>
I don't get any problems from jest when I run <code>npm run test:jest</code> but when I run <code>meteor npm run test:jest</code> I get this issue, going to go ask on the <a href=""https://forums.meteor.com/t/-meteor--npm-run-causes-jest-syntax-error/38506/1"" rel=""nofollow noreferrer"">meteor boards</a>.</p>
",https://stackoverflow.com/questions/45513269/jest-syntaxerror-unexpected-token,"['javascript', 'reactjs', 'meteor', 'jestjs', 'babel-jest']",836,TRUE,2,2
Testing the redux store using Jest,"<p>I've set up the following function to configure a Redux store</p>

<pre><code>const configureStore = (initialState) =&gt; {
  console.log(initialState);
  const store = createStore(
    rootReducer,
    initialState,
    applyMiddleware(
      thunkMiddleware
    )
  );

  console.log(store.getState());
  return store;
};
</code></pre>

<p>Now, running this from my normal app entry point, the console logs show, for example:</p>

<pre><code>-&gt; Initial state = { Test: ""test"" }
-&gt; (Store gets created)
-&gt; Store state = { Test: ""test"" }
</code></pre>

<p>Thats good, and as expected. I'm then trying to confirm this behaviour with the following Jest test</p>

<pre><code>it(""should set the supplied initial state"", () =&gt; {
    const initialState = {
      TestState: ""Test""
    };

    const store = configureStore(initialState);
    expect(store.getState()).toEqual({
      TestState: ""Test""
    });
  });
</code></pre>

<p>This test is failing, as store.getState() is returning undefined. I can see the console logs from the configureStore function, and its showing:</p>

<pre><code>-&gt; Initial state = { Test: ""test"" }
-&gt; (Store gets created)
-&gt; Store state = undefined
</code></pre>

<p>Why is the behaviour different? Is it that Jest is mocking the createStore function? I've read that Jest no longer auto-mocks dependencies, so why would this be the case? I'm new to Jest unit testing, so any light that can be shed on this issue will be greatly appreciated.</p>

<p>Edit: I do realise that I'm essentially just testing a Redux function, which is probably very unnecessary. Regardless, I'd like to understand the testing behaviour that's causing this issue.</p>

<p>Second Edit: Writing my own createStore function as follows makes the test pass:</p>

<pre><code>const createStore = (reducer, initState, middleware) =&gt; {
  return {
    getState: () =&gt; (initState)
  };
};
</code></pre>

<p>But this still doesn't answer why the redux createStore function is behaving differently in the test environment.</p>
",https://stackoverflow.com/questions/45367438/testing-the-redux-store-using-jest,"['javascript', 'unit-testing', 'redux', 'jestjs', 'redux-thunk']",11244,TRUE,2,2
How to automate a test in python?,"<p>I have been working with python (in academia) for 5 years now but I had not written a test until last week. Two weeks ago I applied for a job and the employer asked me to do a python task and part of it should be unit testing. 
Assume that my code is as simple as follows (let call it ""add_numbers.py""):</p>

<pre><code>import argparse
parser = argparse.ArgumentParser()
parser.add_argument('x', type=float)
parser.add_argument('y', type=float)

class add_numbers ():
    def __init__ (self, x, y):
        self.x = x
        self.y = y

    def add(self):
        return self.x+self.y

if __name__ == '__main__':
    args = parser.parse_args()
    an = add_numbers(args.x,args.y)
    print('{} + {} = {}'.format(args.x,args.y,an.add()))
</code></pre>

<p>and also assume that the test script is as follows and we name it ""test_add_numbers.py"":</p>

<pre><code>import unittest
from add_numbers import add_numbers

class TddAdd(unittest.TestCase):

    def test_add_two_numbers(self):        
        self.assertEqual(3, add_numbers(1,2).add()) 

if __name__ == '__main__':
    unittest.main()
</code></pre>

<p>And then as instructions for running the code I wrote to him that you can run the test as</p>

<pre><code>python test_add_numbers.py
</code></pre>

<p>and for running the main program you should type</p>

<pre><code>python add_numbers 2 3
</code></pre>

<p>However he came back to me after 2-3 days and after saying that he regrets to reject me told me that I should have ""automated"" the test. What did he mean? So should I integrate the test in the main file such that when I run</p>

<pre><code>python add_numbers 2 3
</code></pre>

<p>it first ""automatically"" runs the test and then run the main program itself.</p>

<p>What ""automated"" test means here and how to make the above test ""automated""?  </p>
",https://stackoverflow.com/questions/46230111/how-to-automate-a-test-in-python,"['python', 'python-3.x', 'unit-testing', 'automated-tests', 'tdd']",183,TRUE,1,1
Is it possible to debug runtime generated groovy code?,"<p>I'm working on a project where we need to compile groovy classes at runtime and then instantiate objects from these classes and execute methods on it. The source for these classes exists as a string only in live environments.
These classes can contain pretty complex code, so there is a good chance of bugs hiding in there.</p>

<p>The problem with our approach is, that when we notice missbehavior in these classes, we can't use a comfortable method of debugging.
We can of course write and execute tests against these classes, but often times you just want to know what's going on step-by-step.</p>

<p><strong>So my question is: Is there is a way to debug runtime generated groovy/Java classes?</strong></p>

<p>The steps we currently take to track down bugs:</p>

<p>1) Write tests to reproduce the behavior</p>

<p>2) Read through the code. (obviously has a super bad success rate in complex classes)</p>

<p>3) Do instrumentation. We call a static ""_break"" method which we have written in a utils class (so no runtime generated stuff). In that _break method we can add a breakpoint. So this is almost as if we were debugging the runtime generated classes directly. The Problem with that approach is, that you have to recompile and add a new version of the groovy classes to the testsystem everytime you want to add/remove a _break call.</p>

<p>If you're wondering how we can even write tests for these classes, here is how:</p>

<p>For unit tests we copy the code from the strings into regular groovy classes. These are used for development and unit testing, because it gives us code completion and a fast way to at least execute the classes against simple tests.
We can debug the code on unit test level. The problem here is, that the data setup is too complex to reproduce certain combinations in unit tests.</p>

<p>For integration tests, we do the whole compilation, adding, executing process, just like it would happen in the live system.</p>

<p>We use Intellij 2017 as IDE and I currently have no idea if or how we could ""connect"" the bytecode to either the strings which is was generated from, or the copied groovy classes we use for unit testing.
Any other tool that would allow us to debug would be fine as well.</p>
",https://stackoverflow.com/questions/45709420/is-it-possible-to-debug-runtime-generated-groovy-code,"['java', 'intellij-idea', 'groovy', 'jvm', 'remote-debugging']",236,FALSE,2,0
"Moq failed exception on Verify: Expected invocation on the mock at least once, but was never performed","<p>Here's another rookie noob question here:</p>

<p>Consider the following:</p>

<pre><code>    public class Company
{
    public string CompanyName {get; set; }
    public string Address {get; set; }
}

public interface IRepository
{
    bool CreateDatabase(string name);
    bool UpdateTable(Company _co);
}

public class MyService
{
    private IRepository _repo;

    public MyService(IRepository repo)
    {
        _repo = repo;
    }

    public bool Commit(string database_name, Company co)
    {
        if (_repo.CreateDatabase(database_name))
            return _repo.Commit(co);

        return false;
    }
}
</code></pre>

<p>So in the repository, if it was successful on creating the database, then it returns TRUE. Same goes for the UpdateTable if all SQL UPDATE was successful as well. Then all I'm doing is passing along the reults back to ViewModel to indicate that all went well.</p>

<p>So in my MSTest:</p>

<pre><code>    [TestMethod]
    public void Test_If_Calls_CreateDatabase_And_UpdateTable()
    {
        var name = ""test"";
        var repoMock = new Mock&lt;IRepository&gt;();
        var _company = new Company();
        repoMock.Setup(r =&gt; r.CreateDatabase(It.IsAny&lt;string&gt;())).Returns(true);
        repoMock.Setup(r =&gt; r.UpdateCompanyTable(It.IsAny&lt;Company&gt;())).Returns(true);

        var engine = new MyService(repoMock.Object);

        var result = engine.Commit(name, _company);

        Assert.IsTrue(result);   // PASSES
        repoMock.Verify(r =&gt; r.CreateDatabase(name), Times.Once);           //FAILS
        repoMock.Verify(r =&gt; r.UpdateCompanyTable(_company), Times.Once);   //FAILS

    }
</code></pre>

<p>This is where things get so whacked. The result returns back true, which means that it got the proper results back, but the Moq verification fails and I get this exception:</p>

<blockquote>
  <p>Expected invocation on the mock at least once, but was never performed: r => r.CreateDatabase(""test"")</p>
</blockquote>

<p>Why is that? Even if I remove Times.Once and just have <code>repoMock.Verify(r =&gt; CreateDatabase(name))</code> I still get the same failed error message.</p>

<p>Any suggestions?</p>

<h2>Corrections</h2>

<p>The code really was the first suggested answer. but there was some copy and paste errors that crept in and this was due to the fact I was trying some variations to make the unit testing to work. For example, I've tried these variations:</p>

<pre><code>engine.Commit(name, _company); // tried that first, that failed
engine.Commit(It.IsAny&lt;string&gt;(), It.IsAny&lt;Company&gt;()); // failed too
engine.Commit(new String(), new Company()); // fails as well
engine.Commit(null, _company)); // fails!! GRR!!
engine.Commit(null, null)); // FAIL! *cocks gun* IT'S HAMMER TIME! *BANG!!*
</code></pre>

<p>I would have thought that the first line would have worked as someone suggested, but it didn't, hence why I am here asking for some help.</p>
",https://stackoverflow.com/questions/44489464/moq-failed-exception-on-verify-expected-invocation-on-the-mock-at-least-once-b,"['c#', 'unit-testing', 'moq', 'mstest']",21307,TRUE,9,1
Calling Database Built-in function in LINQ statement does only work in Unit-test OR in actual application,"<p>I got a huge LINQ-statement with multiple joins with multiple conditions. I need to use database functions (DatePart, DiffDays) in one of the joins. I use Moq for Unit Testing. As those DBFunctions are only invokable via static methods I can't mock these methods. If I call them via SqlFunctions or EntityFunctions I get a NotSupportedException (""This function can only be invoked from LINQ to Entities.""), but my application works. If I use System.Data.Entity.DbFunction it also works in my application, but not in my unit-test.</p>

<p>I shortened the LINQ-Statement, actually it contains a lot more joins:              </p>

<pre class=""lang-cs prettyprint-override""><code> var resultQuery = from t1 in ctx.Table1.AsNoTracking()    
                              join t2 in ctx.Table2 on new
                              {
//works for application, but not in Unit-Test, firstMonday is a predefined DateTime-variable
                                  z3 = (int)EntityFunctions.DiffDays(firstMonday, t1.Date)%7,
//works only in Application, but not in Unit-Test
                                  z4 = SqlFunctions.DatePart(""wk"", t2.Date)
                              } equals new
                              {
                                  z3 = (int)t2.Day,         
                                  z4 = SqlFunctions.DatePart(""wk"", t2.BeginDate)
                              }  into tGroup

                              from x in tGroup.DefaultIfEmpty()
                              where
[...]
//Class DataTransferObjekt defined to hold attributes of both tables

                    select new DataTransferObject
                    {
                        Id = t1.Id,
                        Date = t1.Date,
                        [...]
                        T2Id = t2.ID
                    };
</code></pre>

<p>I tried a lot and did a lot research. Best approaches I found here:
<a href=""https://stackoverflow.com/questions/9585203/entityfunctions-truncatetime-and-unit-tests"">EntityFunctions.TruncateTime and unit tests</a></p>

<p>But I was unable to transfer the offered solutions to my special case as my condition is part of a join and the solution using System.Data.Entity.DbFunction offered in the second answer also didn't work for the Unit-Test as mentioned before.</p>

<p>Any help would be appreciated, I'm still quite new in Moq and LINQ also!</p>
",https://stackoverflow.com/questions/47264944/calling-database-built-in-function-in-linq-statement-does-only-work-in-unit-test,"['c#', 'entity-framework', 'linq', 'unit-testing']",270,FALSE,1,0
Jasmine TypeScript unit test fails if types in methods being tested are not fully qualified,"<p>So I have successfully got unit testing working with my angularjs app using Jasmine and Karma. However, I've just hit an annoying issue I can't figure out.</p>

<p>So I have a controller with a very simple method like this (this is a random example so don't worry if it seems weird):</p>

<pre><code>public ExecuteUserCreatedCommand(
  id: number,
  userId: string) {
  const command = new Commands.UserCreated();
  command.Id = id;
  command.userId = userId;

  return this.CommandService.UserCreated(command);
}
</code></pre>

<p>Note that the Commands.UserCreated object is defined in another file and its fully qualified name is:</p>

<pre><code>Application.Commands.UserCreated
</code></pre>

<p>Now I don't need to use the Application namespace in the application as the controller is in it too. </p>

<p>However, my unit test which looks a bit like this (I've hacked it a bit for the purposes of this post so don't worry about it being perfect):</p>

<pre><code>it(""should send a command to create a new user"", () =&gt; {

const userCreatedCommand = new Application.Commands.UserCreated();
userCreatedCommand.Id = 1;
userCreatedCommand.UserId = ""ab0277a9-79ba-4240-82cf-072444103e6c"";

spyOn(commandService, ""UserCreated"");

MainController.ExecuteUserCreatedCommand(1, ""ab0277a9-79ba-4240-82cf-072444103e6c"");
expect(commandService.UserCreated).toHaveBeenCalledWith(userCreatedCommand );});
</code></pre>

<p>Now this will fail before whilst executing:</p>

<pre><code>MainController.ExecuteUserCreatedCommand(...)
</code></pre>

<p>With the error:</p>

<blockquote>
  <p>ReferenceError: Commands is not defined</p>
</blockquote>

<p>But if I change the method being called so it has this line instead it passes fine:</p>

<pre><code>const command = new Application.Commands.UserCreated();
</code></pre>

<p>I can kind of see why this might be the case but I don't know how to properly solve it without changing all of my methods to have fully qualified object types!</p>
",https://stackoverflow.com/questions/47066703/jasmine-typescript-unit-test-fails-if-types-in-methods-being-tested-are-not-full,"['angularjs', 'unit-testing', 'typescript', 'jasmine', 'karma-runner']",48,FALSE,1,0
Spring setter dependency injection and immutable object,"<p>We know that spring team suggests using setter injection over field injection:</p>

<p><a href=""http://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/html/beans.html#d0e2778"" rel=""nofollow noreferrer"">http://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/html/beans.html#d0e2778</a></p>

<p>Which is what also needed to do unit testing by injecting mock.</p>

<p>However, one thing really is bothering me is that as the spring beans are singletons, so if in some part of the code, the singleton beans are reconfigured by injecting different dependency using the setter methods, then other parts of the code are going to be affected which might be unwanted. For instance, in some part of the code a particular clock instance is injected but may be that particular kind of clock is undesirable in other parts of the code. </p>

<p>So it looks like setter injection leaves some door open for risky business. At the same time we need to a mechanism to inject some mock during testing. How can we strike a balance? </p>

<p>Besides as we know that mutable objects are undesirable:</p>

<p><a href=""http://www.javapractices.com/topic/TopicAction.do?Id=15"" rel=""nofollow noreferrer"">http://www.javapractices.com/topic/TopicAction.do?Id=15</a></p>

<p>Then is it not bad to use setter methods available for singleton beans?</p>
",https://stackoverflow.com/questions/43163324/spring-setter-dependency-injection-and-immutable-object,"['java', 'spring']",687,FALSE,1,1
iOS Swift design for integrating n/w layer,"<p>I have simple ListView that needs to display the records from the network layer. (first screen of the application)</p>

<p>I need to get some opinion as to which will be correct flow so that I can make the unit test cases easily. (No VIPER architecture)</p>

<p>NetworkMgr makes the network calls and create Model objects.</p>

<p>These Model objects needs to be populated in ListTableView.</p>

<p>I have a completion handler method to call the network request which give the model objects.</p>

<pre><code>func getData() {
 dataMgr.requestData(url:  ""String"") { (EmployeesArray, error) in

        //  print(error)
    }
}
</code></pre>

<p>Now the Question is - For unit testing when I am calling the ListDataTest since the ListVC is in storyboard when it loads the View the viewdidLoad method calls the which will initiate the network logic.</p>

<p>SO I am not able to test only the UI related stuffs.</p>

<p>I tried to create some extension in ListDataTest class but no success is achieved.</p>

<p>Below is the flow of the Controllers : - </p>

<p>===</p>

<pre><code>class ListVC: UIViewController {

 var dataProvider: ListData

override func viewDidLoad() {
    super.viewDidLoad()
    dataProvider.viewLoaded()
  }
}
</code></pre>

<p>=======
In ListData class</p>

<pre><code>protocol DatProviderLoad {

func viewLoaded()
}

class ListData: NSObject {


}

extension ListData : DatProviderLoad {

func viewLoaded() {
    print(""loaded"")
  //the network calls goes here
   }
}  
</code></pre>

<p>/—
The test class</p>

<pre><code>class ListDataProviderTest: XCTestCase {

var sut: ListData!
var controller: ListVC!
override func setUp() {
    super.setUp()
    sut = ListData()
    let storyBoard = UIStoryboard(name:""Main"", bundle: nil)
    controller = storyBoard.instantiateViewController(withIdentifier: ""ListVC"") as! ListVC
   controller.dataProvider = sut //before this called the storyboard already called the viewdidload once
    _ = controller.view 
   }
}
</code></pre>

<p>Your feedback will be very helpful.</p>

<p>Any hint or tutorial in right direction will be highly appreciable.</p>
",https://stackoverflow.com/questions/45844938/ios-swift-design-for-integrating-n-w-layer,"['ios', 'swift', 'design-patterns']",87,TRUE,1,1
Unit Testing Django Views that uploads image to s3,"<p>I wrote a simple unit test to test django view. The view uploads the image file that is passed along with the request object to S3.</p>

<p>Code:</p>

<pre><code>        url = 'view-endpoint-url'
        myfile = open('pathtoimage')
        payload = {'data1': 'xyz', 'file': myfile}
        response = client.post(url, payload, MULTIPART_CONTENT)
</code></pre>

<p>At this point when the view under test is called: the image file is stored as expected in request.FILE['file'] of type InMemoryUploadedFile.</p>

<p>When the view tries to open(request.FILE['file']) and read() I get a </p>

<pre><code> IOError no such file or directory
</code></pre>

<p>I'm confused because the image file does exist within the location but for some reason it's not being picked up. I did the similar testing using curl command and all works fine.</p>

<p>Is there any workaround that can help me with the unit testing?</p>

<p>Update:</p>

<p>Basically I'm trying to grab the file path of the InMemoryUploadedFile to unit test the view</p>

<p><strong>Solution</strong></p>

<p>Fixed this issue by reading the file in the same view under test rather than using another utility method to read the InMemoryUploadedFile.</p>

<p>For some reason the InMemoryUploadedFile is loosing track of the file path when it's read using a utility method in a different folder.</p>
",https://stackoverflow.com/questions/43735406/unit-testing-django-views-that-uploads-image-to-s3,"['python', 'django', 'unit-testing', 'django-views', 'django-rest-framework']",255,TRUE,1,1
How to solve Error: spawn EACCES on Jenkins when running Karma?,"<p>I have setup an AWS Codepipeline.</p>

<p>The pipeline uses Git as a source, Jenkins for testing and an EC2 instance for deployment.</p>

<p>The project is based on <a href=""https://github.com/AngularClass/angular-starter"" rel=""nofollow noreferrer"">Angular Starter by Angular Class</a>. Thus, it uses Karma for unit testing.</p>

<p>The Jenkins service runs on Ubuntu 16.04.</p>

<p>Karma uses Headless Chrome for testing.</p>

<p>The problem is that I currently get the folloing error when running the tests on Jenkins:</p>

<pre><code>[31m07 05 2017 14:30:35.779:ERROR [karma]: [39m{ Error: spawn EACCES
    at exports._errnoException (util.js:1050:11)
    at ChildProcess.spawn (internal/child_process.js:319:11)
    at exports.spawn (child_process.js:378:9)
    at spawnWithoutOutput (/var/lib/jenkins/workspace/ExampleTask/node_modules/karma/lib/launchers/process.js:168:24)
    at Object.ProcessLauncher._execCommand (/var/lib/jenkins/workspace/ExampleTask/node_modules/karma/lib/launchers/process.js:76:21)
    at Object.ProcessLauncher._start (/var/lib/jenkins/workspace/ExampleTask/node_modules/karma/lib/launchers/process.js:33:10)
    at Object.&lt;anonymous&gt; (/var/lib/jenkins/workspace/ExampleTask/node_modules/karma/lib/launchers/process.js:19:10)
    at emitOne (events.js:101:20)
    at Object.emit (events.js:191:7)
    at Object.BaseLauncher.start (/var/lib/jenkins/workspace/ExampleTask/node_modules/karma/lib/launchers/base.js:42:10)
    at Object.j (/var/lib/jenkins/workspace/ExampleTask/node_modules/karma/lib/launcher.js:116:17)
    at Object.setTimeout.bind.j (/var/lib/jenkins/workspace/ExampleTask/node_modules/qjobs/qjobs.js:143:18)
    at ontimeout (timers.js:386:14)
    at tryOnTimeout (timers.js:250:5)
    at Timer.listOnTimeout (timers.js:214:5) code: 'EACCES', errno: 'EACCES', syscall: 'spawn' }
</code></pre>

<p>I have already done some research with the following findings:</p>

<ul>
<li>other people also had similar errors but related to to other packages</li>
<li>the error may be related to wrong permissions</li>
</ul>

<p>What I have tried so far:</p>

<ul>
<li>checking the permissions of /var/lib/jenkins/workspace/ExampleTask ->
result: owner is jenkins user</li>
<li>give jenkins user root privileges (I know it is dangerous but I just wanted to try if it would work) -> result: error still exists</li>
<li>allow jenkins user to run scripts with sudo -> result: nvm, npm and node is not defined; I tried to install nvm, npm and node manually but got a new error <code>permission denied /root/.nvm</code></li>
</ul>

<p>npm log file output looks as follows:</p>

<pre><code>0 info it worked if it ends with ok
1 verbose cli [ '/var/lib/jenkins/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/NodeJS_7.10.0/bin/node',
1 verbose cli   '/var/lib/jenkins/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/NodeJS_7.10.0/bin/npm',
1 verbose cli   'run',
1 verbose cli   'test' ]
2 info using npm@4.2.0
3 info using node@v7.10.0
4 verbose run-script [ 'pretest', 'test', 'posttest' ]
5 info lifecycle  example@0.0.1~pretest:  example@0.0.1
6 silly lifecycle  example@0.0.1~pretest: no script for pretest, continuing
7 info lifecycle  example@0.0.1~test:  example@0.0.1
8 verbose lifecycle  example@0.0.1~test: unsafe-perm in lifecycle true
9 verbose lifecycle  example@0.0.1~test: PATH: /var/lib/jenkins/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/NodeJS_7.10.0/lib/node_modules/npm/bin/node-gyp-bin:/var/lib/jenkins/workspace/ExampleTask/node_modules/.bin:/var/lib/jenkins/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/NodeJS_7.10.0/lib/node_modules/npm/bin/node-gyp-bin:/var/lib/jenkins/workspace/ExampleTask/node_modules/.bin:/var/lib/jenkins/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/NodeJS_7.10.0/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/snap/bin
10 verbose lifecycle  example@0.0.1~test: CWD: /var/lib/jenkins/workspace/ExampleTask
11 silly lifecycle  example@0.0.1~test: Args: [ '-c', 'npm run lint &amp;&amp; karma start' ]
12 silly lifecycle  example@0.0.1~test: Returned: code: 1  signal: null
13 info lifecycle  example@0.0.1~test: Failed to exec test script
14 verbose stack Error:  example@0.0.1 test: `npm run lint &amp;&amp; karma start`
14 verbose stack Exit status 1
14 verbose stack     at EventEmitter.&lt;anonymous&gt; (/var/lib/jenkins/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/NodeJS_7.10.0/lib/node_modules/npm/lib/utils/lifecycle.js:279:16)
14 verbose stack     at emitTwo (events.js:106:13)
14 verbose stack     at EventEmitter.emit (events.js:194:7)
14 verbose stack     at ChildProcess.&lt;anonymous&gt; (/var/lib/jenkins/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/NodeJS_7.10.0/lib/node_modules/npm/lib/utils/spawn.js:40:14)
14 verbose stack     at emitTwo (events.js:106:13)
14 verbose stack     at ChildProcess.emit (events.js:194:7)
14 verbose stack     at maybeClose (internal/child_process.js:899:16)
14 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
15 verbose pkgid  example@0.0.1
16 verbose cwd /var/lib/jenkins/workspace/ExampleTask
17 error Linux 4.4.0-1016-aws
18 error argv ""/var/lib/jenkins/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/NodeJS_7.10.0/bin/node"" ""/var/lib/jenkins/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/NodeJS_7.10.0/bin/npm"" ""run"" ""test""
19 error node v7.10.0
20 error npm  v4.2.0
21 error code ELIFECYCLE
22 error errno 1
23 error  example@0.0.1 test: `npm run lint &amp;&amp; karma start`
23 error Exit status 1
24 error Failed at the  example@0.0.1 test script 'npm run lint &amp;&amp; karma start'.
24 error Make sure you have the latest version of node.js and npm installed.
24 error If you do, this is most likely a problem with the  example package,
24 error not with npm itself.
24 error Tell the author that this fails on your system:
24 error     npm run lint &amp;&amp; karma start
24 error You can get information on how to open an issue for this project with:
24 error     npm bugs  example
24 error Or if that isn't available, you can get their info via:
24 error     npm owner ls  example
24 error There is likely additional logging output above.
25 verbose exit [ 1, true ]
</code></pre>
",https://stackoverflow.com/questions/43832900/how-to-solve-error-spawn-eacces-on-jenkins-when-running-karma,"['node.js', 'jenkins', 'permissions', 'karma-runner', 'ubuntu-16.04']",2879,TRUE,1,2
Using TUG for Windows. Compilation fails,"<p>I'm exploring right now open source tools to test my QT GUI Applications. After some research I found the promising:</p>

<p>TUG: GUI Unit Testing library <a href=""https://github.com/pedromateo/tug_qt_unit_testing_fw"" rel=""nofollow noreferrer"">https://github.com/pedromateo/tug_qt_unit_testing_fw</a></p>

<p>Unfortunately, it is a Linux library, but I'm developing windows applications with MSVC. </p>

<p>But I didn't gave up and installed Cygwin. My idea was to compile TUG with Cygwin and afterwards using it together with the <code>cygwin1.dll</code> in my testing framework.</p>

<p><code>TUG</code> is being compiled using <code>qmake</code> Project files producing normal make files. </p>

<p>The first step was to include the switch <code>-D__MINGW32__</code> in the DEFINES section of my qmake project file. This eliminates some compilation errors.</p>

<p>Then I ran my qmake with:</p>

<pre><code>/cygdrive/[My Windows QMake Install Path]/qmake.exe –spec cygwin-g++ tug_base_lib
</code></pre>

<p>Then I ran make and it compiles fine, but failed in the last step linking the object files to the <code>libTUG.dll</code>. It ended up with a lot of undefined references errors. </p>

<p>My idea is, that make tries to link MSVC Windows Libraries to my <code>libTUG.dll</code> resulting in an error. </p>

<p>Does anyone has experience in using <code>TUG</code> together with Windows Applications?</p>

<p>The corresponding section in the generated Makefile, where the linking failed was probably:</p>

<pre><code>$(TARGET):  $(OBJECTS) $(SUBLIBS) $(OBJCOMP)  
    -$(DEL_FILE) $(TARGET) $(TARGET0) $(TARGET1) $(TARGET2)
    $(LINK) $(LFLAGS) -o $(TARGET) $(OBJECTS) $(LIBS) $(OBJCOMP)
    -$(QMAKE) -install ln -s $(TARGET) $(TARGET0)
    -$(QMAKE) -install ln -s $(TARGET) $(TARGET1)
    -$(QMAKE) -install ln -s $(TARGET) $(TARGET2)
</code></pre>

<p>where the Options where</p>

<pre><code>LINK          = g++
LFLAGS        = -shared -Wl,-soname,libTUG.dll.1
LIBS          = $(SUBLIBS) -L/usr/X11R6/lib -L[Path of my Windows QT Libs] -lQt5Widgets_vc14-x64 -lQt5Gui_vc14-x64 -lQt5XmlPatterns_vc14-x64 -lQt5Network_vc14-x64 -lQt5Test_vc14-x64 -lQt5Core_vc14-x64 -lGL -lpthread 

TARGET        = libTUG.dll.1.0.0
TARGETA       = libTUG.a
TARGET0       = libTUG.dll
TARGETD       = libTUG.dll.1.0.0
TARGET1       = libTUG.dll.1
TARGET2       = libTUG.dll.1.0
</code></pre>
",https://stackoverflow.com/questions/42432522/using-tug-for-windows-compilation-fails,"['c++', 'qt', 'cygwin', 'qmake', 'gui-test-framework']",74,FALSE,1,0
Replacing C# method of declaring type which implements an interface and inherits from base,"<p>I'm trying to swap out the contents of a method at runtime for the purposes of unit testing legacy code. I've been working with these SO answers;</p>

<ol>
<li><a href=""https://stackoverflow.com/questions/7299097/dynamically-replace-the-contents-of-a-c-sharp-method"">Dynamically replace the contents of a C# method?</a></li>
<li><a href=""https://stackoverflow.com/questions/38782934/how-to-replace-the-pointer-to-the-overridden-virtual-method-in-the-pointer-of/38783635#38783635"">How to replace the pointer to the overridden (virtual) method in the pointer of my method? (Release x64 and x86)</a></li>
</ol>

<p>Here's a full code sample of what I have so far.</p>

<pre><code>using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace Foo.Bar {

    public interface IFoo {
        string Apple();
    }

    public class Bar {

        protected virtual object One() {
            return null;
        }

        protected virtual object Two() {
            return null;
        }

        protected virtual object Three() {
            return null;
        }

        /* Uncomment this to generate a null reference */
        //protected virtual object Four() {
        //    return null;
        //}

    }

    public class Foo : Bar, IFoo {

        public string Apple() {
            return ""Apple"";
        }

        public string Orange() {
            return ""Orange"";
        }

        /* Uncommenting this fixes the null reference */
        //public override int GetHashCode() {
        //    throw new NotImplementedException();
        //}

        public void ReplaceMethod(Delegate targetMethod, Delegate replacementMethod) {

            MethodInfo methodToReplace = targetMethod.Method;
            MethodInfo methodToInject = replacementMethod.Method;

            RuntimeHelpers.PrepareMethod(methodToReplace.MethodHandle);
            RuntimeHelpers.PrepareMethod(methodToInject.MethodHandle);

            if (methodToReplace.IsVirtual)
                ReplaceVirtualInner(methodToReplace, methodToInject);
            else
                ReplaceStandard(methodToReplace, methodToInject);

        }

        private void ReplaceStandard(MethodInfo methodToReplace, MethodInfo methodToInject) {

            IntPtr targetPtr = methodToInject.MethodHandle.Value;
            IntPtr replacePtr = methodToReplace.MethodHandle.Value;

            unsafe
            {
                if (IntPtr.Size == 4) {

                    int* inj = (int*)replacePtr.ToPointer() + 2;
                    int* tar = (int*)targetPtr.ToPointer() + 2;

                    if (Debugger.IsAttached) {

                        byte* injInst = (byte*)*inj;
                        byte* tarInst = (byte*)*tar;

                        int* injSrc = (int*)(injInst + 1);
                        int* tarSrc = (int*)(tarInst + 1);

                        *tarSrc = (((int)injInst + 5) + *injSrc) - ((int)tarInst + 5);
                    }
                    else {
                        *tar = *inj;
                    }
                }
                else {

                    long* inj = (long*)replacePtr.ToPointer() + 1;
                    long* tar = (long*)targetPtr.ToPointer() + 1;

                    if (Debugger.IsAttached) {

                        byte* injInst = (byte*)*inj;
                        byte* tarInst = (byte*)*tar;

                        long* injSrc = (long*)(injInst + 1);
                        long* tarSrc = (long*)(tarInst + 1);

                        *tarSrc = (((long)injInst + 5) + *injSrc) - ((long)tarInst + 5);
                    }
                    else {
                        *tar = *inj;
                    }
                }
            }


        }

        private void ReplaceVirtualInner(MethodInfo methodToReplace, MethodInfo methodToInject) {

            unsafe
            {
                UInt64* methodDesc = (UInt64*)(methodToReplace.MethodHandle.Value.ToPointer());
                int index = (int)(((*methodDesc) &gt;&gt; 32) &amp; 0xFF);

                if (IntPtr.Size == 4) {
                    uint* classStart = (uint*)methodToReplace.DeclaringType.TypeHandle.Value.ToPointer();
                    classStart += 10;
                    classStart = (uint*)*classStart;

                    uint* tar = classStart + index;
                    uint* inj = (uint*)methodToInject.MethodHandle.Value.ToPointer() + 2;

                    if (Debugger.IsAttached) {

                        byte* injInst = (byte*)*inj;
                        byte* tarInst = (byte*)*tar;

                        uint* injSrc = (uint*)(injInst + 1);
                        uint* tarSrc = (uint*)(tarInst + 1);

                        *tarSrc = (((uint)injInst + 5) + *injSrc) - ((uint)tarInst + 5);
                    }
                    else {
                        *tar = *inj;
                    }

                }
                else {

                    ulong* classStart = (ulong*)methodToReplace.DeclaringType.TypeHandle.Value.ToPointer();
                    classStart += 8;
                    classStart = (ulong*)*classStart;

                    ulong* tar = classStart + index;
                    ulong* inj = (ulong*)methodToInject.MethodHandle.Value.ToPointer() + 1;

                    if (Debugger.IsAttached) {

                        byte* injInst = (byte*)*inj;
                        byte* tarInst = (byte*)*tar;

                        ulong* injSrc = (ulong*)(injInst + 1);
                        ulong* tarSrc = (ulong*)(tarInst + 1);

                        *tarSrc = (((ulong)injInst + 5) + *injSrc) - ((ulong)tarInst + 5);
                    }
                    else {
                        *tar = *inj;
                    }

                }

            }
        }

    }

}
</code></pre>

<p>Usage;</p>

<pre><code>    Foo.Bar.Foo foo = new Foo.Bar.Foo();

    foo.ReplaceMethod(
        ((Func&lt;string&gt;)foo.Apple),
        ((Func&lt;string&gt;)foo.Orange)
    );

    var result = foo.Apple(); // this is ""Orange"" :)
</code></pre>

<p>I have a broad understanding of the code above, essentially it's locating the address of the target method and changing the value so that it points to a different memory location. There's also some extra voodoo to accommodate for memory buffers added by the debugger.</p>

<p>Virtual methods are handled differently which I don't fully understand, especially;</p>

<pre><code>uint* classStart = (uint*)methodToReplace.DeclaringType.TypeHandle.Value.ToPointer();
classStart += 10; /* why 10?? */
classStart = (uint*)*classStart;
</code></pre>

<p>The code works, however, here's where things get weird; if the base class (of the declaring type of the target method) has more than 3 <em>virtual</em> methods, implements an interface and does not override any methods then a NullReferenceException is thrown.</p>

<p>Please, can someone explain what's going on and help me gain a deeper understanding of the code?</p>
",https://stackoverflow.com/questions/44129319/replacing-c-method-of-declaring-type-which-implements-an-interface-and-inherits,"['c#', 'unit-testing', 'pointers', 'virtual', 'unsafe']",265,TRUE,1,1
How to move towards dependency injection with singleton class,"<p>I am trying to learn to write Testable code in Java. I have seen a lot of links saying a singleton class isn't great to implement if I want to do unit testing. So here is what I am trying to solve. I have a class which sends HTTP Requests (HTTPRequest class). I want this class to worry about which protocol to use (TLSv1.2 etc). I have multiple other classes which just calls HTTPRequest class with body, URL, etc.</p>

<p>The way I approached it was that HTTPRequest can be a singleton class since there is no need to create multiple instances of the same thing. The protocol for the entire project will be same and needs to be set only once. </p>

<p>This is how my HTTPRequest looks like. </p>

<pre><code>public class HTTPRequest {
    private CloseableHttpClient httpClient;
    private HttpGet httpGet;
    private HttpPut httpPut;
    private HttpPost httpPost;

    HTTPRequest(CloseableHttpClient a, HttpGet b, HttpPut c, HttpPost d) {
        httpClient = a;
        httpGet = b;
        httpPut = c;
        httpPost = d;
    }

    public HTTPResponse getRequest(url) {
        //Do some processing with httpClient &amp; httpGet to send the request
    }
}
</code></pre>

<p>Now from the classes which require HTTPRequest is there a way to call getRequest, but using only one object? I read something about dependency injection, but I am not really able to figure out how I should do it. </p>

<p>How should I modify the code so that it is testable as well?</p>
",https://stackoverflow.com/questions/41625811/how-to-move-towards-dependency-injection-with-singleton-class,"['java', 'junit', 'dependency-injection']",224,TRUE,1,3
Vuejs Unit Test - Backing Mocks with Tests,"<p>I am writing unit testing for a vuejs 2 application that uses Vuex as a store. I have the following pattern in many of my components:</p>

<p>example component thing.vue:</p>

<pre><code>&lt;template&gt;
    &lt;div&gt;
        {{ thing.label }}
    &lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
  export default {
    name: 'thing',
    data() { return { } },
    computed: {
       thing () {
         return this.$store.state.thing;
       }
    }
  }

&lt;/script&gt;
</code></pre>

<p>Example Store State:</p>

<pre><code>export const state = {
    thing: { label: 'test' }
};
</code></pre>

<p>Example Unit for Thing.vue:</p>

<pre><code>describe('thing ', () =&gt; {

  const storeMock = new Vuex.Store( state: { thing: { label: 'test' } } );

  it('should pull thing from store', () =&gt; {
      const Constructor = Vue.extend(thing);
      const component new Constructor({ store }).$mount();

      expect(component.thing).toEqual({ label: 'test' });
  });

});
</code></pre>

<p>Example Unit test for Store:</p>

<pre><code>import store from './store';

describe('Vuex store ', () =&gt; {

  it('should have a thing object', () =&gt; {
      expect(store.state.thing).toEqual({ label: 'test' });
  });

});
</code></pre>

<p>There is a huge problem with this pattern.  When another developer refractors the store state, they will see the Store test fail, but because the thing unit test is based on a mocked version of the store that test with continue to pass, even though that component will never work. There isn't a good way to know a refactor invalidated a Mock.</p>

<p>So how do people unit test this type of dependence?</p>

<p>One way would be to cheat a little on the unit test and use the real store state, but then it isn't really a unit test.  The other way is rely on integration testing to catch the mock - store mismatch, but that feels like it would be painful to debug why the unit tests pass but the integration tests are failing.</p>
",https://stackoverflow.com/questions/43682881/vuejs-unit-test-backing-mocks-with-tests,"['laravel', 'unit-testing', 'jasmine', 'vue.js', 'vuex']",377,FALSE,1,1
How to unit test certificate exchange in Lumen 5.4,"<p>I am working on an API authentication project.  Authentication is achieved by adding a client certificate to the https request to the api.  Everything works great when I curl to my api using my client certificate and Lumen actually made it trivial to do.</p>

<p>What is not so trivial is unit testing this.</p>

<p>Does anyone know how to make an HTTPS connection in a unit test?</p>

<p>The callSecure method seems to have disappeared since the last version of lumen.</p>

<p>Assuming the HTTPS connection is made - does anyone know how to easily set the certificate.  I was hoping I could just get the unit test framework to set up the correct $_SERVER superglobal values so I could use a data provider to send several different certificate errors.</p>

<p>I'd also like to mock the models the controller is injected with so I provide known data in my data providers without having to do any database manipulation.</p>

<p>What I do not want to do is write some methods to make an entire curl request using real certificates.</p>
",https://stackoverflow.com/questions/42997506/how-to-unit-test-certificate-exchange-in-lumen-5-4,"['php', 'laravel', 'unit-testing', 'ssl', 'lumen']",116,FALSE,0,1
"Equality check for Dictionary&lt;string, Stream&gt; with xunit","<p>I am trying to unit test a method, and its uses a dictionary passed to a mocked method to add attachments to an email.  The test always fails, stepping through everything seems to be correct but the <code>Assert</code> does not seem to verify that.</p>

<p>Is there a special way of unit testing dictionaries in general, and would that work with on that is setup for <code>&lt;string, Stream&gt;</code>.  Code is below, but don't think its anything with that, but may have set something up incorrectly, i think i am missing something obvious.</p>

<pre><code>    [Fact]
    public void Process_ShouldAttachCsvStreamWhenBuildingEmailMessage()
    {
        //Arrange
        var fixture = new Fixture();
        var settings = fixture.Create&lt;Settings&gt;();
        var sutFixtures = new SUTFixtures(true);
        var response = RemoteClientResponseHelper.GetMockHttpWebResponse(sutFixtures.Items);

        //deal with attachement
        var csv = sutFixtures.ToCsv();
        var bytes = Encoding.GetEncoding(""iso-8859-1"").GetBytes(csv);
        var messageAttachments = new Dictionary&lt;string, Stream&gt; {{""MissingImages.csv"", new MemoryStream(bytes)}};

        var moqClientService = new Mock&lt;IClientService&gt;();
        moqClientService.Setup(x =&gt; x.Call(It.IsAny&lt;string&gt;(), It.IsAny&lt;string&gt;(), It.IsAny&lt;string&gt;(), It.IsAny&lt;string&gt;(), null))
           .Returns(response.Object);

        Dictionary&lt;string, Stream&gt; attachmentsVerify = null;

        var moqEmailService = new Mock&lt;IEmailService&gt;();
        moqEmailService.Setup(
            x =&gt;
                x.BuildMessage(It.IsAny&lt;string&gt;(), It.IsAny&lt;string&gt;(), It.IsAny&lt;string&gt;(), It.IsAny&lt;string&gt;(),
                    It.IsAny&lt;bool&gt;(), It.IsAny&lt;Dictionary&lt;string, Stream&gt;&gt;()))
            .Callback&lt;string, string, string, string, bool, Dictionary&lt;string, Stream&gt;&gt;(
                (to, from, subject, body, isHtml, attachments) =&gt;
                {
                    attachmentsVerify = attachments;
                });

        //Act 
        var sut = new MissingImageNotificationStep(moqClientService.Object, moqEmailService.Object, settings);
        sut.Process(new MappingData() { Parts = sutFixtures.DataTable });

        //Assert
        moqEmailService.Verify(m =&gt; m.BuildMessage(It.IsAny&lt;string&gt;(),
            It.IsAny&lt;string&gt;(),
            It.IsAny&lt;string&gt;(),
            It.IsAny&lt;string&gt;(),
            It.IsAny&lt;bool&gt;(),
            It.IsAny&lt;Dictionary&lt;string, Stream&gt;&gt;()), Times.Once());

        Assert.Equal(messageAttachments, attachmentsVerify);
    }
</code></pre>

<hr>

<p><strong>UPDATE</strong></p>

<p>Must have been very lazy as i thought about a custom comparer but thought maybe it was already something there.  I have something working, for my case anyway, looking at the comparer i have to do some explicit casting which is fine in my case but is a bit smelly and therefor my code needs a refactor, also not sure the GetHash does anything in this scenario, if this code ever gets used outside the tests i will look at that.</p>

<p><strong>Custom Comparer</strong></p>

<pre><code>public class DictionaryComparer : IEqualityComparer&lt;Dictionary&lt;string, Stream&gt;&gt;
{
    private readonly IEqualityComparer&lt;Stream&gt; _valueComparer;
    public DictionaryComparer(IEqualityComparer&lt;Stream&gt; valueComparer = null)
    {
        this._valueComparer = valueComparer ?? EqualityComparer&lt;Stream&gt;.Default;
    }

    public bool Equals(Dictionary&lt;string, Stream&gt; x, Dictionary&lt;string, Stream&gt; y)
    {
        if (x.Count != y.Count)
            return false;

        if (x.Keys.Except(y.Keys).Any())
            return false;

        if (y.Keys.Except(x.Keys).Any())
            return false;

        foreach (var pair in x)
        {
            var xValue = pair.Value as MemoryStream;
            var yValue = y[pair.Key] as MemoryStream;

            if (xValue.Length != yValue.Length)
                return false;

            xValue.Position = 0;
            yValue.Position = 0;

            var xArray = xValue.ToArray();
            var yArray = yValue.ToArray();

            return xArray.SequenceEqual(yArray);
        }

        return true;
    }

    public int GetHashCode(Dictionary&lt;string, Stream&gt; obj)
    {
        unchecked
        {
            var hash = 17;

            foreach (var key in obj.Keys)
            {
                hash = hash * 23 + key.GetHashCode();
            }

            return hash;
        }
    }
}
</code></pre>

<p><strong>Called via XUnit</strong></p>

<pre><code>Assert.Equal(messageAttachments, attachmentsVerify, new DictionaryComparer());
</code></pre>
",https://stackoverflow.com/questions/42350757/equality-check-for-dictionarystring-stream-with-xunit,"['c#', 'unit-testing', 'xunit']",5858,TRUE,0,2
Collaboration in web application - concurrency testing and assert the (eventual) consistency?,"<p>Is there a testing framework or solution to test and assert collaboration on shared data in a webapplication? </p>

<p>The client-side mainly focus on changing the structure of a large collection of ordered objects. Basic operations like insert, delete and reordering the structure. To prevent stale data, operations from other users are synchronized with bi-directional communication.</p>

<p>This collection can be edited by two or more users concurrently. All edits are pessimistic in such a way that the server determines the right outcome to prevent conflicts. The server transforms two concurrent operations (from the same state) and broadcast the changes.</p>

<p>Unit testing the transformation on the server works just fine. But is there a solution to create some sort of automated test that covers the complete flow with two concurrent users? Like simulating that two clients sending a concurrent operation and assert that the result on both clients will be eventual consistent - after applying both changes?</p>

<p>Or is the only solution to write tests for the server and the client fully isolated from each other, without any 'real' collaboration testing?</p>
",https://stackoverflow.com/questions/44945309/collaboration-in-web-application-concurrency-testing-and-assert-the-eventual,"['testing', 'concurrency', 'collaboration', 'eventual-consistency']",48,FALSE,0,0
Android unit test: mock BluetoothDevice and write to parcel,"<p>I would like to ask about unit testing a class that has <code>BluetoothDevice</code> variable. </p>

<p>My object is a simple object that contains some primitive variable and a BluetoothDevice variable. My object is also parcelable.</p>

<p>Eventually my code works totally fine on the mobile device but I have strange error when I run my unit tests.</p>

<p>I mocked the BluetoothDevice in the test class as shown below:</p>

<pre><code>@RunWith(RobolectricTestRunner.class)
@Config(manifest=Config.NONE)
public class BluetoothDeviceTest {

    @Mock
    BluetoothDevice device1;

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

        when(device1.getAddress()).thenReturn(""01:02:03:04:05:06"");
        when(device1.getName()).thenReturn(""device767b1"");
        when(device1.getBondState()).thenReturn(BOND_NONE);
    }
}
</code></pre>

<p>In my object among other primitives I use:</p>

<ul>
<li><p>I use <code>out.writeParcelable(mBluetoothDevice,0);</code> inside <code>@Override public void writeToParcel(Parcel out, int flags)</code> method.   </p></li>
<li><p>I use <code>mBluetoothDevice = in.readParcelable(BluetoothDevice.class.getClassLoader());</code> inside <code>protected MyObject(Parcel in)</code> constructor.</p></li>
</ul>

<p>The unit test that tests parcelling of my object instance fails with an exception
<code>java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String</code></p>

<p>Once again please note that when my code runs totally fine and parcelling works good in the mobile app I work on. Only unit test is acting strange.</p>

<p>I suspect this is because my mocked <code>BluetoothDevice</code> variable is shorter in the parcel than a normal real instance and the order of the data fields in the parcel gets messed up. </p>

<p>Has anybody unit tested with a mocked <code>BluetoothDevice</code> and can give me some hint ? Thank you</p>
",https://stackoverflow.com/questions/43770321/android-unit-test-mock-bluetoothdevice-and-write-to-parcel,"['java', 'android', 'unit-testing', 'mocking', 'android-bluetooth']",4490,TRUE,0,3
akka persistent actor testing events generated,"<p>By the definition of CQRS command can/should be validated and at the end even declined (if validation does not pass). As a part of my command validation I check if state transition is really needed. So let take a simple, dummy example: actor is in state A. A command is send to actor to transit to state B. The command gets validated and at the end event is generated <code>StateBUpdated</code>. Then the exact same command is send to transit to state B. Again command gets validated and during the validation it is decided that no event will be generated (since we are already in state B) and just respond back that command was processed and everything is ok. It is kind of idempotency thingy.</p>

<p>Nevertheless, I have hard time (unit) testing this. Usual unit test for persistent actor looks like sending a command to the actor and then restarting actor and check that state is persisted. I want to test if I send a command to the actor to check how many events were generated. How to do that?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/47001228/akka-persistent-actor-testing-events-generated,"['unit-testing', 'testing', 'akka', 'cqrs', 'akka-persistence']",434,TRUE,0,2
How to correctly build a list of tiles in a for loop?,"<p>I'm working at a turn-based strategy game for school and the playing field consists of a grid 8x8. So there are 64 tiles in a map. For now i'm testing to generate a map apart from the GUI. My grid is x,y based, so the first tile will be (1,1), the second (2,1), the ninth(1,2) .. 64th (8,8).</p>

<p>My idea was to generate a map, that is a list of tiles, in a for loop, like this:</p>

<pre><code>// GENERATE MAP
    int x = 1;
    int y = 1;
    for(int i = 0; i &lt; 64; i++) {
        if(x != 9) {
            Tile tile = new Tile(x, y, null);
            tiles.add(tile);
            x++;
        }
        else {
            x = 1 ;
            y++;
            Tile tile = new Tile(x, y, null);
            tiles.add(tile);
        }
    }
</code></pre>

<p>The problem is when i am unit testing the map, my expected x,y values are not the same as in the generated map. </p>

<pre><code>assertEquals(64, tiles.size());
assertEquals(new Point(2,1), tiles.get(1).getPos());
assertEquals(new Point(8,1), tiles.get(7).getPos());
assertEquals(new Point(1,2), tiles.get(8).getPos());
assertEquals(new Point(8,8), tiles.get(63).getPos());

org.opentest4j.AssertionFailedError: 
Expected :java.awt.Point[x=8,y=8]
Actual   :java.awt.Point[x=1,y=8]
&lt;Click to see difference&gt;
</code></pre>

<p>Tile 63 must be the last tile(8,8) but it isn't. Can someone help me out here?</p>

<p>Besides this problem, my idea was to later set terrain on certain tiles, with tiles.get(4).setTerrain(""Tree""); etc. Is this way of creating a map with tiles a good start or am i working in the wrong direction? Later we will bind it to the GUI.</p>

<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/43218488/how-to-correctly-build-a-list-of-tiles-in-a-for-loop,['java'],414,TRUE,0,3
Should I use the repository pattern or mocking framework for &#39;mocking&#39; a model locally before creating the database tables?,"<p>I have an ASP.NET MVC application using Entity Framework Code First.</p>

<p>I want to be able to test my applications 'look-and-feel' and interaction without first creating the database tables. This is by preference as I don't want to have to keep updating the database if I make changes to the model for some reason.</p>

<p>Is this a good place to use the Repository pattern?</p>

<p>My current code:</p>

<p>Model:</p>

<pre><code>public class FATTemplateHeader
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public int AnatomyModelId { get; set; }
    public virtual AnatomyModel AnatomyModel { get; set; }

    [StringLength(128)]
    public string Description { get; set; }

    [StringLength(16)]
    public string TemplateVersion { get; set; }

    public DateTime DateCreated { get; set; }

    public char Status { get; set; }

    public string CreatedBy { get; set; }
    [ForeignKey(""CreatedBy"")]
    public virtual AspNetUser User { get; set; }
}
</code></pre>

<p>Interface:</p>

<pre><code>public interface IFatTemplateRepository
{
    #region FatTemplateHeader

    IEnumerable&lt;FATTemplateHeader&gt; GetFatTemplateHeaders();
    IEnumerable&lt;FATTemplateHeader&gt; GetFatTemplateHeadersByModel(int modelId);
    FATTemplateHeader GetFatTemplateHeaderByName(string name);

    void InsertFatTemplateHeader(FATTemplateHeader header);
    void DeleteFatTemplateHeader(int headerId);
    void UpdateFatTemplateHeader(FATTemplateHeader header);

    #endregion

    void Save();
}
</code></pre>

<p>Real class that would use the database:</p>

<pre><code>public class FatTemplateRepository : IFatTemplateRepository, IDisposable
{
    private Db _dbContext;

    public FatTemplateRepository(Db context)
    {
        _dbContext = context;
    }

    #region FAT Template Header

    public IEnumerable&lt;FATTemplateHeader&gt; GetFatTemplateHeaders()
    {
        return _dbContext.FATTemplateHeaders.ToList();
    }

    public IEnumerable&lt;FATTemplateHeader&gt; GetFatTemplateHeadersByModel(int modelId)
    {
        return _dbContext.FATTemplateHeaders.Where(x =&gt; x.AnatomyModelId == modelId).ToList();
    }

    public FATTemplateHeader GetFatTemplateHeaderByName(string name)
    {
        return _dbContext.FATTemplateHeaders.Find(name);
    }

    public void InsertFatTemplateHeader(FATTemplateHeader header)
    {
        _dbContext.FATTemplateHeaders.Add(header);
    }

    public void DeleteFatTemplateHeader(int headerId)
    {
        FATTemplateHeader header = _dbContext.FATTemplateHeaders.Find(headerId);
        _dbContext.FATTemplateHeaders.Remove(header);
    }

    public void UpdateFatTemplateHeader(FATTemplateHeader header)
    {
        _dbContext.Entry(header).State = EntityState.Modified;
    }

    #endregion

    public void Save()
    {
        _dbContext.SaveChanges();
    }

    // IDispose
    private bool disposed = false;
    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                _dbContext.Dispose();
            }
        }
        this.disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}
</code></pre>

<p>Mock class that uses Lists as collection:</p>

<pre><code>public class MockFatTemplateRepository: IFatTemplateRepository
{
    #region FAT Template Header

    private static IList&lt;FATTemplateHeader&gt; mockFatTemplateHeaders;

    public MockFatTemplateRepository()
    {
        if (!mockFatTemplateHeaders.Any())
        {
            // Seed with data
            IList&lt;FATTemplateHeader&gt; mockFatTemplateHeaders = new List&lt;FATTemplateHeader&gt;
            {
                new FATTemplateHeader
                {
                    Id = 1,
                    AnatomyModelId = 1,
                    Description = ""TEST 1"",
                    TemplateVersion = ""1.0"",
                    DateCreated = DateTime.Now,
                    Status = 'A',
                    CreatedBy = ""user1""
                },
                new FATTemplateHeader
                {
                    Id = 2,
                    AnatomyModelId = 1,
                    Description = ""TEST 2"",
                    TemplateVersion = ""1.1"",
                    DateCreated = DateTime.Now,
                    Status = 'A',
                    CreatedBy = ""user1""
                }
            };
        } 
    }


    public IEnumerable&lt;FATTemplateHeader&gt; GetFatTemplateHeaders()
    {
        return mockFatTemplateHeaders;
    }

    public IEnumerable&lt;FATTemplateHeader&gt; GetFatTemplateHeadersByModel(int modelId)
    {
        return mockFatTemplateHeaders.Where(x =&gt; x.AnatomyModelId == modelId).ToList();
    }

    public FATTemplateHeader GetFatTemplateHeaderByName(string name)
    {
        return mockFatTemplateHeaders.Where(x =&gt; x.Description == name).FirstOrDefault();
    }

    public void InsertFatTemplateHeader(FATTemplateHeader header)
    {
        mockFatTemplateHeaders.Add(header);
    }

    public void DeleteFatTemplateHeader(int headerId)
    {
        FATTemplateHeader deleteHeader = mockFatTemplateHeaders.Where(x =&gt; x.Id == headerId).FirstOrDefault();

        if (deleteHeader != null)
            mockFatTemplateHeaders.Remove(deleteHeader);
    }

    public void UpdateFatTemplateHeader(FATTemplateHeader header)
    {
        FATTemplateHeader updateHeader = mockFatTemplateHeaders.Where(x =&gt; x.Id == header.Id).FirstOrDefault();

        if (updateHeader != null)
        {
            updateHeader = header;
        }
    }

    #endregion

    public void Save()
    {
    }

}
</code></pre>

<p>Also I have read a bit about using a mocking framework such as Moq, but it seems that it is mostly used for Unit Testing.</p>

<p>I am totally confused as to whether I should using the interface as I have in my code above or if this is the job for a mocking framework.</p>

<p>Lastly I am confused about how to inject my model into my controller so that when I am satisfied with my Model and I do create my database tables, that the switch over from Mock class to real class is simple.</p>

<p>Thanks,</p>

<p>Neill</p>
",https://stackoverflow.com/questions/45219439/should-i-use-the-repository-pattern-or-mocking-framework-for-mocking-a-model-l,"['asp.net-mvc', 'unit-testing', 'mocking']",23,FALSE,0,0
Test a dialog that needs to be forwarded to,"<p>I've created a dialog that expects to be forwarded to</p>

<pre><code>using Microsoft.Bot.Builder.Dialogs;
using pc.apm.bot.Services;
using System;
using System.Diagnostics;
using System.Threading.Tasks;

namespace pc.apm.bot.Dialogs
{
    [Serializable]
    public class NewUserDialog : IDialog&lt;string&gt;
    {
        IApmService _apmService;
        LangaugeCodes _langaugeCode;

        public NewUserDialog(IApmService apmService, LangaugeCodes langaugeCode)
        {
            _apmService = apmService;
            _langaugeCode = langaugeCode;
        }

        public async Task StartAsync(IDialogContext context)
        {
            if (new TraceSwitch(""apmDiagnostics"", """").Level == TraceLevel.Info)
                await context.PostAsync($""Current Dialog: {this.GetType().Name}"");

            context.Wait&lt;string&gt;(MessageReceivedAsync);
        }

        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable&lt;string&gt; result)
        {
            var userEmail = await result;

            await context.PostAsync(StringResourceService.GetStringResource(StringKeys.NewUserStarted_Key, _langaugeCode));

            var apmId = await _apmService.CreateUserAsync(userEmail.ToLower());

            var UserProvisionedAlfabet_Text = StringResourceService.GetStringResource(StringKeys.UserProvisionedAlfabet_Key, _langaugeCode);
            await context.PostAsync(String.Format(UserProvisionedAlfabet_Text, userEmail));

            context.Done(apmId);
        }
    }
}
</code></pre>

<p>now the way it works is on a previous dialog I have some logic that decides a new user needs to be provisioned, when that is the case it forwards the users email to the NewUserDialog to do just that.</p>

<pre><code>await context.Forward(
    child: new NewUserDialog(), 
    resume: (c, r) =&gt; AddProfile(context, result), 
    item: user.Email,
    token: CancellationToken.None);
</code></pre>

<p>so that all works fine and dandy, the problem i'm having is Unit testing this code; i'm trying to follow what has been laid out in bot builder tests project</p>

<p><a href=""https://github.com/Microsoft/BotBuilder/tree/master/CSharp/Tests/Microsoft.Bot.Sample.Tests"" rel=""nofollow noreferrer"">https://github.com/Microsoft/BotBuilder/tree/master/CSharp/Tests/Microsoft.Bot.Sample.Tests</a></p>

<p>now i have my test starting, it's just when my NewUserDialog attempts to await the email address the thing fails and and exception is thrown</p>

<p>pc.apm.bot.tests.Test_New_User_Dialog.Create_New_User threw exception: 
Microsoft.Bot.Builder.Internals.Fibers.InvalidTypeException: invalid type: expected System.String, have Activity</p>

<p>so i see that it's a type issue; but i am at a loss as how to pass the email address to the dialog through the test code.</p>

<p>here's my test code</p>

<pre><code>using Autofac;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.Dialogs.Internals;
using Microsoft.Bot.Builder.Tests;
using Microsoft.Bot.Connector;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using pc.apm.bot.Dialogs;
using pc.apm.bot.Services;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace pc.apm.bot.tests
{
    [TestClass]
    public class Test_New_User_Dialog : DialogTestBase
    {
        [TestMethod]
        public async Task Test_method() =&gt; Assert.IsTrue(await Task.FromResult(true));

        [TestMethod]
        public async Task Create_New_User()
        {
            var mockApmService = new Mock&lt;IApmService&gt;(MockBehavior.Strict);
            mockApmService
                .Setup(m =&gt; m.CreateUserAsync(It.IsAny&lt;string&gt;()))
                .Returns&lt;string&gt;(x =&gt; Task.FromResult(""123-123""));

            var NewUserDialog = new NewUserDialog(mockApmService.Object, LangaugeCodes.en_US);

            var toBot = DialogTestBase.MakeTestMessage();
            toBot.From.Id = Guid.NewGuid().ToString();

            Func&lt;IDialog&lt;string&gt;&gt; MakeRoot = () =&gt; NewUserDialog;

            using (new FiberTestBase.ResolveMoqAssembly(NewUserDialog))
            using (var container = Build(Options.MockConnectorFactory | Options.ScopedQueue, NewUserDialog))
            {
                using (var scope = DialogModule.BeginLifetimeScope(container, toBot))
                {
                    DialogModule_MakeRoot.Register(scope, MakeRoot);
                    await Conversation.SendAsync(scope, toBot);

                    var firstResponse = scope.Resolve&lt;Queue&lt;IMessageActivity&gt;&gt;().Dequeue();
                    Assert.IsTrue(firstResponse.Text.Equals(""Looks as if you are a new user, let's get you started!""));

                    var secondResponse = scope.Resolve&lt;Queue&lt;IMessageActivity&gt;&gt;().Dequeue();
                    Assert.IsTrue(secondResponse.Text.Equals(""A user for pawel.chooch@fake.com has been provisioned in System""));
                }

            }
        }
    }
}
</code></pre>

<p>so in short my question is how can you test a dialog that receives a parameter by having it forwarded to it from a parent dialog?</p>
",https://stackoverflow.com/questions/46671429/test-a-dialog-that-needs-to-be-forwarded-to,"['c#', 'unit-testing', 'botframework']",237,TRUE,0,1
How to unit test private variable?,"<p>I have a class for products (<code>MyProduct</code>) and then another class (<code>ProductAnalyzer</code>) for performing various options on a collection of products.</p>

<p>I want to do unit testing on these classes. Specifically, testing if product is X days old or older. </p>

<p>There is already a function called <code>ProductAnalyzer.tenDaysOld()</code> that will do this. As long as instances of <code>MyProduct</code> are in the  <code>ProductAnalyzer</code> collection, it will do the calculation.</p>

<p>In order to run tests, I need a way to somehow modify timestamps on MyProduct instances so they are older than 10 days. Or perhaps modify <code>tenDaysOld()</code>. Either way, I'm guessing they'll need to be mocked.</p>

<p>In <code>MyProduct</code>, <code>productCreated</code> is timestamped and private. I'd like to keep it that way but that means it can't be tested. If I modify it to public, I can test it but then I'm changing the code base just for testing purposes, which has nothing to do with actual functionality in production (isn't that bad practice?).</p>

<p>Any suggestions how I can approach this?</p>

<p>Below are simplified versions of the classes with relevant code shown.</p>

<pre><code>class MyProduct: NSObject {
    private var productCreated:Date

    init(){
        productCreated = Date()
    }
}

class ProductAnalyzer {
    static var products:[InventoryItem] = []
    static func tenDaysOld() {
        let tenDays = NSCalendar.current.date(byAdding: Calendar.Component.day, value: 10, to: Date())

        let oldProducts = ProductAnalyzer.products.filter({  $0.dateAdded.compare(tenDays!) == .orderedDescending })

    }
}
</code></pre>
",https://stackoverflow.com/questions/47912494/how-to-unit-test-private-variable,"['swift', 'unit-testing', 'mocking']",128,FALSE,0,0
C# `Int32` how to limit range correctly?,"<p>I'm working on my optimized <code>XorShift32</code> pseudo-random number generator to be used for unit tests. It's significantly faster than System.Random, with <code>unsafe</code> optimizations it's way faster. Plus I added server handy methods to make my unit testing easier. However I have a problem with it correctness since the overflow when using ranges close to <code>Int32.MinValue</code> and <code>Int32.MaxValue</code>.</p>

<p>Here's the method (I know it's incorrect):</p>

<pre><code>    /// &lt;summary&gt;
    /// Returns a random integer that is within a specified range.
    /// &lt;/summary&gt;
    /// &lt;param name=""min""&gt;The inclusive lower bound of the random number returned.&lt;/param&gt;
    /// &lt;param name=""max""&gt;The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue.&lt;/param&gt;
    /// &lt;returns&gt;A 32-bit signed integer greater than or equal to minValue and less than maxValue; that is, the range of return values includes minValue but not maxValue. If minValue equals maxValue, minValue is returned.&lt;/returns&gt;
    public int Next(int min, int max) {
        if (min == max) return min;
        Seed ^= Seed &lt;&lt; 13;
        Seed ^= Seed &gt;&gt; 17;
        Seed ^= Seed &lt;&lt; 5;
        if (min == int.MinValue &amp;&amp; max == int.MaxValue) return unchecked((int)Seed);
        return min + (int)(Seed / Max * (max - min));
    }
</code></pre>

<p>When <code>Math.Abs(max - min) &lt; Int32.MaxValue</code> it returns correct numbers, but otherwise the numbers overflow. First, the condition stated above seems to make sense for a human, but not necessarily  for the compiler or IL. Anything except <code>Int32.MaxValue</code> is less than <code>Int32.MaxValue</code> so using that in code is pointless. Then again I could cast max and min to <code>Int64</code>, then make the calculations, but the issue is it would defeat all optimizations gain here.</p>

<p>Any ideas how to limit the output range FAST?</p>

<p>Let's consider the test case: <code>var x = R.Next(-1, Int32.MaxValue)</code>. This code will fail miserably on this. How to make it correct without hitting the performance too much?</p>

<p>BTW, I know there's no practical reason of making such PRNG, I'm doing it solely for learning purpose.</p>
",https://stackoverflow.com/questions/42970917/c-int32-how-to-limit-range-correctly,"['c#', '.net']",399,TRUE,0,1
PHPUnit object cloned,"<p>we're working on PHPunitizing our application with two scopes in mind: reduce regressions and bugs in releases.
The application apply an MVC pattern but with no Open Source framework: we're actually use a proprietary one with lots of components coming from symfony (goal is to port all to symfony sometime in the future).</p>

<p>Application has some design flaws so doesn't fit perfectly for Unit Testing. Anyway we've got a point where we can start and here comes some strage behaviours i can't solve.</p>

<p>All of our business methods rely on router object passed by Dependency injection at creation time.
Router exposes some methods to get and set variables like _SERVER, _GET, _POST that are cloned inside router itself (Use of global variable is prohibited by design).</p>

<p>In the following test i set SERVER and GET just before tested class instancing.. so i was expect to find their values correctly during test. 
Instead they are fully empty and, of course, test fail.</p>

<p>Any clue of what i'm doing wrong?</p>

<p>Thanks.</p>

<pre><code>/**
  * Test external class with valid UUID
  * 
  */
public function testGetClassPermissionExternal() {
    $TEST_SERVER_DATA = array(
        'REQUEST_URI' =&gt; 'https://sviluppo.pardgroup.com/test',
        'SERVER_PORT' =&gt; 443,
        'SERVER_NAME' =&gt; 'sviluppo.pardgroup.com'
    );
    // Due to bad design superglobal $_SERVER need to be fullfilled.
    $_SERVER = $TEST_SERVER_DATA;
    $this-&gt;router-&gt;setSERVER($TEST_SERVER_DATA);

    $TEST_POST_DATA = array('uuid' =&gt; self::$UUID);
    $this-&gt;router-&gt;setGET($TEST_POST_DATA);

    $this-&gt;class = \permission::getInstace($this-&gt;router);

    $test_class = array(""permissionTest/external"");
    $this-&gt;assertFalse($this-&gt;invokeMethod($this-&gt;class, ""getClassPermission"", $test_class));
}
</code></pre>
",https://stackoverflow.com/questions/44407490/phpunit-object-cloned,"['phpunit', 'php-7.1']",71,FALSE,0,0
assert.deepPartiallyEqual function for asymmetric assertion of two objects,"<p>I'm having a hard time finding good names here, but i'll describe what I want:</p>

<p>An assertion function such as nodes <code>assert.deepEqual(obj1, obj2)</code> but instead of recursively comparing <code>obj1</code> with <code>obj2</code> it should have a signature like so: <code>deepPartiallyEqual(spec, obj)</code> and just check that <code>spec</code> ""fits"" in <code>obj</code> or that <code>obj</code> ""conforms"" with <code>spec</code> if you wish. (Maybe a good comparison is <a href=""http://ramdajs.com/docs/#whereEq"" rel=""nofollow noreferrer"">ramdas whereEq</a> but it's shallow)</p>

<p><em>(The context of the question is unit-testing)</em></p>

<p>Example (pass):</p>

<pre><code>spec = {user: {name: 'Elin', age: 30}};
obj = {user: {id: 1, name: 'Elin', sex: 'f', age: 30}};
deepPartiallyEqual(spec, obj);
// would pass
</code></pre>

<p>Example (<strong>fail</strong>):</p>

<pre><code>spec = {user: {name: 'Cedric', age: 31}};
obj = {user: {id: 1, name: 'Elin', sex: 'f', age: 30}};
deepPartiallyEqual(spec, obj);

// should result in a failed test and an error output similar to:

AssertionError: ...
  + expected - actual

   {
      ""user"": {
  -    ""name"": ""Elin""
  +    ""name"": ""Cedric""
  -    ""age"": 30,
  +    ""age"": 31,
      }
   }
</code></pre>

<p>Does what I'm describing exist in any assertion library for javascript? On other platforms? <strong>...and if so, what is it called?</strong></p>

<hr>

<p>Motivation:</p>

<p>I'm asserting things on quite big objects but I'm only interested in testing that some of their (potentially nested) properties have the right values. So I only want to assert a subset of the objects keys. If I have to do a deepEquals my test file will be bloated with object literals with 90% of properties that I'm not really interested in testing anyway.</p>

<p>But at the same time, testing every property separately like so:</p>

<pre><code>assert.equals 'Elin', obj.user.name
assert.equals 30, obj.user.age
</code></pre>

<p>...is a bit painful because it's quite many props to test.</p>
",https://stackoverflow.com/questions/43347681/assert-deeppartiallyequal-function-for-asymmetric-assertion-of-two-objects,"['javascript', 'node.js', 'unit-testing', 'assert']",36,FALSE,0,1
"SelfPopulatingCache incumbent cache issue (Spring 4, EhCache 2.10.3)","<p>I have a project setup <em>(the snippets here are from a demo project I have created on GitHub <a href=""https://github.com/ashishmarwal/self-populating-cache-issue"" rel=""nofollow noreferrer"">https://github.com/ashishmarwal/self-populating-cache-issue</a>)</em> where a raw eh-cache cache is declared in the ehcache config (ehcache.xml). </p>

<pre><code>&lt;cache name=""alphabet-description-cache""
       eternal=""false""
       maxElementsInMemory=""1000""
       memoryStoreEvictionPolicy=""LRU""
       overflowToDisk=""false""
       timeToLiveSeconds=""300""
       timeToIdleSeconds=""300"" /&gt;
</code></pre>

<p>Spring bean descriptor then uses that raw cache to create a decorated (SelfPopulatingCache) using a CacheEntryFactory:
    
        
        
        
        
    </p>

<pre><code>&lt;bean id=""springCacheManager"" class=""org.springframework.cache.ehcache.EhCacheCacheManager""&gt;
    &lt;property name=""cacheManager"" ref=""cacheManager""/&gt;
&lt;/bean&gt;

&lt;!--Creating a decorated cache instance using the raw cache cinfigured in ehcache.xml --&gt;
&lt;bean id=""alphabetDescriptionCache"" class=""org.springframework.cache.ehcache.EhCacheFactoryBean""&gt;
    &lt;property name=""cacheManager"" ref=""cacheManager""/&gt;
    &lt;property name=""cacheName"" value=""alphabet-description-cache""/&gt;
    &lt;property name=""cacheEntryFactory"" ref=""alphabetDescriptionCacheEntryFactory""/&gt;
&lt;/bean&gt;

&lt;bean id=""alphabetDescriptionCacheEntryFactory"" class=""com.marwals.ashish.issues.selfpopulatingcache.AlphabetDescriptionCacheEntryFactory"" /&gt;
</code></pre>

<p>We also have a test-context.xml which is used for unit testing and declares a cacheManager as well as the decorated cache (in my perspective I have given different names to these cache managers):</p>

<pre><code>&lt;bean id=""cacheManager"" class=""org.springframework.cache.ehcache.EhCacheManagerFactoryBean""&gt;
    &lt;property name=""cacheManagerName"" value=""self-populating-cache-issue-demo-test""/&gt;
    &lt;property name=""shared"" value=""true""/&gt;
    &lt;property name=""acceptExisting"" value=""false""/&gt;
    &lt;property name=""configLocation"" value=""classpath:/ehcache.xml""/&gt;
&lt;/bean&gt;

&lt;bean id=""springCacheManager"" class=""org.springframework.cache.ehcache.EhCacheCacheManager""&gt;
    &lt;property name=""cacheManager"" ref=""cacheManager""/&gt;
&lt;/bean&gt;

&lt;bean id=""alphabetDescriptionCache"" class=""org.springframework.cache.ehcache.EhCacheFactoryBean""&gt;
    &lt;property name=""cacheManager"" ref=""cacheManager""/&gt;
    &lt;property name=""cacheName"" value=""alphabet-description-cache""/&gt;
    &lt;property name=""cacheEntryFactory"" ref=""alphabetDescriptionCacheEntryFactory""/&gt;
&lt;/bean&gt;

&lt;bean id=""alphabetDescriptionCacheEntryFactory"" class=""com.marwals.ashish.issues.selfpopulatingcache.AlphabetDescriptionCacheEntryFactory"" /&gt;
</code></pre>

<p>The problem here is that if I have two different tests each loading either the main or the test-context bean descriptor, I run into an incumbent cache issue:</p>

<pre><code>    Error creating bean with name 'alphabetDescriptionCache' defined in class path resource [test-context.xml]: Invocation of init method failed; 
nested exception is net.sf.ehcache.CacheException: Cannot replace alphabet-description-cache It does not equal the incumbent cache.
</code></pre>

<p>Any ideas what could be wrong here? Debugging the code reveals that I have two different cache instance for the same raw cache which is then raised as an error by EhCache's cache manager.</p>

<p>I have created a git repo demonstrating this problem:
<a href=""https://github.com/ashishmarwal/self-populating-cache-issue"" rel=""nofollow noreferrer"">https://github.com/ashishmarwal/self-populating-cache-issue</a></p>

<p>Thanks!!!</p>
",https://stackoverflow.com/questions/43555230/selfpopulatingcache-incumbent-cache-issue-spring-4-ehcache-2-10-3,"['java', 'spring', 'caching', 'ehcache']",628,TRUE,0,1
Graphaware TimeTree procedures in unit test using embedded db,"<p>UPDATE: I found some similar test in neo4j timetree source but using  GraphAwareIntegrationTest, which extends ServerIntegrationTest. So I tried creating a GraphDatabaseService  Bean for my test with the following, but still no luck. I get ""There is no procedure with the name <code>ga.timetree.events.attach</code> registered for this database instance.""  Is this not possible?</p>

<pre><code>@Bean
  public GraphDatabaseService graphDatabaseService() {
    GraphDatabaseService gds = new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().newGraphDatabase();
    Procedures procedures = (Procedures)((GraphDatabaseFacade) gds).getDependencyResolver().resolveDependency(Procedures.class);
    try {
        ClassPathProcedureUtils.registerAllProceduresAndFunctions(procedures);
    }catch (Exception ex) {
        log.error(""error"", ex);
    }
    return gds;
}
</code></pre>

<p>=====================</p>

<p>Similar to <a href=""https://stackoverflow.com/questions/40447328/testing-with-graphaware-timetree"">this issue</a> but I'm using Spring Boot 2, SDN5 with neo4j 3.2.5, graphaware and time tree. I have automatic event attachment setup, and i see events getting saved to the timetree, but I can't query using the procedure call using cypher. I get the error:</p>

<pre><code>Caused by: org.neo4j.ogm.exception.CypherException: Error executing Cypher; Code: Neo.ClientError.Procedure.ProcedureNotFound; Description: There is no procedure with the name `ga.timetree.range` registered for this database instance. Please ensure you've spelled the procedure name correctly and that the procedure is properly deployed.
at org.neo4j.ogm.drivers.embedded.request.EmbeddedRequest.executeRequest(EmbeddedRequest.java:176)
</code></pre>

<p>I don't see a TimeTreeProcedures class as answered in the linked issue. Is this still supported in embedded/unit testing? </p>

<p>Also, if it is supported, I would like to use a CustomRootTimeTree. Any help or pointer to cypher that I can define the custom root tree id in the procedure call would also be very much appreciated. Thanks for any help!</p>

<p>Test:</p>

<pre><code>    @Test
    public void testSingleTimeTree() {

        User user = new User(""alper@alper.com"", ""alper"", ""alper"");
        userRepository.save(user);
        Collection&lt;User&gt; found = userRepository.findByEmail(""alper@alper.com"");
        user = found.iterator().next();
        Workout workout = new Workout(new DateTime().plusMonths(2).getMillis());
        workoutRepository.save(workout);
        GraphUnit.printGraph(graphDb);
        Iterable&lt;Workout&gt; workouts = workoutRepository.findWorkouts();

        for(Workout workout1 : workouts) {
            log.info(""workout: {}"", workout1);
        }
    }
</code></pre>

<p>Repo (hard coded start/end for now):</p>

<pre><code>    public interface WorkoutRepository extends Neo4jRepository&lt;Workout, Long&gt; {

        @Query(""CALL ga.timetree.range({start: 1506826887000, end: 1512097287, create: false})"")
        Iterable&lt;Workout&gt; findWorkouts();

    }
</code></pre>

<p>pom.xml:</p>

<pre><code>  &lt;parent&gt;
      &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
      &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
      &lt;version&gt;2.0.0.BUILD-SNAPSHOT&lt;/version&gt;
      &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
  &lt;/parent&gt;

  &lt;properties&gt;
      &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;
      &lt;java.version&gt;1.8&lt;/java.version&gt;
      &lt;spring-data-releasetrain.version&gt;Kay-RELEASE&lt;/spring-data-releasetrain.version&gt;
      &lt;!--&lt;neo4j-ogm.version&gt;3.0.0&lt;/neo4j-ogm.version&gt;--&gt;
  &lt;/properties&gt;

  &lt;dependencyManagement&gt;
      &lt;dependencies&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;org.springframework.data&lt;/groupId&gt;
              &lt;artifactId&gt;spring-data-releasetrain&lt;/artifactId&gt;
              &lt;version&gt;${spring-data-releasetrain.version}&lt;/version&gt;
              &lt;scope&gt;import&lt;/scope&gt;
              &lt;type&gt;pom&lt;/type&gt;
          &lt;/dependency&gt;
      &lt;/dependencies&gt;
  &lt;/dependencyManagement&gt;

  &lt;dependencies&gt;
      &lt;dependency&gt;
          &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
          &lt;artifactId&gt;spring-boot-starter-data-neo4j&lt;/artifactId&gt;
      &lt;/dependency&gt;
      &lt;dependency&gt;
          &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
          &lt;artifactId&gt;spring-boot-starter-data-rest&lt;/artifactId&gt;
      &lt;/dependency&gt;
      &lt;dependency&gt;
          &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
          &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
      &lt;/dependency&gt;
      &lt;dependency&gt;
          &lt;groupId&gt;org.neo4j&lt;/groupId&gt;
          &lt;artifactId&gt;neo4j-ogm-embedded-driver&lt;/artifactId&gt;
          &lt;version&gt;${neo4j-ogm.version}&lt;/version&gt;
      &lt;/dependency&gt;
      &lt;dependency&gt;
          &lt;groupId&gt;org.neo4j&lt;/groupId&gt;
          &lt;artifactId&gt;neo4j&lt;/artifactId&gt;
          &lt;version&gt;3.2.5&lt;/version&gt;
          &lt;scope&gt;runtime&lt;/scope&gt;
      &lt;/dependency&gt;

      &lt;dependency&gt;
          &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
          &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
          &lt;scope&gt;test&lt;/scope&gt;
      &lt;/dependency&gt;

      &lt;!-- added by me --&gt;
      &lt;dependency&gt;
          &lt;groupId&gt;org.neo4j&lt;/groupId&gt;
          &lt;artifactId&gt;neo4j-kernel&lt;/artifactId&gt;
          &lt;version&gt;3.2.5&lt;/version&gt;
          &lt;type&gt;test-jar&lt;/type&gt;
      &lt;/dependency&gt;
      &lt;dependency&gt;
          &lt;groupId&gt;com.graphaware.neo4j&lt;/groupId&gt;
          &lt;artifactId&gt;graphaware-framework-embedded&lt;/artifactId&gt;
          &lt;version&gt;3.2.5.51&lt;/version&gt;
          &lt;type&gt;pom&lt;/type&gt;
      &lt;/dependency&gt;
      &lt;dependency&gt;
          &lt;groupId&gt;com.graphaware.neo4j&lt;/groupId&gt;
          &lt;artifactId&gt;timetree&lt;/artifactId&gt;
          &lt;version&gt;3.2.1.51.27&lt;/version&gt;
      &lt;/dependency&gt;
      &lt;dependency&gt;
          &lt;groupId&gt;org.neo4j&lt;/groupId&gt;
          &lt;artifactId&gt;neo4j-graphdb-api&lt;/artifactId&gt;
          &lt;version&gt;3.2.5&lt;/version&gt;
      &lt;/dependency&gt;
      &lt;dependency&gt;
          &lt;groupId&gt;org.neo4j&lt;/groupId&gt;
          &lt;artifactId&gt;neo4j-io&lt;/artifactId&gt;
          &lt;version&gt;3.2.5&lt;/version&gt;
          &lt;type&gt;test-jar&lt;/type&gt;
      &lt;/dependency&gt;
      &lt;dependency&gt;
          &lt;groupId&gt;com.graphaware.neo4j&lt;/groupId&gt;
          &lt;artifactId&gt;tests&lt;/artifactId&gt;
          &lt;version&gt;3.2.5.51&lt;/version&gt;
      &lt;/dependency&gt;
  &lt;/dependencies&gt;
</code></pre>
",https://stackoverflow.com/questions/46842076/graphaware-timetree-procedures-in-unit-test-using-embedded-db,"['java', 'unit-testing', 'spring-data', 'spring-data-neo4j', 'graphaware']",94,TRUE,0,1
How to unit test sql-stored steps in a camel route,"<p>I recently joined a project in which lots of autosys jobs are replaced with camel routes. most of the processing flows follow the same pattern:</p>

<ul>
<li>Read a file from a certain folder</li>
<li>Apply some deserialization of some sort into a java structure</li>
<li>Invoke a stored procedure or another based on some values included in the java structuure</li>
<li>Send the processing results to some third party consumer</li>
</ul>

<p>The easiest way to implement the stored procedure invoke was to use the <code>sql-stored</code> component. Let's just say I have this route:</p>

<pre><code>from(""file://d:/temp/in/?include=myFile*.csv"")
.process(""myHeaderSetter"")
.choice()
    .when(header(""myheader"")).to(""sql-stored:proc_1()?dataSource=#dataSource"")
    .otherwise().to(""sql-stored:proc_2()?dataSource=#dataSource"")
.end()
.to(""reportGenerator"")
.to(""file://d:temp/out/?fileName=report.txt"");
</code></pre>

<p>Each processor is very well unit tested but we want to make sure that the route logic goes as we expect. The stored procedures can take a while to execute and running the real route is not an option part of the unit testing so I need a way to test that the stored procedures are invoked without actually getting them to run.</p>

<p>So what would be a good approach to unit test a route like above.</p>

<p>Thank you in advance for your inputs</p>
",https://stackoverflow.com/questions/43626826/how-to-unit-test-sql-stored-steps-in-a-camel-route,"['apache-camel', 'camel-sql']",674,TRUE,0,1
How to create object from another object in Python unit test,"<p>I'm having trouble understanding unit testing in Python. I have an object, <code>retailer</code>, which creates another object, <code>deal</code>. <code>deal</code> refers to an attribute created in <code>retailer</code>, so I'm passing it a reference:</p>

<pre><code>class deal():
    def __init__(self, deal_container, parent):
</code></pre>

<p>The <code>deal_container</code> attribute also comes from <code>retailer</code>, which calls its own methods to create it.  So how do I create everything I need to easily make a <code>deal</code> object? </p>

<p>Do I have to create an instance of <code>retailer</code> in my unit test and then call the method in that object that creates <code>deal</code>? </p>

<p>Can I use FactoryBoy to create an instance of <code>retailer</code> and how do I include the method that creates <code>deal</code> in that object?</p>

<p>What's the best way to approach this?</p>

<p>Here's the unit test. I'm setting up the <code>soup_obj</code> I need to give deal:</p>

<pre><code>class TestExtractString(TestCase):
    fixtures = ['deals_test_data.json']

    def setUp(self):
        with open('/home/danny/PycharmProjects/askarby/deals/tests/BestBuyTest.html', 'r') as myfile:
            text = myfile.read().replace('\n', '')
        self.soup_obj = bs4.BeautifulSoup(text,""html.parser"")
        self.deal = self.soup_obj.find_all('div',attrs={'class':'list-item'})[0]

    def test_extracts_title(self):
        z = Retailer.objects.get(pk=1)
        s = dealscan.retailer(z)
        d = dealscan.deal(self.deal,s)
        result = d.extract_string(self.deal,'title')
</code></pre>

<p>and here's the relevant bit of the <code>deal</code> class in <code>dealscan</code>. There's a <code>retailer</code> class that creates a <code>deal</code>, but I haven't even written the bit in <code>retailer</code> that creates <code>deal</code> yet. I'm hoping I can mock the bits I need for <code>deal</code> without having to invoke <code>retailer</code> at all, but then how do I deal with the fact that <code>deal</code> references <code>retailer</code>?</p>

<pre><code>class deal():
    def __init__(self, deal_container, parent):
        '''
        Initializes deal object
        Precondition: 0 &gt; price
        Precondition: 0 &gt; old_price
        Precondition: len(currency) = 3

        :param deal_container: obj
        '''
        self.css = self.parent.css

        self.deal_container = deal_container
        self.parent = parent
        self.title = self.extract_string('title')
        self.currency = self.parent.currency
        self.price = self.extract_price('price')
        self.old_price = self.extract_price('old_price')
        self.brand = self.extract_string('brand')
        self.image = self.extract_image('image')
        self.description = self.extract_string('description')

        #define amazon category as clearance_url
        #define all marketplace deals

    def __str__(self):
        return self.title

    def extract_string(self, element, deal):
        '''

        :param object deal: deal object to extract title from
        :param string element: element to look for in CSS
        :return string result: result of string extract from CSS
        '''
        tag = self.css[element]['tag']
        attr = self.css[element]['attr']
        name = self.css[element]['name']
        result = deal.find(tag, attrs={attr: name})
        if result:
            if element == 'title':
                return result.text
            elif element == 'price':
                result = self.extract_price(result).text
                if result:
                    return result
            elif element == 'image':
                result = self.extract_image(result)

        return False
</code></pre>
",https://stackoverflow.com/questions/46633842/how-to-create-object-from-another-object-in-python-unit-test,"['python', 'factory', 'factory-boy']",1672,TRUE,0,1
How to simulate on `onChange` event that updates the state,"<p>I'm writing an application in React and I'm unit testing this with Jest and Enzyme.</p>

<p>I have a very simple component that represents an input field, which contains the following code:</p>

<pre><code>// 'Container' component definition.
class Container extends React.Component&lt;containerProps, containerState&gt; {
  static defaultProps = { };
  state = {
    hasValue: false
  };

  constructor(props: containerProps) {
    super(props);

    // Bind all the event handlers for the component.
    (this: any).onChange = this.onChange.bind(this);
  }

  onChange(event: MouseEvent) : void {
    this.setState(
      {
        hasValue: (event.target: window.HTMLInputElement).value !== ''
      }
    );

    // Prevent a default browser event from happening.
    event.preventDefault();
  }

  createComponentProps(): componentProps {
    return {
      cssClass: this.createComponentCssClass()
    };
  }

  // Create the CSS class to pass to the component.
  createComponentCssClass(): string {
    let className = '';

    if (this.state.hasValue) { className = className !== '' ? className + 'value' : 'value'; }
    if (this.props.errorMessage &amp;&amp; this.props.errorMessage !== '') {
      className = className !== '' ? className + ' error' : 'error';
    }

    // Return the CSS class to apply to the component.
    return className;
  }

  // Renders the 'Container' component.
  render(): React$Element&lt;any&gt; {
    return (
      &lt;Component {...this.createComponentProps()} /&gt;
    );
  }
}
</code></pre>

<p>So, it's a fairly simple component.
Now, when the contents of the input field are changed, a state change occurs which forces a different CSS class to be applied to the component.</p>

<p>I can confirm that this is working since it's working in the browser as intended.</p>

<p>Now, I'm writing a unit test to verify that the className <code>value</code> is passed to the component using the following code:</p>

<pre><code>it('Passes down the \'cssClass\' property to the \'Input Field\' Component.', () =&gt; {
  // Act.
  const wrapper = mount(
    &lt;InputFieldContainer primaryThemeColor=""TEAL"" accentThemeColor=""PINK"" useAccentColor={true} /&gt;
  );
  wrapper.find('input').simulate('change', { target: { value: 'value' }});
  wrapper.update();

  // Assert.
  expect(wrapper.find(InputFieldComponent).props().cssClass).toEqual('value');
});
</code></pre>

<p>Thus, I'm rendering the component, I simulate a change event, and I check the CSS class property of the component, however, it's an empty string. It seems it didn't update regarding the state change (but only in unit tests).</p>

<p>Reading the state in Jest, using <code>console.log(wrapper.state())</code> gives me a JSON object saying <code>hasValue: true</code>, so the state is updated, but even after calling <code>wrapper.update()</code>, the CSS class does not seem to be passed.</p>

<p>What am I missing here?</p>

<p>Kind regards</p>
",https://stackoverflow.com/questions/46539302/how-to-simulate-on-onchange-event-that-updates-the-state,"['javascript', 'reactjs', 'unit-testing']",640,FALSE,0,1
Mockito unit test BaseObserver and static method with context,"<p>I am facing with Unit testing for the first time and I would like to know what is the best approach for the following scenario.
I am using Mockito for the tests. The following test is for logic(Presenter) layer and I am trying to verify certain behaviors of the view.</p>

<p>App classes</p>

<p><strong>The method of the Presenter that need to be include in the test</strong>:</p>

<pre><code>public void loadWeather() {

CityDetailsModel selectedCity = getDbHelper().getSelectedCityModel();

if (selectedCity != null) {
  getCompositeDisposableHelper().execute(
      getApiHelper().weatherApiRequest(selectedCity.getLatitude(), selectedCity.getLongitude()),
      new WeatherObserver(getMvpView()));
} else {
  getMvpView().showEmptyView();
}
</code></pre>

<p>}</p>

<p><strong>WeatherObserver</strong>:</p>

<pre><code> public class WeatherObserver extends BaseViewSubscriber&lt;DayMvpView, WeatherResponseModel&gt; {

   public WeatherObserver(DayMvpView view) {
      super(view);
    }

    @Override public void onNext(WeatherResponseModel weatherResponseModel) {
      super.onNext(weatherResponseModel);

      if (weatherResponseModel.getData().isEmpty()) {
        getMvpView().showEmptyView();
      } else {
        getMvpView().showWeather(weatherResponseModel.getData());
      }
    }
  }
</code></pre>

<p><strong>BaseViewSubscriber (Default DisposableObserver base class to be used whenever we want default error handling)</strong>:</p>

<pre><code> public class BaseViewSubscriber&lt;V extends BaseMvpView, T&gt; extends DisposableObserver&lt;T&gt; {

  private ErrorHandlerHelper errorHandlerHelper;
  private V view;

  public BaseViewSubscriber(V view) {
    this.view = view;
    errorHandlerHelper = WeatherApplication.getApplicationComponent().errorHelper();
  }

  public V getView() {
    return view;
  }

  public boolean shouldShowError() {
    return true;
  }

  protected boolean shouldShowLoading() {
    return true;
  }

  @Override public void onStart() {
    if (!AppUtils.isNetworkAvailable(WeatherApplication.getApplicationComponent().context())) {
      onError(new InternetConnectionException());
      return;
    }

    if (shouldShowLoading()) {
      view.showLoading();
    }
    super.onStart();
  }

  @Override public void onError(Throwable e) {
    if (view == null) {
      return;
    }

    if (shouldShowLoading()) {
      view.hideLoading();
    }

    if (shouldShowError()) {
      view.onError(errorHandlerHelper.getProperErrorMessage(e));
    }
  }

  @Override public void onComplete() {
    if (view == null) {
      return;
    }

    if (shouldShowLoading()) {
      view.hideLoading();
    }
  }

  @Override public void onNext(T t) {
    if (view == null) {
      return;
    }
  }
}
</code></pre>

<p><strong>CompositeDisposableHelper (CompositeDisposable helper class)</strong>:</p>

<pre><code>public class CompositeDisposableHelper {

  public CompositeDisposable disposables;
  public TestScheduler testScheduler;

  @Inject public CompositeDisposableHelper(CompositeDisposable disposables) {
    this.disposables = disposables;
    testScheduler = new TestScheduler();
  }

  public &lt;T&gt; void execute(Observable&lt;T&gt; observable, DisposableObserver&lt;T&gt; observer) {
    addDisposable(observable.subscribeOn(testScheduler)
        .observeOn(testScheduler)
        .subscribeWith(observer));
  }

  public void dispose() {
    if (!disposables.isDisposed()) {
      disposables.dispose();
    }
  }

  public TestScheduler getTestScheduler() {
    return testScheduler;
  }

  public void addDisposable(Disposable disposable) {
    disposables.add(disposable);
  }
}
</code></pre>

<p><strong>My test</strong>:</p>

<pre><code>  @Test public void loadSuccessfully() {
    WeatherResponseModel responseModel = new WeatherResponseModel();
    List&lt;WeatherModel&gt; list = new ArrayList&lt;&gt;();
    list.add(new WeatherModel());
    responseModel.setData(list);

    CityDetailsModel cityDetailsModel = new CityDetailsModel();
    cityDetailsModel.setLongitude("""");
    cityDetailsModel.setLatitude("""");

    when(dbHelper.getSelectedCityModel()).thenReturn(cityDetailsModel);

    when(apiHelper.weatherApiRequest(anyString(), anyString())).thenReturn(
        Observable.just(responseModel));

    dayPresenter.loadWeather();

    compositeDisposableHelper.getTestScheduler().triggerActions();

    verify(dayMvpView).showWeather(list);
    verify(dayMvpView, never()).showEmptyView();
    verify(dayMvpView, never()).onError(anyString());
  }
</code></pre>

<p>When I try to run the test, I get NullPointer, because <code>new WeatherObserver(getMvpView())</code> is called, and in the <code>BaseViewSubscriber</code> errorHandlerHelper is null because getApplicationCopomnent is null.
As well NullPointer is thrown in the static method <code>AppUtils.isNetworkAvailable()</code> for the same reason.</p>

<p>When I try to comment these lines, the test is OK.</p>

<p><strong>My questions are:</strong></p>

<ul>
<li>Should I use Dagger for the Unit test as well or? If yes please give
me example for my test. </li>
<li>Should I use PowerMockito for the static    method
<code>AppUtils.isNetworkAvailable()</code>? If yes, is it ok just because    of
this method to use PowerMockito Runner<br>
<code>@RunWith(PowerMockRunner.class)</code>?</li>
</ul>
",https://stackoverflow.com/questions/43070173/mockito-unit-test-baseobserver-and-static-method-with-context,"['android', 'unit-testing', 'mockito', 'powermockito', 'rx-java2']",534,TRUE,0,1
How to unit test with ContentValues always null vs Method getAction in android.content.Intent not mocked,"<p>Recently I've been unit testing doing an update using the latest android studio, which is 3 beta 6, and I've found that even when I initialize a <code>ContentValues</code> it is null. I need it to actually be a value / init-ed <code>ContentValues</code>.</p>

<p>my gradle file:</p>

<pre><code>apply plugin: 'com.android.application'

android {

    compileSdkVersion 26
    buildToolsVersion ""26.0.1""
    defaultConfig {
        applicationId ""com.cubedelement.soundplanner""
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName ""1.0""
        testInstrumentationRunner ""org.mockito.testInstrumentationRunner""
        vectorDrawables.useSupportLibrary = true
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        targetCompatibility 1.8
        sourceCompatibility 1.8
    }

    testOptions {
        unitTests.returnDefaultValues = true
    }
}
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:palette-v7:26.1.0'
    androidTestImplementation('com.android.support.test.espresso:espresso-core:3.0.0', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    implementation 'com.google.dagger:dagger-android:2.11'
    implementation 'com.google.dagger:dagger-android-support:2.11' // if you use the support libraries
    annotationProcessor 'com.google.dagger:dagger-android-processor:2.11'
    annotationProcessor 'com.google.dagger:dagger-compiler:2.11'

    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test:rules:1.0.1'
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.google.code.gson:gson:2.8.0'
    testImplementation 'junit:junit:4.12'
    testImplementation 'org.powermock:powermock-api-mockito2:1.7.0'
    testImplementation 'org.powermock:powermock-module-junit4:1.6.5'
    implementation 'com.android.support:design:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'org.mockito:mockito-core:2.8.47'
    androidTestImplementation 'org.mockito:mockito-core:2.8.47'
}
</code></pre>

<p>but wait, there's more! </p>

<p>So I've also got a simple test which is:</p>

<pre><code>import android.content.ContentValues;

public class Test {
    @Test public void ContentValuesShouldNotBeNull(){
         ContentValues v = new ContentValues();
         assertEquals(v, null) // this is true, but I don't want it to be, help!
    }
}
</code></pre>

<p>here is the view in android studio
<a href=""https://i.stack.imgur.com/GhmR8.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/GhmR8.jpg"" alt=""android beta showing null for content values""></a></p>

<p>So I've tried a default gradle file and found that contentvalues is not null.</p>

<p>here is the file:</p>

<pre><code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.1'
    defaultConfig {
        applicationId ""com.example.kelly_vernon.myapplication""
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName ""1.0""
        testInstrumentationRunner ""android.support.test.runner.AndroidJUnitRunner""
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
</code></pre>

<p>I honestly don't understand gradle a lot at this point, but I do know that my config, which is a bunch of ideas to support dagger and other values is not great by any stretch. </p>

<p>After trying other things, I found this to be the culprit:</p>

<pre><code>testOptions {
    unitTests.returnDefaultValues = true
}
</code></pre>

<p>I figured out the reason why I had this. I have a test in another area that is testing intents, and I need the default.</p>

<p>Is there a way to restrict this to exclude <code>ContentValues</code> or the inverse to not include the <code>Intent</code>?</p>
",https://stackoverflow.com/questions/46383129/how-to-unit-test-with-contentvalues-always-null-vs-method-getaction-in-android-c,"['android', 'unit-testing', 'android-gradle-plugin', 'android-sqlite', 'junit4']",1363,TRUE,0,2
Docker Compose: Mock external services,"<p>I have the following situation: </p>

<p>My application consists of a single web service that calls an 
external API (say, some SaaS service, ElasticSearch or so). For non-unit-testing purposes we want to control the external service and later also inject faults. The application and the ""mocked"" API are dockerized and 
now I want to use <code>docker-compose</code> to spin all containers up. </p>

<p>Because the application has several addresses hardcoded (e.g. the hostname of external services) I cannot change them and need to work around. </p>

<p>The <code>service</code> container makes a call to <code>http://external-service.com/getsomestuff</code>.</p>

<p>My idea was to use some features that are provided by docker to reroute all outgoing traffic to the external <code>http://external-service.com/getsomestuff</code> to the mock container without changing the URL. </p>

<p>My <code>docker-compose.yaml</code> looks like:</p>

<pre><code>version: '2'
services:
  service:
    build: ./service
    container_name: my-service1
    ports:
      - ""5000:5000""
    command: /bin/sh -c ""python3 app.py""

  api:
    build: ./api-mock
    container_name: my-api-mock
    ports:
      - ""5001:5000""
    command: /bin/sh -c ""python3 app.py""
</code></pre>

<p>Finally, I have a driver that just does the following:</p>

<pre><code>curl -XGET localhost:5000/
curl -XPUT localhost:5001/configure?delay=10
curl -XGET localhost:5000/
</code></pre>

<p>where the second <code>curl</code> just sets the delay in the mock to 10 seconds.</p>

<p>There are several options I have considered:</p>

<ul>
<li>Using <code>iptables</code>-fu (would require modifying Dockerfiles to install it)</li>
<li>Using docker networks (this is really unclear to me)</li>
</ul>

<p>Is there any simple option to achieve what I want?</p>

<p><em>Edit</em>:</p>

<p>For clarity, here is the relevant part of the <code>service</code> code:</p>

<pre><code>import requests

@app.route('/')
def do_stuff():
    r = requests.get('http://external-service.com/getsomestuff')
    return process_api_response(r.text())
</code></pre>
",https://stackoverflow.com/questions/42964666/docker-compose-mock-external-services,"['networking', 'docker']",3295,TRUE,6,3
Use an Android Library (AAR) as dependency for a Java (Jar) Project with Gradle,"<p>The Java Jar <code>build.gradle</code> module:</p>

<pre><code>apply plugin: 'java'

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'junit:junit:4.12'

    // rx
    compile ""io.reactivex.rxjava2:rxjava:2.0.4""
    compile ""io.reactivex.rxjava2:rxandroid:2.0.1""
}

sourceCompatibility = ""1.8""
targetCompatibility = ""1.8""
</code></pre>

<p>This Jar is supposed to be a library used as an utility library for unit testing android projects:</p>

<pre><code>apply plugin: 'com.android.application'

android {
    // ...
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    // test
    testCompile 'junit:junit:4.12'
    testCompile project(':test-utils')

    // ... other non-test dependencies here (including rx)
}
</code></pre>

<p>This include:</p>

<pre><code>    testCompile project(':test-utils')
</code></pre>

<p>fails with:</p>

<blockquote>
  <p>Error:Module 'my-android-app:test-utils:unspecified' depends on one or
  more Android Libraries but is a jar</p>
</blockquote>

<p>Which is because <code>RxAndroid</code> is an Android .aar library.</p>

<p>I need RxAndroid in my test utility module because one of the things the module provide is a junit <code>MethodRule</code> for setting up Rx Schedulers through the <code>@Rule</code> annotation and other custom annotations in <code>@Test</code> methods.</p>

<p>This is needed because RxAndroid AndroidScheduler use Android <code>Handler</code> / <code>Looper</code> class, which are part of the Android framework and are not available in unit tests. The Android Scheduler can be replaced using <code>RxAndroidPlugins</code>.</p>

<p>Which means I only need the JAR part of the RxAndroid AAR (<code>classes.jar</code> inside rxandroid artifact).</p>

<p>Is there a way to tell gradle I only need the Java part of the AAR as dependency?</p>

<p>I do not consider a solution manually extracting the <code>classes.jar</code> from the AAR and including it as a dependency. That's a workaround.</p>

<p>This Java test library is supposed to be shared among my projects and I'm currently copying the <code>MethodRule</code> class in every of my projects which is far from ideal.</p>
",https://stackoverflow.com/questions/41954557/use-an-android-library-aar-as-dependency-for-a-java-jar-project-with-gradle,"['android', 'unit-testing', 'gradle', 'rx-android']",1918,FALSE,6,0
Java Reflection - IllegalAccessException on &quot;set&quot; if preceded by &quot;get&quot; operation,"<p>I was trying to change the value of a <code>private static final</code> field using reflection (yes, that's probably a very bad idea to begin with, I know).
And, well, for the most part it works fine using following code:</p>

<pre><code>import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class A {

    public static void main(String[] args) throws ReflectiveOperationException {
        System.out.println(""Before :: "" + B.get());
        Field field = B.class.getDeclaredField(""arr"");
        field.setAccessible(true);
        // System.out.println(""Peek   :: "" + ((String[]) field.get(null))[0]);
        Field modifiersField = Field.class.getDeclaredField(""modifiers"");
        modifiersField.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() &amp; ~Modifier.FINAL);
        field.set(null, new String[] { ""Good bye, World!"" });
        System.out.println(""After  :: "" + B.get());
    }
}

class B {
    private static final String[] arr = new String[] { ""Hello, World!"" };

    public static String get() {
        return arr[0];
    }
}
</code></pre>

<p>Which prints as expected:</p>

<pre><code>Before :: Hello, World!
After  :: Good bye, World!
</code></pre>

<p>Problems arise when I try to <code>get</code> the field value via reflection prior to <code>set</code>ting it.
That is, if I uncomment the commented line in above sample, I get the following:</p>

<pre><code>Before :: Hello, World!
Peek   :: Hello, World!
Exception in thread ""main"" java.lang.IllegalAccessException: Can not set static final [Ljava.lang.String; field B.arr to [Ljava.lang.String;
        at sun.reflect.UnsafeFieldAccessorImpl.throwFinalFieldIllegalAccessException(UnsafeFieldAccessorImpl.java:76)
        at sun.reflect.UnsafeFieldAccessorImpl.throwFinalFieldIllegalAccessException(UnsafeFieldAccessorImpl.java:80)
        at sun.reflect.UnsafeQualifiedStaticObjectFieldAccessorImpl.set(UnsafeQualifiedStaticObjectFieldAccessorImpl.java:77)
        at java.lang.reflect.Field.set(Field.java:764)
        at A.main(A.java:14)
</code></pre>

<p>Why is this happening??
I tried to set again the <code>accessible</code> flag after the call to <code>get</code> but it doesn't help.
I tried many other things that don't seem to help either...</p>

<p>Thanks for your help!</p>

<hr>

<p><strong>Edit</strong>: there is an element of answer in <a href=""https://stackoverflow.com/questions/2474017/using-reflection-to-change-static-final-file-separatorchar-for-unit-testing/2474242#2474242"">Using reflection to change static final File.separatorChar for unit testing?</a> (see ""<strong>Important update</strong>"" by @Rogério).</p>

<blockquote>
  <p><strong>Important update</strong>: the above solution <em>does not</em> work in all cases. If the field is made accessible and read through Reflection before it gets reset, an <code>IllegalAccessException</code> is thrown. It fails because the Reflection API creates internal <code>FieldAccessor</code> objects which are cached and reused (see the java.lang.reflect.Field#acquireFieldAccessor(boolean) implementation).
  Example test code which fails:</p>

<pre><code>Field f = File.class.getField(""separatorChar""); f.setAccessible(true); f.get(null);
// call setFinalStatic as before: throws IllegalAccessException
</code></pre>
</blockquote>

<p>Sadly, it doesn't say anything about how to work around it... How do I ""reset"" the field?</p>
",https://stackoverflow.com/questions/47980223/java-reflection-illegalaccessexception-on-set-if-preceded-by-get-operation,"['java', 'reflection']",2429,TRUE,5,1
Where to write tests for a Frontend/Backend application?,"<p>I want to write a web application with a simple Frontend-Backend(REST API) architecture.
It's not clear to me where and how to write tests.</p>

<p>Frontend:  should I write tests mocking API responses and testing only UX/UI?
Backend: should I write here API call testing and eventually more fine grained unit testing on classes?</p>

<p>But in this way I'm afraid that Frontend testing is not aware of real API response (because it's mocking independently from the backend).
On the other side if I don't mock API response and use real response from backend, how can the Frontend client prepare the DB to get the data he wants?</p>

<p>It seems to me that I need 3 kind of testing types:
- UX/UI testing: the Frontend is working with a set of mock responses
- API testing: the API is giving the correct answers given a set of data
- Integration testing: The Frontend is working by calling really the backend with a set of data (generated by who?).</p>

<p>There are framework or tools to make this as painless as possible?
It seems to me very complicated (if API spec changes I must rewrite a lot of tests)</p>

<p>any suggestion welcome</p>
",https://stackoverflow.com/questions/42747791/where-to-write-tests-for-a-frontend-backend-application,"['rest', 'testing', 'frontend', 'backend']",3476,TRUE,5,2
Unit testing Cloud Functions for Firebase: what&#39;s the &quot;right way&quot; to test/mock `transaction`s with sinon.js,"<p>Man, this firebase unit testing is really kicking my butt. </p>

<p>I've gone through <a href=""https://firebase.google.com/docs/functions/unit-testing"" rel=""nofollow noreferrer"">the documentation</a> and read through the examples that they provide, and have gotten some of my more basic Firebase functions unit tested, but I keep running into problems where I'm not sure how to verify that the <code>transactionUpdated</code> function passed along to the refs <code>.transaction</code> is correctly updating the <code>current</code> object.  </p>

<p>My struggle is probably best illustrated with their <a href=""https://github.com/firebase/functions-samples/blob/master/child-count/functions/index.js"" rel=""nofollow noreferrer""><code>child-count</code> sample code</a> and a poor attempt I made at writing a unit test for it.</p>

<p>Let's say my function that I want to unit test does the following (taken straight from that above link):</p>

<pre><code>// count.js
exports.countlikechange = functions.database.ref('/posts/{postid}/likes/{likeid}').onWrite(event =&gt; {
      const collectionRef = event.data.ref.parent;
      const countRef = collectionRef.parent.child('likes_count');

      // ANNOTATION: I want to verify the `current` value is incremented
      return countRef.transaction(current =&gt; {
        if (event.data.exists() &amp;&amp; !event.data.previous.exists()) {
          return (current || 0) + 1;
        }
        else if (!event.data.exists() &amp;&amp; event.data.previous.exists()) {
          return (current || 0) - 1;
        }
      }).then(() =&gt; {
        console.log('Counter updated.');
      });
    });
</code></pre>

<p>Unit Test Code:</p>

<pre><code>const chai = require('chai');
const chaiAsPromised = require(""chai-as-promised"");
chai.use(chaiAsPromised);
const assert = chai.assert;
const sinon = require('sinon');

describe('Cloud Functions', () =&gt; {
  let myFunctions, functions;

  before(() =&gt; {
    functions = require('firebase-functions');
    myFunctions = require('../count.js');
  });

  describe('countlikechange', () =&gt; {
    it('should increase /posts/{postid}/likes/likes_count', () =&gt; {
      const event = {
        // DeltaSnapshot(app: firebase.app.App, adminApp: firebase.app.App, data: any, delta: any, path?: string);
        data: new functions.database.DeltaSnapshot(null, null, null, true)
      }

      const startingValue = 11
      const expectedValue = 12

      // Below code is misunderstood piece.  How do I pass along `startingValue` to the callback param of transaction
      // in the `countlikechange` function, and spy on the return value to assert that it is equal to `expectedValue`?
      // `yield` is almost definitely not the right thing to do, but I'm not quite sure where to go.
      // How can I go about ""spying"" on the result of a stub,
      // since the stub replaces the original function?
      // I suspect that `sinon.spy()` has something to do with the answer, but when I try to pass along `sinon.spy()` as the yields arg, i get errors and the `spy.firstCall` is always null. 
      const transactionStub = sinon.stub().yields(startingValue).returns(Promise.resolve(true))

      const childStub = sinon.stub().withArgs('likes_count').returns({
        transaction: transactionStub
      })
      const refStub = sinon.stub().returns({ parent: { child: childStub }})

      Object.defineProperty(event.data, 'ref', { get: refStub })

      assert.eventually.equals(myFunctions.countlikechange(event), true)
    })
  })
})
</code></pre>

<p>I annotated the source code above with my question, but I'll reiterate it here.</p>

<p>How can I verify that the <a href=""https://firebase.google.com/docs/reference/js/firebase.database.Reference#transaction"" rel=""nofollow noreferrer""><code>transactionUpdate</code> callback</a>, passed to the transaction stub, will take my <code>startingValue</code> and mutate it to <code>expectedValue</code> and then allow me to observe that change and assert that it happened.</p>

<p>This is probably a very simple problem with an obvious solution, but I'm very new to testing JS code where everything has to be stubbed, so it's a bit of a learning curve... Any help is appreciated.</p>
",https://stackoverflow.com/questions/44055553/unit-testing-cloud-functions-for-firebase-whats-the-right-way-to-test-mock,"['unit-testing', 'firebase', 'sinon', 'google-cloud-functions', 'sinon-chai']",3450,TRUE,4,1
How to use moq to unit test an application that consumes asmx service in .NET,"<p>I have a web application that sends an sms by consuming an ASMX service(which is now production and working fine), however I now need to unit test this application consumes the asmx service, below is the specific action method I'm interested in unit testing </p>

<pre><code>public ActionResult CreateSms(SendSMSViewModel tblSend)
{
    if (ModelState.IsValid)
    {
        if (_dbManager.SendSMS(tblSend.CellNumber, tblSend.Message, User.Identity.Name))
        {
            TempData[""Success""] = ""Message was successfully sent"";
        }
        else
        {
            TempData[""Error""] = ""An error occured while sending the message"";
        }
    }

    return RedirectToAction(""CreateSms"");
}
</code></pre>

<p>So this action method receives a view model as parameter, this vmodel has 2 properties(cell number, message) and there is also user who is sending the sms. Now in my unit test or integration(apologies I also happen to confuse the two) I have the following code, this first part I am just trying to mock the method(s) </p>

<pre><code>public DatabaseManagerTest()
{
    Mock&lt;IDatabaseManager&gt; moqDB = new Mock&lt;IDatabaseManager&gt;();

    //Setup send sms test
    moqDB.Setup(md =&gt; md.SendSMS(""0734233173"", ""Test message"", ""Ronny.Mahlangu"")).Returns(true);

    this._mockDatabaseManager = moqDB.Object;
}
</code></pre>

<p>and below is the actual test method </p>

<pre><code>public void TestSendSms()
{
    bool results = this._mockDatabaseManager.SendSMS(""0734233173"", ""Test message"", ""Ronny.Mahlangu"");
    Assert.IsTrue(results);
}
</code></pre>

<p>My testing seem to pass, however I also want to unit test the action method itself, in this case I'm only testing whether sms sends successfully, how do I go about testing the action method itself, surely I need to mock the asmx service but I am blank</p>

<p>Also note that the <code>SendSMS</code> method comes from a class named <code>DatabaseManager</code>, which is where the asmx methods are being invoked, here is the peace of code from that class </p>

<pre><code>public bool SendSMS(string cellNumber, string message, string logonName) {    
    if(string.IsNullOrWhiteSpace(cellNumber))
    {
        throw new ArgumentNullException(""cell phone number is null"");
    }
    if(string.IsNullOrWhiteSpace(message))
    {
        throw new ArgumentNullException(""Sms message is null"");
    }

    using (SMSService.SendSmsSoapClient sms = new SMSService.SendSmsSoapClient())
    {
        if (sms.SendDirect(cellNumber, message, ConfigurationManager.AppSettings[""costCentre""], userLogonName, ConfigurationManager.AppSettings[""source""]) == SMSService.Status.Successful)
        {
            SaveSmsDetails(cellNumber, message, userLogonName);
            return true;
        }
    }

    return false; 
}
</code></pre>
",https://stackoverflow.com/questions/43753435/how-to-use-moq-to-unit-test-an-application-that-consumes-asmx-service-in-net,"['c#', 'asp.net-mvc', 'unit-testing', 'moq']",667,TRUE,3,1
Unit tests missing output in VS2017,"<p><strong>EDIT:</strong></p>

<p>I might have found a possible lead.</p>

<p>Checking my <strong>Test Runs</strong> it would seem as if I have 0 completed runs (even though all my 15 tests complete). Any clues?</p>

<hr>

<p>I've got a technical interview coming up where testing will be the main focus. I've got rather limited exposure to testing in Visual Studio and can't seem to figure out why my version (VS2017) won't display the <strong>output</strong> button when I run tests. </p>

<p>Since my limited exposure I've been following along a few PluralSight courses on the subject and have found a decent one covering both LINQ and VS's own unit testing framework.</p>

<p>This is where it should be on VS2015 (I think?):<a href=""https://i.stack.imgur.com/U1Mjn.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/U1Mjn.png"" alt=""enter image description here""></a></p>

<p>And this is how it looks for me:</p>

<p><a href=""https://i.stack.imgur.com/oIHBB.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/oIHBB.png"" alt=""enter image description here""></a></p>

<p>As you can see I'm missing the <strong>output</strong> button for some god forsaken reason. I've looked in multiple windows (output's debug and tests), but simply cannot see the output.</p>

<p>My unit test follows the instructor's structure with some small changes (like how I set up my <code>TestContext</code>, which follows the structure of <strong><a href=""https://stackoverflow.com/a/4787047/5986941"">this answer to a similar question.</a></strong>.</p>

<p>This is my unit test:</p>

<pre><code>using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ACM.Library.Test
{
    [TestClass]
    public class BuilderTest
    {
        private TestContext _testContextInstance;
        public TestContext TestContext
        {
            get { return _testContextInstance; }
            set { _testContextInstance = value; }
        } 
        public Builder listBuilder { get; set; }

        [TestInitialize]
        public void TestInitialize ()
        {
            this.listBuilder = new Builder();
        }

        [TestMethod]
        public void TestBuildIntegerSequence()
        {
            var result = listBuilder.BuildIntegerSequence();

            foreach(var item in result)
            {
                TestContext.WriteLine(item.ToString());
            }

            Assert.IsNotNull(result);
        }
    }
}
</code></pre>

<p><strong>EDIT:</strong></p>

<p>Here is the function I'm testing...</p>

<pre><code>    public IEnumerable&lt;int&gt; BuildIntegerSequence()
    {
        var integers = Enumerable.Range(0, 10);
        return integers;
    }
</code></pre>
",https://stackoverflow.com/questions/44656386/unit-tests-missing-output-in-vs2017,"['c#', 'visual-studio', 'unit-testing', 'visual-studio-2017']",739,FALSE,3,0
"Angular, Karma (SystemJS) XHR error (404 Not Found) - [Separate Src/Build]","<p>I'm working with a build system using Angular(2), typescript, karma and SystemJs.</p>

<p>The application build works perfectly taking the src files from apps/samples/** to build/** this is the structure of the build directory. I run my gulp task build the files and browser-sync presents me with my app :)</p>

<pre><code>apps/
  samples/
    app/
      app.component.ts
      app.module.ts
      main.ts
    assets/
      scss/
      js/ //@angular and other node libs get kept here
    test/
      app.component.spec.ts
    index.html
    systemjs.config.js
    systemjs.config.extras.js    
build/
  app/
    app.component.js
    app.component.js.map
    app.module.js
    app.module.js.map
    main.js
    main.js.map
  assets/
    css/
    js/ //@angular and other node libs get kept here
  test/
    app.component.spec.js
    app.component.spec.js.map
  index.html
  systemjs.config.js
  systemjs.config.extras.js
Gulpfile.babel.js
karma.conf.js
karma-test-shim.js
package.json
</code></pre>

<p>Now as mentioned before I have no problems with typescript or any other part of the build the problem comes when running karma I keep getting an error as follows:</p>

<pre><code>Chrome 55.0.2883 (Windows 10 0.0.0) ERROR: 'Unhandled Promise rejection:', '(SystemJS) XHR error (404 Not Found) loading http://localhost:9876/base/systemjs.config.js
    Error: XHR error (404 Not Found) loading http://localhost:9876/base/systemjs.config.js
    Error loading http://localhost:9876/base/systemjs.config.js', '; Zone:', '&lt;root&gt;', '; Task:', 'Promise.then', '; Value:', Error{stack: '(SystemJS) XHR error (404 Not Found) loading http://localhost:9876/base/systemjs.config.js
    Error: XHR error (404 Not Found) loading http://localhost:9876/base/systemjs.config.js
    Error loading http://localhost:9876/base/systemjs.config.js', message: '(SystemJS) XHR error (404 Not Found) loading http://localhost:9876/base/systemjs.config.js
    Error: XHR error (404 Not Found) loading http://localhost:9876/base/systemjs.config.js
    Error loading http://localhost:9876/base/systemjs.config.js', originalStack: 'Error: (SystemJS) XHR error (404 Not Found) loading http://localhost:9876/base/systemjs.config.js
    Error: XHR error (404 Not Found) loading http://localhost:9876/base/systemjs.config.js
    Error loading http://localhost:9876/base/systemjs.config.js', zoneAwareStack: 'Error: (SystemJS) XHR error (404 Not Found) loading http://localhost:9876/base/systemjs.config.js
    Error: XHR error (404 Not Found) loading http://localhost:9876/base/systemjs.config.js
    Error loading http://localhost:9876/base/systemjs.config.js', name: 'Error', toString: function toString() { ... }, originalErr: Error{stack: 'Error: XHR error (404 Not Found) loading http://localhost:9876/base/systemjs.config.js', message: 'XHR error (404 Not Found) loading http://localhost:9876/base/systemjs.config.js', originalStack: 'Error: XHR error (404 Not Found) loading http://localhost:9876/base/systemjs.config.js', zoneAwareStack: 'Error: XHR error (404 Not Found) loading http://localhost:9876/base/systemjs.config.js', name: 'Error', toString: function toString() { ... }}}, '(SystemJS) XHR error (404 Not Found) loading http://localhost:9876/base/systemjs.config.js
    Error: XHR error (404 Not Found) loading http://localhost:9876/base/systemjs.config.js
    Error loading http://localhost:9876/base/systemjs.config.js'
</code></pre>

<p>Now i've been working from a combination of the angular quickstart project and a tutorial here <a href=""https://www.agvision.ro/angular-2-karma-jasmine-unit-testing/"" rel=""nofollow noreferrer"">https://www.agvision.ro/angular-2-karma-jasmine-unit-testing/</a></p>

<p>Here is my karma.config.js</p>

<pre><code>module.exports = function(config) {

var appBase    = 'build/app/';       // transpiled app JS and map files
var appSrcBase = 'apps/samples/app//';       // app source TS files
var appAssets  = '/build/app/'; // component assets fetched by Angular's compiler

// Testing helpers (optional) are conventionally in a folder called `testing`
var testingBase    = 'testing/'; // transpiled test JS and map files
var testingSrcBase = 'testing/'; // test source TS files

config.set({
    basePath: '',
    frameworks: ['jasmine'],

    plugins: [
        require('karma-jasmine'),
        require('karma-chrome-launcher'),
        require('karma-jasmine-html-reporter')
    ],

    client: {
        builtPaths: [appBase, testingBase], // add more spec base paths as needed
        clearContext: false // leave Jasmine Spec Runner output visible in browser
    },

    customLaunchers: {
        // From the CLI. Not used here but interesting
        // chrome setup for travis CI using chromium
        Chrome_travis_ci: {
            base: 'Chrome',
            flags: ['--no-sandbox']
        }
    },

    files: [
        // System.js for module loading
        'node_modules/systemjs/dist/system.src.js',

        // Polyfills
        'node_modules/core-js/client/shim.js',

        // zone.js
        'node_modules/zone.js/dist/zone.js',
        'node_modules/zone.js/dist/long-stack-trace-zone.js',
        'node_modules/zone.js/dist/proxy.js',
        'node_modules/zone.js/dist/sync-test.js',
        'node_modules/zone.js/dist/jasmine-patch.js',
        'node_modules/zone.js/dist/async-test.js',
        'node_modules/zone.js/dist/fake-async-test.js',
        // RxJs
        { pattern: 'node_modules/rxjs/**/*.js', included: false, watched: false },
        { pattern: 'node_modules/rxjs/**/*.js.map', included: false, watched: false },

        // Paths loaded via module imports:
        // Angular itself
        { pattern: 'node_modules/@angular/**/*.js', included: false, watched: false },
        { pattern: 'node_modules/@angular/**/*.js.map', included: false, watched: false },

        { pattern: 'build/systemjs.config.js', included: false, watched: false },
        { pattern: 'build/systemjs.config.extras.js', included: false, watched: false },
        'karma-test-shim.js', // optionally extend SystemJS mapping e.g., with barrels

        // transpiled application &amp; spec code paths loaded via module imports
        { pattern: appBase + '**/*.js', included: false, watched: true },
        { pattern: testingBase + '**/*.js', included: false, watched: true },


        // Asset (HTML &amp; CSS) paths loaded via Angular's component compiler
        // (these paths need to be rewritten, see proxies section)
        { pattern: appBase + '**/*.html', included: false, watched: true },
        { pattern: appBase + '**/*.css', included: false, watched: true },

        // Paths for debugging with source maps in dev tools
        { pattern: appSrcBase + '**/*.ts', included: false, watched: false },
        { pattern: appBase + '**/*.js.map', included: false, watched: false },
        { pattern: testingSrcBase + '**/*.ts', included: false, watched: false },
        { pattern: testingBase + '**/*.js.map', included: false, watched: false}
    ],

    // Proxied base paths for loading assets
    proxies: {
        // required for component assets fetched by Angular's compiler
        ""/app/"": appAssets
    },

    exclude: [],
    preprocessors: {},
    reporters: ['progress', 'kjhtml'],

    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: true
})
}
</code></pre>

<p>and here is my karma-test-shim.js</p>

<pre><code>// /*global jasmine, __karma__, window*/
Error.stackTraceLimit = 0; // ""No stacktrace"""" is usually best for app testing.

// Uncomment to get full stacktrace output. Sometimes helpful, usually not.
// Error.stackTraceLimit = Infinity; //

jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;

// builtPaths: root paths for output (""built"") files
// get from karma.config.js, then prefix with '/base/' (default is 'app/')
var builtPaths = (__karma__.config.builtPaths || ['app/'])
.map(function (p) {
    return '/base/build/' + p;
});

__karma__.loaded = function () {
};

function isJsFile(path) {
    return path.slice(-3) == '.js';
}

function isSpecFile(path) {
    return /\.spec\.(.*\.)?js$/.test(path);
}

// Is a ""built"" file if is JavaScript file in one of the ""built"" folders
function isBuiltFile(path) {
    return isJsFile(path) &amp;&amp;
        builtPaths.reduce(function (keep, bp) {
            return keep || (path.substr(0, bp.length) === bp);
    }, false);
}

var allSpecFiles = Object.keys(window.__karma__.files)
    .filter(isSpecFile)
    .filter(isBuiltFile);

System.config({
    baseURL: 'base/',
    // Extend usual application package list with test folder
    packages: {'testing': {main: 'index.js', defaultExtension: 'js'}},

    // Assume npm: is set in `paths` in systemjs.config
    // Map the angular testing umd bundles
    map: {
        '@angular/core/testing': 'npm:@angular/core/bundles/core-testing.umd.js',
        '@angular/common/testing': 'npm:@angular/common/bundles/common-testing.umd.js',
        '@angular/compiler/testing': 'npm:@angular/compiler/bundles/compiler-testing.umd.js',
        '@angular/platform-browser/testing': 'npm:@angular/platform-browser/bundles/platform-browser-testing.umd.js',
        '@angular/platform-browser-dynamic/testing': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic-testing.umd.js',
        '@angular/http/testing': 'npm:@angular/http/bundles/http-testing.umd.js',
        '@angular/router/testing': 'npm:@angular/router/bundles/router-testing.umd.js',
        '@angular/forms/testing': 'npm:@angular/forms/bundles/forms-testing.umd.js',
    },
});

System.import('systemjs.config.js').then(function (m) {
    console.log(m);
})
//.then(importSystemJsExtras)
.then(initTestBed)
.then(initTesting);

/** Optional SystemJS configuration extras. Keep going w/o it */
 function importSystemJsExtras() {
     return System.import('systemjs.config.extras.js')
         .catch(function (reason) {
             console.log(
              'Warning: System.import could not load the optional ""systemjs.config.extras.js"". Did you omit it by accident? Continuing without it.'
        );
        console.log(reason);
    });
}

 function initTestBed() {
    return Promise.all([
        System.import('@angular/core/testing'),
        System.import('@angular/platform-browser-dynamic/testing')
    ])

    .then(function (providers) {
        var coreTesting = providers[0];
        var browserTesting = providers[1];

        coreTesting.TestBed.initTestEnvironment(
            browserTesting.BrowserDynamicTestingModule,
            browserTesting.platformBrowserDynamicTesting());
    })
}

// Import all spec files and start karma
function initTesting() {
    return Promise.all(
        allSpecFiles.map(function (moduleName) {
        return System.import(moduleName);
    })
)
    .then(__karma__.start, __karma__.error);
}
</code></pre>

<p>Now im getting the error and have read post after post after post some mention the base/ directory that karma puts files in, some have mentioned packages and modules and more but nowere gives a definitive answer as to why karma wont load system js.</p>

<p>Im a neewb with angular2 and prefer the build strucutre so wont be changing that aspect, anything else would be helpfull even if im missing something really simple.</p>
",https://stackoverflow.com/questions/41705004/angular-karma-systemjs-xhr-error-404-not-found-separate-src-build,"['javascript', 'angular', 'typescript', 'karma-runner', 'systemjs']",1389,FALSE,3,1
Slim/Http/Environment not found in PHPUnit test,"<p>I'm developing an API with <code>Slim/Composer</code> and I am currently trying to implement some unit testing with <code>PHPUnit</code>. I keep running into an error when I run the test via command line:</p>

<pre><code>Fatal error: Class 'Slim\Http\Environment' not found
in C:\workspace\client\website\client\api\client-api\src\testclasses\dao\GenreDaoTest.php
on line 15
</code></pre>

<p>My composer.json looks like this:</p>

<pre><code>{
    ""require"": {
        ""slim/slim"": ""^3.1"",
        ""slim/php-view"": ""^2.0"",
        ""monolog/monolog"": ""^1.17"",
        ""robmorgan/phinx"": ""^0.5.1"",
        ""firebase/php-jwt"": ""^5.0"",
        ""vlucas/phpdotenv"": ""^2.4"",
        ""tuupola/slim-jwt-auth"": ""^2.3""
    },
    ""autoload"": {
        ""psr-4"": {
            """": [""classes/dao"",
                 ""classes/controller"",
                 ""classes/app"",
                 ""testclasses/dao""]
        }
    },
    ""require-dev"": {
        ""phpunit/phpunit"": ""^5.7""
    }
}
</code></pre>

<p>My test class looks like this:</p>

<pre><code>&lt;?php

use \Slim\Http\Environment as Environment;
use \Slim\Http\Request as Request;
use \Slim\Http\Response as Response;

class GenreDaoTest extends \PHPUnit_Framework_TestCase {

   public function testTemp() {
      $this-&gt;assertEquals(0, 0);
   }

   public function testGenres() {

      $environment = Environment::mock([
         'REQUEST_METHOD' =&gt; 'GET',
         'REQUEST_URI' =&gt; '/api/v1/genres'
      ]);

      $request = \Slim\Http\Request::createFromEnvironment($environment);
      $response = new Response();

      $this-&gt;assertEquals('test', 'test');
   }
}
?&gt;
</code></pre>

<p>If I comment out the entire 2nd test, leaving the use statements, the first test will pass with no problem. I thought maybe it was something to do with the location of the test file, so I moved it to the classes/app directory where I have other classes with similar imports, and I'm seeing the same results, so I don't <em>think</em> it's and issue with where the file lives.</p>

<p>The only 2 things I can think of is that something is happening when I run the test via the command line ($phpunit src/testclasses/dao/GenreDaoTest.php) or something is wrong with my Composer setup.</p>

<p>I'm a Java engineer usually, so I may be missing something simple in the PHP realm, too :)</p>

<p>Anyone have any suggestions? I greatly appreciate it!</p>

<p>(also, I understand that I probably shouldn't be testing API requests/responses in a test for a DAO, I'm in the process of refactoring)</p>
",https://stackoverflow.com/questions/47966397/slim-http-environment-not-found-in-phpunit-test,"['php', 'unit-testing', 'phpunit', 'composer-php', 'slim']",846,FALSE,3,2
C++ ld linker --wrap option does not work for internal function calls,"<p>I am trying to implement some unit tests for a C++ library that does not use OO (all functions are declared at namespace level)</p>

<p>For that purpose, I am trying to create a test binary that mocks (simulate) some functions.</p>

<p>I have achieved the above for functions that I call directly, but <strong>I have been unable to replace the calls that the library's functions do</strong>. The example below explains this:</p>

<h1>Production code</h1>

<p>Lets suppose this is the production code, the one that uses the real functions instead of the simulated ones:</p>

<p><strong>CameraHandler.H</strong></p>

<pre><code>namespace Cam {
    int myFunc();
    int myFunc2();
}
</code></pre>

<p><strong>CameraHandler.cpp</strong></p>

<pre><code>#include ""CameraHandler.h""

using namespace Cam;

int Cam::myFunc() {
    // Imagine this is the function I want to simulate with a mock
    // Its mangled name is _ZN3Cam6myFuncEv
    return 1;
}

int Cam::myFunc2(){
    return Cam::myFunc() + 11;
}
</code></pre>

<h1>Testing code</h1>

<p>This is the code for the unit testing. As you can see in the Makefile, it generates a binary called <strong>testsMain</strong>.</p>

<p><strong>CameraHandlerMock.h</strong></p>

<pre><code>extern ""C"" {
    int __wrap__ZN3Cam6myFuncEv(); // mangled name of Cam::myFunc(), with the __wrap_ prefix.
}
</code></pre>

<p><strong>CameraHandlerMock.cpp</strong></p>

<pre><code>#include ""CameraHandlerMock.h""

int __wrap__ZN3Cam6myFuncEv(){
    // As you can see, the mocked function returns 999 instead of 1.
    return 999;
}
</code></pre>

<p><strong>UnitTestsMain.cpp</strong></p>

<pre><code>#include &lt;iostream&gt;
#include &lt;typeinfo&gt;
#include ""CameraHandler.h""
#include ""CameraHandlerMock.h""

extern ""C"" int _ZN3Cam6myFuncEv();

int main(){
    std::cout &lt;&lt; Cam::myFunc() &lt;&lt; std::endl;
    std::cout &lt;&lt; Cam::myFunc2() &lt;&lt; std::endl;
    return 0;
}
</code></pre>

<p><strong>The Makefile</strong></p>

<pre><code>WRAP=-Wl,--wrap,_ZN3Cam6myFuncEv

all: production unitTests

production: // does not matter for this example
        g++ main.cpp CameraHandler.cpp -o main 

unitTests:
        g++ ${WRAP} UnitTestsMain.cpp CameraHandlerMock.cpp CameraHandler.cpp -o testsMain
</code></pre>

<h1>The problem</h1>

<p>If I execute the <code>testsMain</code> program, I obtain the following result:</p>

<pre><code>999 // call to Cam::myFunc()
12 // Cam::myFunc2(), which is Cam::myFunc() + 11.
</code></pre>

<p>Taking into account that <code>Cam::myFunc2()</code> calls to <code>Cam::myFunc1()</code>, and I have replaced it by <code>__wrap__ZN3Cam6myFuncEv</code>, what I expect is that t he result of calling <code>Cam::myFunc2()</code> is <code>999 + 11 = 1010</code>. Nevertheless, <code>Cam::myFunc2()</code> is still calling the non-wrapped <code>Cam::myFunc1()</code>, so the result is <code>12</code>.</p>

<p><strong>Is there any way to wrap functions that are internally called by the library I want to test</strong>?</p>
",https://stackoverflow.com/questions/44464961/c-ld-linker-wrap-option-does-not-work-for-internal-function-calls,"['c++', 'unit-testing', 'linker', 'mocking', 'ld']",2355,TRUE,3,1
"Unit testing Leaflet app with Karma, Jasmine and Webpack (vanilla ES6). `Uncaught Error: Map container not found`","<p>I'm developing a small mapping app with an straigh forward configuration. The dependencies of the app are Leaflet, for displaying the map, Webpack for building (and webpack-dev-server to hot reload), Babel and Karma and Jasmine for unit testing.<br>
The app is written in vanilla JS implementing some kind of pub/sub pattern (dom events trigger some setters that update the state and notify map and DOM handler functions that update the view with the new state).
This are Karma and Webpack config files. </p>

<p><strong>karma.conf.js</strong>  </p>

<pre><code>var webpackConfig = require('./webpack.config.js')

module.exports = function(config) {
  config.set({


    basePath: '',

    frameworks: ['jasmine'],

    files: [
      'index.html',
      './test/spec/*.spec.js'
    ],


    plugins: [
      'karma-chrome-launcher',
      'karma-jasmine',
      'karma-webpack'
    ],


    preprocessors: {
      'test/spec/*.spec.js': ['webpack']
    },

    webpack: webpackConfig,

    reporters: ['progress'],


    // web server port
    port: 9876,
    colors: true,

    logLevel: config.LOG_INFO,

    autoWatch: true,

    browsers: ['Chrome'],

    singleRun: false,

    concurrency: Infinity
  })
}
</code></pre>

<p><strong>webpack.config.js</strong>  </p>

<pre><code>module.exports = {
  resolve: {
    extensions: ['.js', '.html', '.css']
  },
  context: __dirname,
  entry: {
    app:['./index.js']
  },
  output: {
    path: __dirname +'/build',
    filename: 'app.js',
    publicPath: '/build/'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      }
    ]
  },
  devServer: {
    host: 'localhost',
    port: 8080
  }
}
</code></pre>

<p>The app gets fired from <code>index.html</code> that has a <code>&lt;script&gt;</code> tag that serves <code>build/app.js</code><br>
I trying to run some unit tests but I'm getting <code>Uncaught Error: Map container not found</code> and two warnings:  </p>

<pre><code>26 11 2017 21:19:51.778:WARN [web-server]: 404: /css/general.css
26 11 2017 21:19:51.779:WARN [web-server]: 404: /build/app.js
</code></pre>

<p>I'm only running this <code>setters.spec.js</code> file:  </p>

<pre><code>'use strict'

import {state} from '../../modules/store.js'
import {setHue} from '../../modules/setters.js'
import {notifyBaseHueChange} from '../../modules/eventBus.js'


describe(""Setters"", function() {

  it(""setHue should update state baseHue and notify the change"", 
  function() {
    var hue = 120
    setHue(hue)
    expect(state.baseHue).toEqual(hue)
  })

})
</code></pre>

<p>Notification functions triggers some methods inside <code>mapHandler.js</code> and <code>DOMhandler.js</code> which update the map and DOM values on <code>index.js</code>, but is evident that karma, nor webpack, does not know anything about <code>index.js</code> andcan not access to the <code>&lt;div id=""map""&gt;&lt;/div&gt;</code> where map is displayed on the page.<br>
I'm not really sure how to make karma aware of <code>index.html</code> to use while testing.
I've been through <a href=""https://github.com/webpack/webpack/issues/536"" rel=""nofollow noreferrer"">some</a> <a href=""https://stackoverflow.com/questions/32155154/webpack-config-how-to-just-copy-the-index-html-to-the-dist-folder"">forums</a> <a href=""https://github.com/PaulLeCam/react-leaflet/issues/204"" rel=""nofollow noreferrer"">answers</a> but I'm a little bit lost.<br>
Of course I'm not a seasoned tester :_(<br>
Any advice would be apreciated</p>
",https://stackoverflow.com/questions/47500812/unit-testing-leaflet-app-with-karma-jasmine-and-webpack-vanilla-es6-uncaugh,"['javascript', 'unit-testing', 'webpack', 'leaflet', 'karma-jasmine']",722,FALSE,2,0
Warning developers in Visual Studio if C# expression is used (or throw error),"<p>Does anybody know of a way to prevent developers from using a particular type of expression in a Visual Studio C# code base? I have seen that analysers might be the way to go here.</p>

<p>I would like Visual Studio to warn developers when they use <code>DateTime.Now</code> instead of <code>DateTime.UtcNow</code> in our code base.</p>

<p>As far as my analysis goes, I don't think we will ever need to use <code>DateTime.Now</code> in our API code base, so I'm also pondering the idea of throwing errors at compilation if <code>DateTime.Now</code> is used, in case unit testing doesn't cover this case.</p>

<p>The reason I want to do this is to prevent any non UTC time values from making their way into the database. Senior developers are solid on this, however I have seen time and time again <code>DateTime.Now</code> being used by less senior developers, and I would like to automate the management of this.</p>

<p>I know that setting server time zones to UTC could negate this, however I'd like to solve the issue closer to the cause.</p>

<p>Are there any existing tools out there I could leverage, that anyone knows of, or should I write my own analyser?</p>

<p>Any tips would be much appreciated.</p>
",https://stackoverflow.com/questions/45829965/warning-developers-in-visual-studio-if-c-expression-is-used-or-throw-error,"['c#', 'visual-studio', 'stylecop']",367,TRUE,2,1
python unittest : what is the best way to run the unit tests?,"<h1>Short question</h1>

<p>I can find many resources and instructions on <a href=""https://docs.python.org/3/library/unittest.html"" rel=""nofollow noreferrer"">how</a> <a href=""http://www.python-course.eu/python3_tests.php"" rel=""nofollow noreferrer"">to get</a> <a href=""https://jeffknupp.com/blog/2013/12/09/improve-your-python-understanding-unit-testing/"" rel=""nofollow noreferrer"">unittest</a> <a href=""https://cgoldberg.github.io/python-unittest-tutorial/"" rel=""nofollow noreferrer"">to work</a>, and I can reproduce them on my computer. However, they all are ""dummy"" examples in the sense that they have a flat file tree instead of the file tree typically found in actual python projects. I can't seem to find a satisfactory solution for unit testing in an actual python project.</p>

<p>My problem boils down to : how do I run the test cases? Should I put a main (as in <code>__main__</code>) testing script somewhere? Do I call <code>python3 myPackage/test/test_aModule.py</code>? Do I call <code>python3 -m myPackage.test.test_aModule</code>?</p>

<hr>

<h1>More details</h1>

<p>From what I understand from this <a href=""https://stackoverflow.com/a/3419951/3492512"">answer</a>, this is what my file tree should look like:</p>

<pre><code>MyProject
├── myPackage
│   ├── aModule.py
│   ├── anotherModule.py
│   ├── __init__.py
│   └── test
│       ├── __init__.py
│       ├── test_aModule.py
│       └── test_anotherModule.py
├── README.md
└── setup.py
</code></pre>

<p>I have two modules, the first called ""aModule""</p>

<pre><code># aModule.py
class MyClass:
    def methodToTest(self, a, b):
        return a + b
</code></pre>

<p>and the second called ""anotherModule""</p>

<pre><code># anotherModule.py
def functionToTest(a, b):
    return a * b
</code></pre>

<p>Both modules are being unit-tested. ""aModule"" is unit-tested by ""test_aModule""</p>

<pre><code># test_aModule.py
import unittest
from aModule import MyClass

myObject = MyClass()
print( ""myObject(a,b) = "", myObject.methodToTest(1,2) )
print( ""myObject(a,b) = "", functionToTest(1,2) )

if __name__ == '__main__':
    unittest.main()
</code></pre>

<p>and ""anotherModule"" is unit-tested by ""test_anotherModule""</p>

<pre><code># test_anotherModule.py
import unittest
from anotherModule import functionToTest

if __name__ == '__main__':
    unittest.main()
</code></pre>

<p>What is the best way to run those tests?</p>

<p>Besides, following <a href=""https://stackoverflow.com/a/11536794/3492512"">this answer</a>, invoking <code>python -m myPackage.test.test_aModule</code> from <code>MyProject/</code> outputs <code>No module named 'aModule'</code>. <a href=""https://stackoverflow.com/a/2326045/3492512"">This question</a> suggests to add the current directory to <code>sys.path</code>. However I find this solution quite surprising: am I supposed to add all python projects that I have on my computer to <code>sys.path</code> just so that I can unittest them?!</p>
",https://stackoverflow.com/questions/44009370/python-unittest-what-is-the-best-way-to-run-the-unit-tests,"['python', 'python-3.x', 'python-import', 'python-unittest']",237,FALSE,2,0
LengthFieldBasedFrameDecoder not parsing correctly when buffer size is less than frame size,"<p>I am unit testing a netty pipeline using the frame based decoder. It looks like the framing is incorrect if I use buffer size that is smaller that the largest frame. I am testing with a file that contains two messages. The length field is the second work and includes the length of the entire message including the length field and the work before it.</p>

<pre><code> new LengthFieldBasedFrameDecoder(65536, 4, 4, -8, 0)
</code></pre>

<p>I am reading a file with various block sizes. The size of the first message is 348 bytes, the second is 456 bytes. If block size of 512, 3456, or larger, is used both messages are read and correctly framed to the next handler which for diagnostic purposes will print out as a hexadecimal string the contents of the buffer it received. If a smaller block size is used framing errors occur. The code used to read and write the file is shown below.</p>

<pre><code>public class NCCTBinAToCSV {
    private static String inputFileName = ""/tmp/combined.bin"";
    private static final int BLOCKSIZE = 456;
    public static void main(String[] args) throws Exception {
        byte[] bytes = new byte[BLOCKSIZE];
        EmbeddedChannel channel = new EmbeddedChannel(
                new LengthFieldBasedFrameDecoder(65536, 4, 4, -8, 0),
                new NCCTMessageDecoder(),
                new StringOutputHandler());
        FileInputStream fis = new FileInputStream(new File(inputFileName));
        int bytesRead = 0;
        while ((bytesRead = fis.read(bytes)) != -1) {
            ByteBuf buf = Unpooled.wrappedBuffer(bytes, 0, bytesRead);
            channel.writeInbound(buf);
        }
        channel.flush();
    }
}
</code></pre>

<p>Output from a successful run with block size of 356 bytes is show below (with the body of the messages truncated for brevity</p>

<pre><code>LOG:DEBUG 2017-04-24 04:19:24,675[main](netty.NCCTMessageDecoder) -  com.ticomgeo.mtr.ncct.netty.NCCTMessageDecoder.decode(NCCTMessageDecoder.java:21) ]received 348 bytes

Frame Start========================================

(byte) 0xbb,   (byte) 0x55,   (byte) 0x05,   (byte) 0x16,   
(byte) 0x00,   (byte) 0x00,   (byte) 0x01,   (byte) 0x5c,   
(byte) 0x01,   (byte) 0x01,   (byte) 0x02,   (byte) 0x02,   
(byte) 0x05,   (byte) 0x00,   (byte) 0x00,   (byte) 0x00,   
(byte) 0x50,   (byte) 0x3a,   (byte) 0xc9,   (byte) 0x17,

....   
Frame End========================================

Frame Start========================================

(byte) 0xbb,   (byte) 0x55,   (byte) 0x05,   (byte) 0x1c,   
(byte) 0x00,   (byte) 0x00,   (byte) 0x01,   (byte) 0xc8,   
(byte) 0x01,   (byte) 0x01,   (byte) 0x02,   (byte) 0x02,   
(byte) 0x05,   (byte) 0x00,   (byte) 0x00,   (byte) 0x00,   
(byte) 0x04,   (byte) 0x02,   (byte) 0x00,   (byte) 0x01,  
</code></pre>

<p>If I change the block size to 256, the wrong bytes seem to be read as the length field.</p>

<pre><code>Exception in thread ""main"" io.netty.handler.codec.TooLongFrameException: Adjusted frame length exceeds 65536: 4294967040 - discarded
    at io.netty.handler.codec.LengthFieldBasedFrameDecoder.fail(LengthFieldBasedFrameDecoder.java:499)
    at io.netty.handler.codec.LengthFieldBasedFrameDecoder.failIfNecessary(LengthFieldBasedFrameDecoder.java:477)
    at io.netty.handler.codec.LengthFieldBasedFrameDecoder.decode(LengthFieldBasedFrameDecoder.java:403)
</code></pre>
",https://stackoverflow.com/questions/43592095/lengthfieldbasedframedecoder-not-parsing-correctly-when-buffer-size-is-less-than,"['java', 'netty']",1721,TRUE,2,1
How do I programmatically pause a unittest?,"<p>I'm using visual-studio built-in unit-testing framework - <code>Microsoft.VisualStudio.TestTools.UnitTesting</code> namespace.</p>

<p><strong>I need to pause unit-test execution from the test code (and, preferably, allow the developer to resume the test by pressing some button or something).</strong></p>

<p>Is there any built-in way to do that?</p>

<p>I know I can use a <code>Thread.Sleep()</code> to simply pause for several seconds, but is there a way to pause/resume or prompt the user somehow? Probably another obvious solution would be to call <code>MessageBox.Show()</code> but that'd require a reference to the whole Windows.Forms family...</p>

<p>P.S. The reason behind this: I have a ""fuzzy"" integration test that <em>sometimes</em> fails, but I can't tell why exactly (it's a UI test that automates a browser via <code>Selenium</code>, and the browser screen flashes quickly and I can't tell what happened there...). And for some reason I cannot catch this failure when debugging a test, only when running it regularly...</p>

<p>UPDATE: I guess there's no built-in way to do that, and it actually makes sense, since <strong>tests should run without any user interaction</strong> by design. Guess, a simple <code>Sleep()</code> or even <code>Console.ReadLine()</code> to simply freeze execution, until developer clicks ""cancel"" in the test-explorer.</p>
",https://stackoverflow.com/questions/42926527/how-do-i-programmatically-pause-a-unittest,"['c#', 'visual-studio', 'unit-testing', 'visual-studio-test-runner']",2358,TRUE,1,1
Unit Tests are never discovered,"<p>I have the following solution in Visual Studio 2017 Update 3 preview, which consists of a Xamarin.Forms project as NetStandard1.4 and a NetStandard1.4 dotnet Core Services.API project and a NetStandard1.6 dotnet Core unit test project.</p>

<p><a href=""https://i.stack.imgur.com/Wx5Et.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Wx5Et.png"" alt=""enter image description here""></a></p>

<p>The Unit Test project references the services project only. The csproj file looks like this, with the MSTest framework added for unit testing. The issue though is that the tests are never discovered.</p>

<h2>csproj</h2>

<pre><code>&lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;netstandard1.6&lt;/TargetFramework&gt;
    &lt;AssemblyName&gt;FloatSink.Services.Api.Tests&lt;/AssemblyName&gt;
    &lt;RootNamespace&gt;FloatSink.Services&lt;/RootNamespace&gt;
&lt;/PropertyGroup&gt;

&lt;PropertyGroup Condition=""'$(Configuration)|$(Platform)'=='Debug|AnyCPU'""&gt;
    &lt;DebugType&gt;full&lt;/DebugType&gt;
    &lt;DebugSymbols&gt;True&lt;/DebugSymbols&gt;
&lt;/PropertyGroup&gt;

&lt;ItemGroup&gt;
    &lt;PackageReference Include=""Microsoft.NET.Test.Sdk"" Version=""15.0.0""&gt;&lt;/PackageReference&gt;
    &lt;PackageReference Include=""Microsoft.TestPlatform.TestHost"" Version=""15.0.0"" /&gt;
    &lt;PackageReference Include=""MSTest.TestAdapter"" Version=""1.1.17"" /&gt;
    &lt;PackageReference Include=""MSTest.TestFramework"" Version=""1.1.17"" /&gt;
&lt;/ItemGroup&gt;

&lt;ItemGroup&gt;
    &lt;ProjectReference Include=""..\Services.API\Services.API.csproj"" /&gt;
&lt;/ItemGroup&gt;
</code></pre>

<h2>Unit Test class</h2>

<pre><code>[TestClass]
public class AppBuilderTests
{
    private const string DebugBuild = ""Debug build"";
    private const string ReleaseBuild = ""Release build"";

    /// &lt;summary&gt;
    /// Test that the ToString() method returns the string we sent into the constructor
    /// &lt;/summary&gt;
    [TestMethod]
    public void ToStringReturnsStringFromCtor()
    {
        // Act
        var build = new AppBuild(DebugBuild);

        // Assert
        Assert.AreEqual(DebugBuild, build.ToString());
    }
}
</code></pre>

<p>Finally this is the test output when I build and select Run All from the Test Explorer (which is empty).</p>

<blockquote>
  <p>[5/26/2017 6:38:23 PM Informational] ------ Load Playlist started ------</p>
  
  <p>[5/26/2017 6:38:23 PM Informational] ========== Load Playlist finished (0:00:00.004501) ==========</p>
  
  <p>[5/26/2017 6:38:24 PM Informational] ------ Discover test started ------</p>
  
  <p>[5/26/2017 6:38:25 PM Informational] ========== Discover test finished: 0 
  found (0:00:00.5716028) ==========</p>
</blockquote>

<p>Why won't the MSTest unit tests show up in the Test Explorer and allow me to discover/run them?</p>

<h1>Update</h1>

<p>I changed the debug type from Full to portable and I've also tried this with xUnit and have the same issue. So this isn't specific to MSTest.</p>

<h2>csproj with xUnit</h2>

<pre><code>&lt;Project Sdk=""Microsoft.NET.Sdk""&gt;

  &lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;netstandard1.6&lt;/TargetFramework&gt;
    &lt;AssemblyName&gt;FloatSink.Services.Api.Tests&lt;/AssemblyName&gt;
    &lt;RootNamespace&gt;FloatSink.Services&lt;/RootNamespace&gt;
  &lt;/PropertyGroup&gt;

  &lt;PropertyGroup Condition=""'$(Configuration)|$(Platform)'=='Debug|AnyCPU'""&gt;
    &lt;DebugType&gt;portable&lt;/DebugType&gt;
    &lt;DebugSymbols&gt;True&lt;/DebugSymbols&gt;
  &lt;/PropertyGroup&gt;

  &lt;ItemGroup&gt;
    &lt;PackageReference Include=""Microsoft.NET.Test.Sdk"" Version=""15.0.0"" /&gt;
    &lt;PackageReference Include=""xunit"" Version=""2.2.0"" /&gt;
    &lt;PackageReference Include=""xunit.runner.visualstudio"" Version=""2.2.0"" /&gt;
  &lt;/ItemGroup&gt;

  &lt;ItemGroup&gt;
    &lt;ProjectReference Include=""..\Services.API\Services.API.csproj"" /&gt;
  &lt;/ItemGroup&gt;

&lt;/Project&gt;
</code></pre>
",https://stackoverflow.com/questions/44212141/unit-tests-are-never-discovered,"['unit-testing', '.net-core', 'mstest', 'visual-studio-2017']",314,TRUE,1,1
Customized build lifecycle for Java project,"<p>Working on one Maven project, I faced quite a curious kind of dependencies cycle: there are two maven modules, one of which is instrumenting the Java bytecode, and at the same time uses assertions (for unit-testing purposes), defined in another module, which is in turn supposed to be instrumented by the first one.</p>

<p>So, it's not just a cycle, it's cycle, spreaded between maven phases. I failed to solve it by means of reorganizing Maven modules, and I doubt that it is possible in such case.</p>

<p>Hypothetical solution for this problem might be to reorganise build lifecycle in a following way:</p>

<ol>
<li>Compile the first module's sources</li>
<li>Compile the second module's sources</li>
<li>Instrument the second module using the 1st module's classes</li>
<li>Test first and second modules</li>
<li>Package them</li>
<li>Install/deploy them</li>
</ol>

<p>I doubt that Maven was designed for such hacks. What about other tools? Can it be done with Gradle or Ivy? Or maybe it is possible in Maven by some plugin? Or probably the problem is typical and has more straight solution?</p>

<p>PS: please do not suggest to outline common dependencies to a separate module. If it was so simple, I wouldn't be here.</p>
",https://stackoverflow.com/questions/46575485/customized-build-lifecycle-for-java-project,"['java', 'maven', 'gradle', 'ivy']",136,TRUE,1,2
Injector returns undefined for $httpBackend,"<p>I've been looking into unit testing a project I'm doing for Angular (my first). I've set up a DataTree service that depends on a NodeFactory and also makes $http calls.</p>

<p>First off, (a snippet of) my test:</p>

<pre><code>describe(""the data tree service"", function() {

  let DataTree, NodeFactory, $httpBackend;

  beforeEach(module('memApp.common'));

  beforeEach( inject(function(_DataTree_, _NodeFactory_, _$httpBackend_) {
      DataTree = _DataTree_;
      NodeFactory = _NodeFactory_;
      $httpBackend = _$httpBackend_;
  }));

  describe(""is sane, so it"", function() {

      $httpBackend
        .when('GET', 'json/home.json')
        .respond(200, {
            ""esv"": {
                ""_title"" : ""ESV"",
                ""_filePath"" : ""json/bookData.json""
            }
        });

      ...
  }
...
}
</code></pre>

<p>It is trying to set up a mock backend responding with JSON.</p>

<p>My Karma tests fail on the $httpBackend.when, specifically:</p>

<pre><code>TypeError: Cannot read property 'when' of undefined
        at &lt;the httpBackend.when call&gt;
</code></pre>

<p>My DataTree service (a service service - just want one global instance of it):</p>

<pre><code>(function() {
    angular.module('memApp.common')
        .service('DataTree', ['NodeFactory', '$http', '$q',    
    function(NodeFactory, $http, $q) {
    ...
    }]);
})();
</code></pre>

<p>My NodeFactory factory - a wrapper for a class:</p>

<pre><code>(function() {
    angular.module('memApp.common')
        .factory('NodeFactory', function() {
    ....
    });
})();
</code></pre>

<p>Finally, my included karma.conf.js files:</p>

<pre><code>files: [
  'bower_components/angular/angular.min.js',
  'bower_components/angular-mocks/angular-mocks.js',
  'bower_components/angular-route/angular-route.js',
  'js/common/common.module.js',     //memApp.common module def'd here
  'js/common/node.service.js',      //NodeFactory def'd here
  'js/common/datatree.service.js',  //DataTree def'd here
  'js/common/common.controller.js',
  'js/hierarchy/hierarchy.module.js',
  'js/hierarchy/hierarchy.controller.js',
  'js/rehearsal/rehearsal.module.js',
  'js/rehearsal/rehearsal.controller.js',
  'js/app/app.module.js',
  'js/hierarchy/hierarchy.directive.js',
  'js/rehearsal/rehearsal.directive.js',
  'spec/*Spec.js'                   //all Jasmine tests here - in particular, there is a test suite for NodeFactory here.
],
</code></pre>

<p>I don't think this is relevant, but NodeFactory's test does the following (and I have been burned by what other tests are doing before...):</p>

<pre><code>describe(""the Node service"", function() {

    let NodeFactory;
    let home;

    beforeEach(module('memApp.common'));

    beforeEach( inject(function(_NodeFactory_) {
        NodeFactory = _NodeFactory_;
        home = NodeFactory.create();
    }));
    ...
});
</code></pre>

<p>I have gotten tests in my data tree service to pass without doing anything with $httpBackend. This sorta worries me as I think my service shouldn't be making actual $http calls in a unit test? </p>

<p>I am a bit of a newbie to ng-mock (and am taking the PluralSight course on said topic) but I'm trying to follow along with my project and this is blocking me from doing much. In general, $httpBackend still feels a tad magical.</p>
",https://stackoverflow.com/questions/42957765/injector-returns-undefined-for-httpbackend,"['angularjs', 'karma-jasmine']",509,TRUE,1,1
Encoding and decoding GB1830 on Android,"<p>I have developed a small encoder class that encodes and decodes GB1830. I need this to read and write Dicom files, which could use GB1830. For those of you that are not into these things, <a href=""https://en.wikipedia.org/wiki/GB_18030"" rel=""nofollow noreferrer"">GB1830</a> is a chinese multibyte encoding (1, 2 or 4 bytes) that covers the same codepoints as Unicode (over 1.1M), but with a very complex mapping, to keep it compatible with older chinese standards (GBK).</p>

<p>But on Windows this turned out to be easier than I expected:</p>

<pre><code>Type
  GB18030String = Type AnsiString(54936);

Class Procedure TMEGB18030Encoder.Decode(Const Input: TMEStreamHandler; Const Output: TMEMultiCharSetString);
Var
  sGB18030: GB18030String;
  sUTF16LE: UnicodeString;
Begin
  sGB18030 := AnsiStringOf(Input.ReadRawByteString, 54936);
  sUTF16LE := UnicodeString(sGB18030);
  TMEUTF16LEEncoder.Decode(RawByteStringOf(sUTF16LE), Output);
End;

Class Procedure TMEGB18030Encoder.Encode(Const Input: TMEMultiCharSetString; Const Output: TMEStreamHandler);
Var
  sUTF16LE: UnicodeString;
  sGB18030: GB18030String;
Begin
  sUTF16LE := StringOf(TMEUTF16LEEncoder.Encode(Input));
  sGB18030 := GB18030String(sUTF16LE);
  Output.WriteRawByteString(RawByteStringOf(AnsiString(sGB18030)));
End;
</code></pre>

<p>This basically uses an AnsiString with a codepage of 54936 and lets the OS handle the conversion from and to GB1830 and Unicode (UTF16LE).</p>

<p>But obviously this code won't event compile on Android, as there are no AnsiStrings, and I suppose there is not much support for Windows codepages. But I could be wrong on this, as I am actually going through a call to LocaleCharsFromUnicode, which I think is emulated on non Windows platforms.</p>

<p>All this is subject to unit testing... but if I can't even find a way to recompile this code on Android, I see no way to start testing it. Any hints or ideas?</p>
",https://stackoverflow.com/questions/45234642/encoding-and-decoding-gb1830-on-android,"['android', 'delphi', 'encoding']",301,FALSE,1,0
unit test case for a function which doesn&#39;t returns but calls other function,"<p>I am working on a project using angularjs(1.x) as framework. In this project, I have a web interface and I make some backend request. I felt the need to write testing for this tool. So, I started writing unit test cases for this. But now, I am not able to figure out to write test case for some of the functions. My problem is:</p>

<p>I am trying to write test case of the function which is making backend request, and on either <code>success</code> or <code>error</code>, I am calling other function. So, basically, this function is not returning anything. So, How I can test this function?</p>

<p>Code snippet is:</p>

<pre><code>public makePutRequest(): void {
    this.backendService.putBackendRequest(url, backendData, config)
    .then((success) =&gt; {
        successFunction(success); // function call on success
    }, (error) =&gt; {
        errorFunction(error);   // function call on error
    })
}
</code></pre>

<p>function in backendService is:</p>

<pre><code>public putBackendRequest(url, backendData, config){
    let defered = this.$q.defer();
    this.$httpService.put(url, backendData, config)
        .success((data, status, headers, config): void =&gt; {
            if (status === 200) {
                // do some further manipulation with data.
            }
            return defered.resolve(data);
        })
        .error((data, status, headers, config): void =&gt; {
            if (status === 500) {
                // do some other manipulation.
            }
            return defered.reject(data);
        });
    return defered.promise;
}
</code></pre>

<p>I am writing unit test test cases using karma as test runner and jasmine as testing framework with angularjs(1.x) as framework.</p>

<p>Now, I am not able to figure out how to write test case for the function <code>makePutRequest</code> because it is getting <code>promise</code>, and on <code>resolve</code> of promise it is calling one function and on <code>reject</code> it is calling other function.</p>

<p>I am new to write unit testing in angularjs. Any useful suggestion will be very helpful!</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/43986568/unit-test-case-for-a-function-which-doesnt-returns-but-calls-other-function,"['javascript', 'angularjs', 'unit-testing', 'jasmine', 'karma-jasmine']",734,FALSE,1,1
"Using Moq testing overloaded methods, get System.MissingMethodException: &quot;Method Not Found&quot;","<p>I have this interface:</p>

<pre><code>public interface IProductsRepository
{

    // Use this method for non transactional commits, and return the new primary key.
    Task&lt;int&gt; CreateNewProductItem(ProductExt product);

    // use this method for transactional commits, and return the new primary key
    Task&lt;int&gt; CreateNewProductItem(ProductExt product, MySqlConnection conn, MySqlTransaction transaction);
</code></pre>

<p>Now I'm trying to write some Moq setups:</p>

<pre><code>            Mock&lt;IProductsRepository&gt; _ProductRepositoryMoq = new Mock&lt;IProductsRepository&gt;();

            _ProductRepositoryMoq.Setup(r =&gt; r.CreateNewProductItem(It.IsAny&lt;ProductExt&gt;()))
                .ReturnsAsync((ProductExt p) =&gt;
                {
                    p.ID = productList.Last().ID + 1;
                    return p.ID;
                });
            _ProductRepositoryMoq.Setup(r =&gt; r.CreateNewProductItem(It.IsAny&lt;ProductExt&gt;(), It.IsAny&lt;MySqlConnection&gt;(), It.IsAny&lt;MySqlTransaction&gt;()))
                .ReturnsAsync((ProductExt p, MySqlConnection c, MySqlTransaction t) =&gt;
                {
                    p.ID = productList.Last().ID + 1;
                    return p.ID;
                });
</code></pre>

<p>When I try to run the unit test and before it happens, I get this error:</p>

<pre><code>System.MissingMethodException
  HResult=0x80131513
  Message=Method not found: 'System.Threading.Tasks.Task`1&lt;Int32&gt; 
  Repositories.ProductManager.IProductsRepository.CreateNewProductItem(ProductManagerModels.ProductExt, MySql.Data.MySqlClient.MySqlConnection, MySql.Data.MySqlClient.MySqlTransaction)'.
</code></pre>

<p>I don't get it. This method is defined in the usual way and it's clearly visible, so why is Moq throwing a fit that it cannot find CreateNewProductItem(product, MySqlConnection, MySqlTransaction) ??</p>

<p>NOTE: I've already tried nuking all bin/obj in all projects to force VS 2017 to rebuild the entire solution, and although unlikely, I did see if there was a remote possibility that is was in the GAC, but there was not one item from my projects that has been placed into the GAC. Therefore it has be elsewhere.</p>

<p>SECOND NOTE: As I stated, this is happening <strong><em>before</em></strong> I run any unit tests in the [TestInitialize] method. I'm using MSTest for unit testing. Now the funny thing is that I wrote up a spike to use the database directly instead of the Moq, and NO system.MethodMissingException is thrown. I also verified that the data has indeed been inserted and/or updated in the MySQL Database.</p>
",https://stackoverflow.com/questions/47831031/using-moq-testing-overloaded-methods-get-system-missingmethodexception-method,"['c#', 'unit-testing', 'moq']",990,FALSE,1,0
"Writing unit tests with Jasmine for AngularJS controller with Google maps, modals","<p>I have been coding for so many years, but for for the first time I'm about to write test cases for an angularJS app with Jasmine... I went through many Jasmine tutorials, but most of them include simple apps like calculators or doing similar calculations. I did try it with a few tweaks and it worked fine.</p>

<p>But im finding it hard to implement it in some complex cases like the ones below.</p>

<p>for an example. Below angular code generates a map with markers on it</p>

<pre><code>//Data
var cities = [
    {
        city : 'Toronto',
        desc : 'This is the best city in the world!',
        lat : 43.7000,
        long : -79.4000
    },
    {
        city : 'New York',
        desc : 'This city is aiiiiite!',
        lat : 40.6700,
        long : -73.9400
    },
    {
        city : 'Chicago',
        desc : 'This is the second best city in the world!',
        lat : 41.8819,
        long : -87.6278
    },
    {
        city : 'Los Angeles',
        desc : 'This city is live!',
        lat : 34.0500,
        long : -118.2500
    },
    {
        city : 'Las Vegas',
        desc : 'Sin City...\'nuff said!',
        lat : 36.0800,
        long : -115.1522
    }
];

//Angular App Module and Controller
angular.module('mapsApp', [])
.controller('MapCtrl', function ($scope) {

    var mapOptions = {
        zoom: 4,
        center: new google.maps.LatLng(40.0000, -98.0000),
        mapTypeId: google.maps.MapTypeId.TERRAIN
    }

    $scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);

    $scope.markers = [];

    var infoWindow = new google.maps.InfoWindow();

    var createMarker = function (info){

        var marker = new google.maps.Marker({
            map: $scope.map,
            position: new google.maps.LatLng(info.lat, info.long),
            title: info.city
        });
        marker.content = '&lt;div class=""infoWindowContent""&gt;' + info.desc + '&lt;/div&gt;';

        google.maps.event.addListener(marker, 'click', function(){
            infoWindow.setContent('&lt;h2&gt;' + marker.title + '&lt;/h2&gt;' + marker.content);
            infoWindow.open($scope.map, marker);
        });

        $scope.markers.push(marker);

    }  

    for (i = 0; i &lt; cities.length; i++){
        createMarker(cities[i]);
    }

    $scope.openInfoWindow = function(e, selectedMarker){
        e.preventDefault();
        google.maps.event.trigger(selectedMarker, 'click');
    }

});
</code></pre>

<p>so when i comes to writing the test case, but it has no user inputs</p>

<pre><code>describe('generate the map', function() {
  it('generate the map with the markers', function() {
    // how does test start?
  });
});
</code></pre>

<p>the second controller is where data is where i get values from a php file and open a modal when the user clicks.</p>

<pre><code> angular.module('mapsApp', [])
    .controller('userInputs', function ($scope,$modal,$location,$http) {

 $scope.fblock= [];
     $http.get('grab_from_1.php').success(function(a){
         $scope.fblock= a;
            }).error(function(data){
                $scope.fblock= a;
            });

  $scope.fblock2= [];
     $http.get('grab_from_2.php').success(function(b){
         $scope.fblock2= b;
            }).error(function(b){
                $scope.fblock2 = b;
            });



    $scope.open = function (_vals) {

        var modalInstance = $modal.open({
            controller: ""popin"",
            templateUrl: 'get_template.php',
            resolve: {
                values: function()
                {
                    return _vals;
                },
                dates: function()
                {
                    return $scope.fblock2.filter(function (vals2) {
                        return vals2.id == _vals.id;
                    })

                }
            }
        });
    };


 }]);




    angular.module('mapsApp', []).controller('popin', function ($scope,modalInstance,$location,$http,vals1,vals2) {


      $scope.onclicking = function (cid) {
           $modalInstance.dismiss('cancel');
             $location.path('/information/'+cid);

        };

$scope.vals1= vals1;
$scope.vals2= vals2;


});
</code></pre>

<p>so the unit testing will be something like</p>

<pre><code>describe('grab users from fblock 1nd fblock 2 and show a popup', function() {
  it('grab users from fblock 1', function() {

  });

 it('grab users from fblock 2', function() {

  });

it('open the popup modal', function() {

  });
</code></pre>

<p>});</p>

<p>Its not that i have not tried, im finding it a bit hard to apply the basics which i know to a bit complex scenario for the test controllers i have written above. </p>

<p>I would really appreciate if some one can help or guide me to write proper test cases using Jasmine </p>
",https://stackoverflow.com/questions/41640737/writing-unit-tests-with-jasmine-for-angularjs-controller-with-google-maps-modal,"['angularjs', 'unit-testing', 'jasmine']",87,FALSE,1,0
Build or Pipeline for testing in angular project. Protractor issue,"<p>I am working on a mobile app. I am using ionic framework with angularjs. So I am programming this app using web technologies. My issues are regarding to the tests. I have unit and end to end (e2e) tests in my application. 
Look at my script section in my package.json file:</p>

<pre><code>""scripts"": {
  ""test"": ""karma start test/karma.conf.js"",
  ""test-single-run"": ""karma start test/karma.conf.js --single-run""
}
</code></pre>

<p>I am able to run my unit tests executing the command in a git console:</p>

<pre><code>npm run test
</code></pre>

<p>And my e2e tests executing two commands in two git consoles:</p>

<pre><code>ionic serve (to run my app)
protractor test/protractor-conf.js (to run my e2e tests)
</code></pre>

<p>I have two issues here:</p>

<ul>
<li><p>I am not able to add a script command to my package.json in order to simplify the protractor command. In the same way of my karma commands for unit testing.
I have tried this:</p>

<p>""e2e"" : ""protractor test/protractor-conf.js""</p></li>
</ul>

<p>In order to run ""npm run e2e"", But I received this error: 
<a href=""https://i.stack.imgur.com/digPB.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/digPB.jpg"" alt=""enter image description here""></a></p>

<ul>
<li>The second issue: I would like to create a build (or pipeline) for all my tests. I mean, to have a command like ""rake"" in ruby. Where I can run my units and e2e tests through it. This could be very useful in order to save time in the development process and to avoid the fact of forgetting to run my e2e tests. </li>
</ul>
",https://stackoverflow.com/questions/42570469/build-or-pipeline-for-testing-in-angular-project-protractor-issue,"['javascript', 'angularjs', 'testing', 'protractor']",675,TRUE,1,1
Making C# compatible interface for C++/CLI managed type,"<p>I have some native C/C++ functions for which I'm creating managed wrappers in C++/CLI (Visual Studio 2015).</p>

<p>In particular, one of my managed types looks like this:</p>

<pre class=""lang-cpp prettyprint-override""><code>public ref class MyClass abstract : public IMyClass
{
public:
    virtual void SomeMethod(ID id);
}
</code></pre>

<p>The type <strong>ID</strong> is defined as:</p>

<pre class=""lang-cpp prettyprint-override""><code>typedef unsigned long ID;
</code></pre>

<p>Due to unit testing purposes, I would like to create compatible interfaces to my wrapper types on a different C# assembly that I want to keep separate from the C++/CLI world, so I made this interface:</p>

<pre class=""lang-cs prettyprint-override""><code>public interface IMyClass
{
    void SomeMethod(uint id);
}
</code></pre>

<p>When I try to compile the managed C++/CLI assembly I'm getting and error saying that I should provide a suitable implementation for ""<strong>void SomeMethod(unsigned int)</strong>"".</p>

<p>I used the type <strong>uint</strong> on my interface because according to this <a href=""https://learn.microsoft.com/en-us/cpp/dotnet/dotnet-framework-equivalents-to-cpp-native-types-cpp-cli"" rel=""nofollow noreferrer"">MSDN documentation</a>, an <strong>unsigned long</strong> is converted to the managed type <strong>System.UInt32</strong> (uint), but it seems like (the opposite) using <strong>unsigned long</strong> to implement a <strong>uint</strong> is not possible.</p>

<p>Have any of you had the same problem before? Do you know how to fix this?
Is it possible to tell the C++/CLI compiler that my unsigned long should be treated as a uint type?</p>

<p>I can't change the ID definition as it is part of the native library and is used extensively by other functions.</p>
",https://stackoverflow.com/questions/47755591/making-c-compatible-interface-for-c-cli-managed-type,"['c#', '.net', 'interface', 'c++-cli']",442,TRUE,1,1
3rd party dependency mock for Angular2 jasmine test are not initiated correctly,"<p>So I want to create a test for an Angular 2.4.1 service which has a dependency on Apollo.
In the service where I use Apollo I placed a console log to see what kind of object it sees, and what the result of the function 'watchQuery()' is. I expect the log to print 'TEST', but instead I get an 'undefined'.</p>

<p>When I log just 'watchQuery', it will show that is a function with no parameters. When I update the parameters in the mock-class, I will see the mocked parameters in the log.</p>

<p>So it looks like the class is not initiated properly or something.</p>

<pre><code>describe('Service: ViewGraphService', () =&gt; {

  let viewGraphsService: ViewGraphsService;
  let apolloMock: Apollo;

  class ApolloMock {
    public watchQuery () {
      return 'TEST';
    }
  };

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      providers: [
        ViewGraphsService,
        {
          provide: Apollo,
          useClass: ApolloMock
        }
      ]
    });
  });

  beforeEach(inject([ Apollo ],
    (apollo: Apollo) =&gt; {
      viewGraphsService = new ViewGraphsService(apollo);
      apolloMock = apollo;
    }));

  it('should call apollo when a stream is started', () =&gt; {
    // do some tests
  });
</code></pre>

<p>I also tried to use 'useFactory', but it gave me the same result..</p>

<pre><code>class ApolloMock {
    public watchQuery (a) {
      return 'TEST';
    }
  };

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      providers: [
        ViewGraphsService,
        {
          provide: Apollo,
          useFactory: () =&gt; {
            return new ApolloMock();
          }
        }
      ]
    });
  });
</code></pre>

<p>What am I missing here?</p>

<p><strong>EDIT 1</strong></p>

<p>tried this from <a href=""https://stackoverflow.com/questions/40592637/angular-2-unit-testing-observables"">Angular 2 - Unit Testing Observables</a> </p>

<pre><code>  beforeEach(() =&gt; {
    apolloMock = new ApolloMock();
    TestBed.configureTestingModule({
      providers: [
        ViewGraphsService,
        { provide: Apollo, useValue: apolloMock }
      ]
    });

    viewGraphsService = TestBed.get(ViewGraphsService);
  });
</code></pre>

<p><strong>EDIT 2</strong></p>

<p>So, passing in a new instance of the ApolloMock-class directly to the service is working, but this does not feels like the way it is intended to work... For the simple reason that my typings are off now. The ApolloMock-class does not meet the Apollo class/interface which is expected by the service.</p>

<pre><code>  beforeEach(inject([ Apollo ],
    (apollo: Apollo) =&gt; {
      viewGraphsService = new ViewGraphsService(new ApolloMock());
      apolloMock = apollo;
    }));
</code></pre>
",https://stackoverflow.com/questions/45034344/3rd-party-dependency-mock-for-angular2-jasmine-test-are-not-initiated-correctly,"['angular', 'jasmine', 'angular2-services']",486,TRUE,1,1
Should I unit test methods that have a cyclomatic complexity of 1 if they are part of larger interactions?,"<p>I'm kind of new to unit testing so please excuse a naive question.</p>

<p>I've heard the idea of not testing anything that has a cyclomatic complexity of 1. This is interesting to me b/c I do a lot of interaction testing between events. For example, button is pressed, fires an event, raises event on presenter, presenter modifies the model, and presenter calls method on the view. So I test to make sure that when the button event is raised, the right method on the view is called.</p>

<p>Each method in this sequence may have a cyclomatic complexity of 1. There is no branching. But if I want to test it as a ""system"" (i.e. view, presenter, model) cyclomatic complexity is higher -- adding up all the 1-valued methods in the event sequence.</p>

<p>So my question is when people suggest that I don't need to test methods that have a cyclomatic complexity of 1, are they not talking about interaction tests for testing interactions between classes like I've described above?</p>

<p>I've come across this idea twice this week - once in a Mark Seemann Pluralsight video and once here: <a href=""http://webquali.com/blog/67/15-ways-to-write-beautiful-code.html"" rel=""nofollow noreferrer"">http://webquali.com/blog/67/15-ways-to-write-beautiful-code.html</a>.</p>
",https://stackoverflow.com/questions/43025341/should-i-unit-test-methods-that-have-a-cyclomatic-complexity-of-1-if-they-are-pa,"['c#', 'unit-testing', 'cyclomatic-complexity']",1057,TRUE,1,1
running unit-tests after every successful compilation,"<p>Consider Visual Studio C++ solution with a static lib project and a console app with unit-tests. App post-build step is <code>""$(TargetDir)$(TargetFileName)""</code> to run tests automatically on each successful compilation.</p>

<p>When compilation is successful but tests fail I want to debug them sometimes, so I need to run them from VS. The problem is if tests fail the build is considered failed also, and so VS refuses to run.</p>

<p>A not ideal solution is to enable an option
<a href=""https://i.stack.imgur.com/4Egy9.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/4Egy9.jpg"" alt=""enter image description here""></a></p>

<p>so when you try to run failed build you get</p>

<p><a href=""https://i.stack.imgur.com/JjtOL.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/JjtOL.jpg"" alt=""enter image description here""></a></p>

<p>(the option is <code>on</code> by default but sooner or later everybody clicks on ""Do not show this dialog again"")</p>

<p>It's not ideal because it's confusing, it triggers build again (compilation is skipped as it was successful but tests are run again, and the option is global meaning it applies to all your projects even those that don't need it. It's certainly not a very big deal, just wonder if people have some clever hacks for this. </p>

<p>For example, C# projects build events have an option ""When the build updates the project output"" - perfect for unit-testing after each compilation.</p>

<p>The project is cross-platform, so VS testing framework is not applicable.</p>
",https://stackoverflow.com/questions/44391063/running-unit-tests-after-every-successful-compilation,"['c++', 'visual-studio', 'unit-testing']",303,FALSE,1,1
"How to Unit Test an MVC Controller with Three Dependencies, Using Moq","<p>Caveat: I'm brand spanking new to Moq, Unit Testing with Moq, and TDD, generally.</p>

<p>I have a controller with three dependencies. Here is the Constructor (etc) to the SomethingController:</p>

<pre><code>public class SomethingController : Controller
    {
        private readonly ILogger&lt;SomethingController&gt; _logger;
        private readonly ISomethingRepository _something;
        private readonly IExceptionSvc _ex;

        public SomethingController(ILogger&lt;SomethingController&gt; logger,
            ISomethingRepository something,
            IExceptionSvc ex)
        {            
            _logger = logger;
            _something = something;
            _ex = ex;

        }

[HttpGet]
        [AllowAnonymous]
        public JsonResult GetStuff()
        {
            //intitialize list
            var stuffs = new List&lt;StuffViewModel&gt;();

        try
        {
            _logger.LogInformation(""SomethingController: GetStuff() - Getting Stuff, sorted ascending."");

            //get the stuffs
            stuffs = _something.GetStuff();

            _logger.LogInformation(""Retrieved {0} Stuffs."", stuffs.Count);
        }
        catch (Exception ex)
        {
            _logger.LogError(""Error in SomethingController: GetStuff()"", ex);
            return _ex.Http500ErrorReturn(""GetStuff"");
        }

        return Json(stuffs);
    }

}
</code></pre>

<p>Now, here is the description of what each dependency is for:</p>

<p><strong>ILogger</strong>: This is simply for logging, using Microsoft.Extensions.Logging via NLog. 
<strong>ISomethingRepository</strong>: This does all the work (well...the impementation of it, really). It calls the database and gets things. There is a method called <strong>GetStuff()</strong>, which simply returns a list of Stuffs. This Repository has a dependency on the database, which is injected into the repo via the constructor.
<br><strong>IExceptionSvc</strong>: This is just a dumb little service that has a method that returns a 500 Error response for a JSON formatted return to the caller.</p>

<p>I want to test the GetStuff() action in the Controller, which will call the GetStuff() implementation in the Repository. </p>

<p>I currently have the following code stubbed in, in my test project:</p>

<pre><code>public void GetStuff_Is_Awesome()
        {
            Mock&lt;ILogger&lt;SomethingController&gt;&gt; logger = new Mock&lt;ILogger&lt;SomethingController&gt;&gt;();
            Mock&lt;ISomethingRepository&gt; something = new Mock&lt;ISomethingRepository&gt;();
            Mock &lt;IExceptionSvc&gt; ex = new Mock&lt;IExceptionSvc&gt;();
            SomethingController sc = new SomethingController(logger.Object, something.Object, ex.Object);

sc.GetStuff();

//...what now? What am I looking for? Am I going to see a list of stuffs here?

}
</code></pre>

<p>I just want to know what to expect? Am I testing whether a list of Stuffs was returned? How do I test that?</p>

<p>Here is the implementation of GetStuff() in the Repository (with the repo constructor for reference sake):</p>

<pre><code>private readonly ApplicationDbContext _context;
        private readonly ILogger&lt;SomethingRepository&gt; _logger;

        public SomethingRepository(ApplicationDbContext context,
            ILogger&lt;SomethingRepository&gt; logger)
        {
            _context = context;
            _logger = logger;
        }

public List&lt;StuffViewModel&gt; GetStuff()
        {
            List&lt;StuffViewModel&gt; stuffs = null;
            stuffs = _context.Stuffs.OrderBy(b =&gt; b.Name).Select(b =&gt; new StuffViewModel
                {
                    Id = b.Id,
                    Name = b.Name
                }).ToList();

return stuffs;
            }
</code></pre>
",https://stackoverflow.com/questions/43741115/how-to-unit-test-an-mvc-controller-with-three-dependencies-using-moq,"['.net', 'asp.net-mvc', 'unit-testing', 'tdd', 'moq']",1055,TRUE,1,1
Correct way to unit test Express Middleware,"<p>I have a piece of Express middleware that is set to check for a valid Content-Type header in all of my POST requests that hit my server, the code for this middleware is below:</p>

<pre><code>import * as STRINGS from ""../Common/strings"";

function ContentTypeValidator(req, res, next) {
    let contentHeader = req.get(""content-type"");
    if(!contentHeader) {
        res.status(400).send(STRINGS.ERROR_CONTENT_TYPE_MISSING);
    } else {
        if(contentHeader.toLowerCase() !== ""application/json"") {
            res.status(415).send(STRINGS.ERROR_CONTENT_TYPE_UNSUPPORTED);
        } else {
            next();
        }
    }
}

export default ContentTypeValidator;
</code></pre>

<p>I am using <code>mocha</code>, <code>chai</code> and <code>node-mocks-http</code> for my TDD and my question surrounds the tests when <code>next()</code> will not be called as <code>res.send()</code> will handle the ending of this request for me.</p>

<pre><code>it(""Should return 200 for valid Content-Type header"", (done) =&gt; {
    req = nodeMocks.createRequest({
        headers: {
            ""Content-Type"": ""application/json""
        }
    });
    ContentTypeValidator(req, res, (err) =&gt; {
        res.statusCode.should.equal(200);
        expect(err).to.be.undefined;
        done();
    });
});

it(""Should return 400 if Content-Type header is missing"", (done) =&gt; {
    ContentTypeValidator(req, res, () =&gt; {});
    res.statusCode.should.equal(400);
    res._getData().should.equal(""Content-Type header missing"");
    done();
});
</code></pre>

<p>In the first test above, I am expecting this to pass, so I pass in a function to act as the <code>next()</code> function and this test passes. In the second test, I am expecting this to fail so if I pass in a function then mocah complains that the test has exceeded 2000ms as the callback function is never called, which is to be expected since <code>res.send()</code> is handling it in this instance.</p>

<p>Is the way I've written the second test correct when it comes to unit testing Express middleware like this or is there a better/more advisable way to do this?</p>

<p>EDIT: So just to clarify, I am focused on wanting to test the middlewear when the next callback will NOT be called, the question I'm apparently duplicating is looking at using <code>sinon</code> to check if next is called. I am looking to see how to unit test when the callback function will NOT be called.</p>
",https://stackoverflow.com/questions/41636201/correct-way-to-unit-test-express-middleware,"['node.js', 'unit-testing', 'express', 'mocha.js', 'chai']",24668,TRUE,15,1
Parse server unit test with mocha,"<p>So I've been following some tutorials about unit testing with Cloud Code. Here is how I organize my code base :</p>

<pre><code>cloud/
  ChatMessage/
    model.js
    update.js
  ChatRoom/
    model.js
    update.js
test/
  test.js
</code></pre>

<p>In my <code>model.js</code> files, I have Parse.Object subclass with helper functions. It looks like this</p>

<pre><code>class ChatMessage extends Parse.Object {
    constructor() {
        super('ChatMessage')
    }

    // Some functions
}

Parse.Object.registerSubclass('ChatMessage', ChatMessage)

module.exports = ChatMessage
</code></pre>

<p>In my <code>update.js</code> files, I have the before/after save and cloud code functions :</p>

<pre><code>function beforeSave(request, response) {
    // Do stuff
}

Parse.Cloud.beforeSave('ChatMessage', function (request, response) {
    beforeSave(request, response)
})

module.exports = {
    beforeSave: beforeSave,
}
</code></pre>

<p>I've extracted the content of the beforeSave function for test purposes. It enables me to expose the before save function to mocha. For the record, all this works fine in production. </p>

<p>Now in my test I do this :</p>

<pre><code>const ChatMessage = require('../cloud/ChatMessage/model.js')
const ChatMessageUpdate = require('../cloud/ChatMessage/update.js')
const expect = require('expect')

describe('ChatMessage', function () {
    const request = {
        user: new Parse.User(),
        object: new ChatMessage()
    }
    const response = {
        success: function () {},
        error: function () {}
    }

    describe('creation', function () {
        it('should fail when the author is undefined', function () {
            ChatMessageUpdate.beforeSave(request, response)
            expect(response.error).toHaveBeenCalled()
        })
    })
})
</code></pre>

<p>I mock the request and response object. And then I try to launch a test using my beforeSave function. And I get the following error :</p>

<blockquote>
  <p>class ChatRoom extends Parse.Object {
                         ^</p>
  
  <p>ReferenceError: Parse is not defined</p>
</blockquote>

<p>A quick fix is to add this at the beginning of my model file like this :
const Parse = require('parse/node')</p>

<p>But Parse is already expose in <code>/cloud</code> so it seems stupid to me to copy paste this line in every file. What should I do ? More precisely : how do I have my object oriented structure conform to tests ?</p>

<p>Also, what would be the best code structure to test all my code with zero asynchronous test (for test performance) ?</p>
",https://stackoverflow.com/questions/42539305/parse-server-unit-test-with-mocha,"['javascript', 'unit-testing', 'parse-server']",970,FALSE,0,2
Why do i need to have create database permissions for asp.net web app?,"<p>I am building an ASP.NET, code-first web app. I am using a company owned database, and have crud permissions for tables within one database on this server. I do not believe I have ""Create Database"" permissions. I am running into issues publishing my web app. I can run everything locally, but when I publish the code on the company server I get errors like:</p>

<pre><code>Format of the initialization string does not conform to specification starting at index 0. 
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

 Exception Details: System.ArgumentException: Format of the initialization string does not conform to specification starting at index 0.

Source Error: 
 An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  

Stack Trace: 
[ArgumentException: Format of the initialization string does not conform to specification starting at index 0.]
   System.Data.Common.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, Boolean useOdbcRules, String&amp; keyname, String&amp; keyvalue) +1742
   System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey) +191
   System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules) +136
   System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) +75
   System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous) +35
   System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions&amp; userConnectionOptions) +241
   System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key) +78
   System.Data.SqlClient.SqlConnection.set_ConnectionString(String value) +116
   System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) +104
   System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.SetConnectionString(DbConnection connection, DbConnectionPropertyInterceptionContext`1 interceptionContext) +434
   System.Data.Entity.Internal.LazyInternalConnection.TryInitializeFromAppConfig(String name, AppConfig config) +39
   System.Data.Entity.Internal.LazyInternalConnection.Initialize() +160
   System.Data.Entity.Internal.LazyInternalConnection.get_Connection() +16
   [Project].DBContext.Context..ctor() in C:\Users\[UserName]\Documents\[FilePath]\[Project]\DBContext\Context.cs:20
   [Project].Data_Manager.DataManager..ctor() in C:\Users\[UserName]\Documents\[FilePath]\[Project]\Data_Manager\DataManager.cs:15
   [Project].Controllers.HeaderController..ctor() in C:\Users\[UserName]\Documents\[FilePath]\[Project]\Controllers\HeaderController.cs:12
</code></pre>

<p>This error makes me believe I have an issue with my connection string. When using Unit Testing, I get the error:</p>

<pre><code>An exception of type 'System.Data.SqlClient.SqlException' occurred in EntityFramework.dll but was not handled in user code

Additional information: CREATE DATABASE permission denied in database 'master'.
</code></pre>

<p>I recently changed my context constructor from:</p>

<pre><code>public Context() : base(""[server_Name].[database_name]"")
{}
</code></pre>

<p>to:</p>

<pre><code>public Context() : base(""[server_Name].[full_company_server_file_path]"")
{}
</code></pre>

<p>And when I ran the solution locally, also got the ""<code>CREATE DATABASE permission denied in database 'master'</code>"" error.</p>

<p>For the record, my connection string is:</p>

<pre><code>&lt;connectionStrings&gt;
      &lt;clear /&gt;
    &lt;add name=""[server_Name].[database_name]"" providerName=""System.Data.SqlClient"" connectionString=""Data Source=[server_Name].[full_company_server_file_path];Initial Catalog=[database_name];Persist Security Info=True;User ID=userid;Password=password;MultipleActiveResultSets=True;Application Name=EntityFramework"" /&gt;
&lt; /connectionStrings&gt;
</code></pre>

<p>My question is:</p>

<p>Why do I need Create Database Permissions in order for this all to work?
And if that isn't the case, why do I keep getting this error? (No where in my code do I say create DB, nor should / can I).</p>

<p>Secondly, any suggestions as to fixing my connection string? I got this connectionString from database -> properties -> Connection String (so I feel like it's correct).</p>

<p>Thanks for all help / tips / explanations.</p>

<p>Using: </p>

<ul>
<li>ASP.NET / Entity Framework / C#</li>
<li>Visual Studio 2015</li>
<li>SQL Server Management Studio 2014</li>
</ul>
",https://stackoverflow.com/questions/41812266/why-do-i-need-to-have-create-database-permissions-for-asp-net-web-app,"['asp.net', 'sql-server', 'database', 'database-permissions']",645,TRUE,0,2
How to handle logging in Android JUnit tests?,"<p>I would like to log information in model classes - not necessarily for unit testing purposes but for real life scenarios where I am trying to debug.</p>

<p>However, if I try to use <code>android.util.Log</code> methods I get the following errors when running JUnit tests:</p>

<pre><code>java.lang.RuntimeException: Method d in android.util.Log not mocked. See http://g.co/androidstudio/not-mocked for details.
</code></pre>

<p>I understand <em>why</em> this occurs, I should not be using Android framework code in model classes that are designed to be framework independent!  I'm not really arguing against the error, but rather I am trying to find a way to work around this.</p>

<p>I have one idea, does this make sense?</p>

<p>Create a <code>CustomLog</code> class along these lines:</p>

<pre><code>public class CustomLog {
    private static ILogger mLogger;

    public static void setLogger(ILogger logger) {
        mLogger = logger;
    }

    public static void e(String tag, String message) {
        mLogger.e(tag, message);
    }
}
</code></pre>

<p>Where <code>ILogger</code> is an interface with the required methods to perform the log functionality (e, d, etc. methods...)</p>

<p>I could create an <code>ILoggerImpl</code> that uses the <code>android.util.Log</code> methods, and a <code>MockLogger</code> class that simply prints out to <code>System.out.println</code> and/or does nothing (or anything else!).</p>

<p>I think that'd perfectly fit my needs (I would be required to setup my <code>CustomLog</code> class very early on in the lifecycle, but that's not a huge deal).</p>

<p>However, if I ever needed to add third party libraries/outside code to my model classes, this would likely break again in the same manner if the new libraries/code use <code>android.util.Log</code> methods.</p>

<p>So, is there a ""catch all"" type behavior I could use?  What do you think?</p>
",https://stackoverflow.com/questions/42633777/how-to-handle-logging-in-android-junit-tests,"['android', 'unit-testing', 'junit', 'android-testing']",4008,FALSE,7,1
OOP Design setter vs passing parameter in method,"<p>I have a doubt about good OOP design in this case:</p>

<p>The example is not real. But I can´t give you the real example because its private code. However the example concept it's exactly the same.</p>

<p>Imagine I have a class where I store a List of strings and I have a method called ThereIsString(string mystring).</p>

<p>I return true or false depending on if a computation I do with that string ""is related"" to one of the strings is listOfString. (this is the private algorithm)</p>

<p>Example:</p>

<pre><code>public class StringBagAlgorithm()
{
    List&lt;string&gt; listofString = new List&lt;string&gt;();

    public boolean ComputeString(string myString)
    {
        return true or false depending on the computation with the list of strings;
    }
}
</code></pre>

<p>Ok. the list of Strings is stored in a different class called ListOfStrings which has a reference to StringBagAlgorithm so:</p>

<pre><code>public class ListOfStrings()
{
    List&lt;string&gt; listofString = new List&lt;string&gt;();
    List&lt;string&gt; MySecondListofString = new List&lt;string&gt;();
    StringBagAlgorithm _bagAlgorithm

    public ListOfStrings(StringBagAlgorithm bagAlgorithm)
    {
        this._bagAlgorithm = bagAlgorithm;
    }

    public void ComputeSecondList()
    {
       for (int i=0; i&lt;MySecondListofString; i++ )
          _bagAlgorithm.ComputeString(MySecondListofString[i]);
    }
}
</code></pre>

<p>My question is what is the best way of passing the listofString to the StringBagAlgorithm. By doing it in the for loop for example:</p>

<p>_bagAlgorithm.ComputeString(MySecondListofString[i],listofString);</p>

<p>Or by doing it using a setter before doing the for loop. Or any other options?</p>

<p>Would like to know which is the best OO design for loose coupling and unit testing. Also I guess that by using a setter once and not passing the list in every call, the performance is better, but the design is worse?</p>
",https://stackoverflow.com/questions/44088230/oop-design-setter-vs-passing-parameter-in-method,"['java', 'c#', 'oop']",146,FALSE,0,1
Unit testing a method with two database queries. Should I be stubbing out database calls? Rails/Rspec,"<p>I'm trying to test a method that makes use of ActiveRecord a moderate amount. I've always heard that unit testing methods and not using a database is the best way to go about things. However, the downsides of this to me are what if you incorrectly stub the response from ActiveRecord? I might incorrectly be stubbing out whatever ActiveRecord is returning in reality and now I have an inaccurate test.</p>

<p>FYI a <code>user</code> has many <code>coupons</code> and a <code>coupon</code> can have many <code>coupon_uses</code> (the times when it's applied to an <code>order</code>).</p>

<p>This is my method:</p>

<pre><code>def get_coupons_and_uses_for_user
      coupons = Promotions::Coupon
        .includes(:coupon_uses)
        .where(user_id: user_id)

      coupons.reduce([]) do |memo, c|
        memo &lt;&lt; { coupon: c, coupon_uses: c.coupon_uses.order('created_at desc') }
      end
    end
</code></pre>

<p>The above method (which basically queries the user's coupons and then returns each coupon associated with its usages) has two ActiveRecord calls, both of which I need to stub out if I don't use a database in my tests:</p>

<p><code>Promotions::Coupon.includes(:coupon_uses).where(user_id: user_id)</code></p>

<p>and</p>

<p><code>c.coupon_uses.order('created_at desc') #The .order causes ActiveRecord to hit the database</code></p>

<p>Here my test:</p>

<pre><code>describe ""#get_coupons_and_uses_for_user"" do
    subject { service_instance.get_coupons_and_uses_for_user }

    let(:service_instance) { described_class.new(user_id) }
    let(:user_id) { 1 }
    let(:coupon1) { build_stubbed(:coupon) }
    let(:coupon2) { build_stubbed(:coupon) }
    let(:coupons) { [coupon1, coupon2] }
    let!(:coupon_use1) { build_stubbed(:coupon_use) }
    let!(:coupon_use2) { build_stubbed(:coupon_use) }
    let!(:coupon_use3) { build_stubbed(:coupon_use) }
    let!(:coupon_use4) { build_stubbed(:coupon_use) }

    before do
      allow(Promotions::Coupon).to receive_message_chain(:includes, :where) { coupons }
      allow(coupon1).to receive_message_chain(:coupon_uses, :order) { [coupon_use1, coupon_use2] }
      allow(coupon2).to receive_message_chain(:coupon_uses, :order) { [coupon_use3, coupon_use4] }
    end

    it ""returns the user's coupons associated with their coupon uses"" do
      expect(subject).to eq(
        [
          {
            coupon: coupon1,
            coupon_uses: [coupon_use1, coupon_use2]
          },
          {
            coupon: coupon2,
            coupon_uses: [coupon_use3, coupon_use4]
          }
        ]
      )
    end
  end 
</code></pre>

<p>Is this a good way to test? Or should I be using a database? Why or why not?</p>

<p>The problem here is that I'm stubbing out the return values of my ActiveRecord calls like this:</p>

<pre><code>allow(coupon1).to receive_message_chain(:coupon_uses, :order) { [coupon_use1, coupon_use2] }
</code></pre>

<p>But what if I'm wrong about what that query returns (imagine if the query were more complicated). Is this a valid concern?</p>
",https://stackoverflow.com/questions/46347585/unit-testing-a-method-with-two-database-queries-should-i-be-stubbing-out-databa,"['ruby-on-rails', 'unit-testing', 'rspec']",1011,TRUE,0,1
How to mock a redux-form field?,"<p>I am trying to mock a redux-form field in a unit test so that when onChange gets fired in my code the value gets updated. My field looks something like this:</p>

<pre><code>myField: {
  value: false,
  onChange: () =&gt; {},
}
</code></pre>

<p>I have passed an empty function to onChange here as a placeholder for the purposes of asking this question but I know that I need to write some logic to update the value... I am not sure where to begin with that though.</p>

<p>In the component that I am unit testing the onChange gets called like so:</p>

<pre><code>this.props.myField.onChange(true);
</code></pre>

<p>and this works under normal usage (non unit test scenario).</p>

<p>I have a very basic knowledge of sinon (specifically using spies) but I'm not sure if this is what I need or if I can just pass a normal function to onChange in my unit test.</p>

<p>I really appreciate any help on this!</p>

<p>EDIT:</p>

<p>It was pointed out in the comments that it wasn't completely clear what I am trying to achieve. What I am specifically trying to do is manipulate the value property of myField from inside the onChange method as I want to be able to test the effect that value change has on my component.</p>
",https://stackoverflow.com/questions/45816486/how-to-mock-a-redux-form-field,"['reactjs', 'sinon', 'redux-form']",482,FALSE,0,0
mvn clean package: no main manifest attribute,"<p>While the project <a href=""https://stackoverflow.com/q/46866012/262852"">executes</a> from the IDE, how is the <code>JAR</code> created so that a hello world type console app will actually run?</p>

<pre><code>thufir@dur:~/NetBeansProjects/HelloMaven$ 
thufir@dur:~/NetBeansProjects/HelloMaven$ mvn clean package
[INFO] Scanning for projects...
[INFO] 
[INFO] ------------------------------------------------------------------------
[INFO] Building HelloMaven 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ HelloMaven ---
[INFO] Deleting /home/thufir/NetBeansProjects/HelloMaven/target
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ HelloMaven ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 0 resource
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ HelloMaven ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to /home/thufir/NetBeansProjects/HelloMaven/target/classes
[INFO] 
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ HelloMaven ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /home/thufir/NetBeansProjects/HelloMaven/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ HelloMaven ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ HelloMaven ---
[INFO] No tests to run.
[INFO] 
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ HelloMaven ---
[INFO] Building jar: /home/thufir/NetBeansProjects/HelloMaven/target/HelloMaven-1.0-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.400 s
[INFO] Finished at: 2017-10-21T10:50:42-07:00
[INFO] Final Memory: 14M/47M
[INFO] ------------------------------------------------------------------------
thufir@dur:~/NetBeansProjects/HelloMaven$ 
thufir@dur:~/NetBeansProjects/HelloMaven$ tree
.
├── nbactions.xml
├── pom.xml
├── src
│   ├── main
│   │   ├── java
│   │   │   └── net
│   │   │       └── bounceme
│   │   │           └── dur
│   │   │               └── hello_maven
│   │   │                   └── Main.java
│   │   └── resources
│   └── test
│       └── java
└── target
    ├── classes
    │   └── net
    │       └── bounceme
    │           └── dur
    │               └── hello_maven
    │                   └── Main.class
    ├── generated-sources
    │   └── annotations
    ├── HelloMaven-1.0-SNAPSHOT.jar
    ├── maven-archiver
    │   └── pom.properties
    └── maven-status
        └── maven-compiler-plugin
            ├── compile
            │   └── default-compile
            │       ├── createdFiles.lst
            │       └── inputFiles.lst
            └── testCompile
                └── default-testCompile
                    └── inputFiles.lst

25 directories, 9 files
thufir@dur:~/NetBeansProjects/HelloMaven$ 
thufir@dur:~/NetBeansProjects/HelloMaven$ java -jar target/HelloMaven-1.0-SNAPSHOT.jar 
no main manifest attribute, in target/HelloMaven-1.0-SNAPSHOT.jar
thufir@dur:~/NetBeansProjects/HelloMaven$ 
</code></pre>

<p>apparently just need to specify the <code>Main-Class</code> entry for the manifest.</p>

<p>Just focusing on the <code>package</code> <a href=""https://maven.apache.org/guides/getting-started/maven-in-five-minutes.html"" rel=""nofollow noreferrer"">phase</a>:</p>

<blockquote>
  <p>Running Maven Tools Maven Phases</p>
  
  <p>Although hardly a comprehensive list, these are the most common
  default lifecycle phases executed.</p>
  
  <p>validate: validate the project is correct and all necessary
  information is available compile: compile the source code of the
  project test: test the compiled source code using a suitable unit
  testing framework. These tests should not require the code be packaged
  or deployed package: take the compiled code and package it in its
  distributable format, such as a JAR. integration-test: process and
  deploy the package if necessary into an environment where integration
  tests can be run verify: run any checks to verify the package is valid
  and meets quality criteria install: install the package into the local
  repository, for use as a dependency in other projects locally deploy:
  done in an integration or release environment, copies the final
  package to the remote repository for sharing with other developers and
  projects</p>
</blockquote>
",https://stackoverflow.com/questions/46866280/mvn-clean-package-no-main-manifest-attribute,"['java', 'maven', 'jar', 'packaging', 'manifest.mf']",2065,FALSE,0,1
NodeJS Mocha Chai - Unit Test Socket Emit After Chai Request To Node Event,"<p>I have an application which dynamically updates the client side data whenever there comes data update on the server side. I am using AngularJS as front end and NodJS as the relay server. So when there is data update happens another application of someone else would post the data to my NodeJS server, which will be handled by a NodeJS route API (eg: route.post(/send)). For the testing purpose, I am using REST CLIENT for sending data to this API, and these all are working fine too.</p>

<p>When I do unit testing this route(/send) I should confirm whether there happens an event emit to the front end or not when I post a valid data to the node route right?. I am using mocha chai for unit test purpose. I could send the post request to the above-mentioned API using chai.request() method.But how can I verify whether API emitted the data to the client or not?.Below is my sample code and I think it is self-explanatory. </p>

<p>Issue facing is: This piece of code is working, and which is the proof of the success of the event being called.</p>

<pre><code> `server.on('gotData',function(){
     console.log('event emitted');
     assert(true);
     done();
   });`
</code></pre>

<p><strong>Node Code:</strong></p>

<pre><code>router.post('/send', jsonParser, function (req, res) {
      //some logic here
      io.to(socketId).emit('gotData', data);
});
</code></pre>

<p><strong>Client side</strong></p>

<pre><code>var socket = io.connect(serverUrl);
socket.on('gotData', function(data){
      console.log('Data got in client side');                         
});
</code></pre>

<p><strong>Test Suite:</strong></p>

<pre><code>it('should be sent event to client-side when valid object has provided', function (done) {
   chai.request(server)
                .post('/send')
                .set({'Content-Type':'application/json'})
                .send(data);

   var socket;
   socket = io.connect(server);
   socket.on('gotData',function(){
     console.log('event emitted'); // not get firing after chai request
     assert(true);
     done();
   });
});
</code></pre>
",https://stackoverflow.com/questions/44415070/nodejs-mocha-chai-unit-test-socket-emit-after-chai-request-to-node-event,"['node.js', 'unit-testing', 'mocha.js', 'chai']",701,FALSE,0,1
Apache Camel - Calling method from autowired object in @Produce,"<p>I have the following in a unit test for a Camel route:</p>

<p><b>RouteUnitTest.java</b></p>

<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {RouteUnitTestConfig.class})
public class RouteUnitTest extends CamelTestSupport {
    @Autowired
    MQProperties mqProps;
    @Autowired
    Route route;

    @Produce(uri=""..."")
    ProducerTempalte template;

    @Test
    //rest of test class

}
</code></pre>

<p>The MQProperties object pulls properties from property files, and for unit tests it reads the application-unit-test.properties file, which uses SEDA endpoints for unit testing. I can't seem to get the expression correct in the @Produce tag; I want to set the ProducerTemplates uri to mqProps.getReceiveQueue(), but out of the formats I've tried, I get an exception regarding setting a default endpoint for the producer. I know that it's not an issue with the value that should be passed in, calling template.send(mqProps.getReceiveQueue(), exchange); for example works just fine. I have tried the following formats:</p>

<pre><code>@Produce(uri=""#{@mqProps.getReceiveQueue}"")
@Produce(uri=""{{mqProps.getReceiveQueue}}"")
@Produce(uri=""#{mqProps.getReceiveQueue}"")
</code></pre>

<p>These have thrown the exception mentioned. Am I getting the EL format wrong, or is it an issue with the autowiring?i.e. Maybe the object isn't populated by the time the producer uri stuff is all hooked up? I can't find much else on this, Camel resources talk more around Bean injction etc, but any resources I've seen thus far on the @Produce annotation usually use a hardcoded string, or read from a property file directly</p>
",https://stackoverflow.com/questions/43118277/apache-camel-calling-method-from-autowired-object-in-produce,"['java', 'spring', 'spring-boot', 'apache-camel']",744,FALSE,0,1
What could be causing my NoClassDefFoundError?,"<p>I have an existing project with web services that I'm working to attach Drools to to process business rules on submissions to these services.</p>

<p>Everything seems to work fine in compile-time unit testing, but when I run the project in the Tomcat 7 container on my testing server, I'm getting the following stack trace:</p>

<pre><code>05/25/2017 13:38:53.052 (EDT):[com.myproject.helpers.BusinessRuleHelper.checkBusinessRules]:[SEVERE]- Failed to process our request
05/25/2017 13:38:53.052 (EDT):[com.myproject.helpers.BusinessRuleHelper.checkBusinessRules]:[SEVERE]- Could not initialize class org.drools.compiler.kie.builder.impl.KieContainerImpl
05/25/2017 13:38:53.052 (EDT):[com.myproject.helpers.BusinessRuleHelper.checkBusinessRules]:[SEVERE]- class java.lang.NoClassDefFoundError
05/25/2017 13:38:53.053 (EDT):[com.myproject.helpers.BusinessRuleHelper.checkBusinessRules]:[SEVERE]- java.lang.NoClassDefFoundError: Could not initialize class org.drools.compiler.kie.builder.impl.KieContainerImpl
    at org.drools.compiler.kie.builder.impl.KieServicesImpl.newKieClasspathContainer(KieServicesImpl.java:135)
    at org.drools.compiler.kie.builder.impl.KieServicesImpl.getKieClasspathContainer(KieServicesImpl.java:101)
    at org.drools.compiler.kie.builder.impl.KieServicesImpl.getKieClasspathContainer(KieServicesImpl.java:79)
    at com.myproject.rules.Engine.processRequest(Engine.java:19)
    at com.myproject.helpers.BusinessRuleHelper.checkBusinessRules(BusinessRuleHelper.java:366)
    at com.myproject.helpers.BusinessRuleHelper.checkCriticalErrorBusinessRules(BusinessRuleHelper.java:291)
    at com.myproject.helpers.WebServiceHelper.processWebServiceRequest(WebServiceHelper.java:184)
    at com.myproject.webservicepackage.WebServiceImpl.webService(WebServiceImpl.java:40)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.cxf.service.invoker.AbstractInvoker.performInvocation(AbstractInvoker.java:172)
    at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:88)
    at org.apache.cxf.jaxws.JAXWSMethodInvoker.invoke(JAXWSMethodInvoker.java:63)
    at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:74)
    at org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:58)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at org.apache.cxf.workqueue.SynchronousExecutor.execute(SynchronousExecutor.java:37)
    at org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:106)
    at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:262)
    at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:123)
    at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:206)
    at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:213)
    at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:193)
    at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:127)
    at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:187)
    at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doPost(AbstractHTTPServlet.java:110)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
    at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:166)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:203)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.ajp.AjpProcessor.process(AjpProcessor.java:193)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
</code></pre>

<p>The last line frame under my control, in <code>com.myproject.rules.Engine.processRequest</code> is </p>

<pre><code>/**
 * Runs a Request through the business rule engine
 * @param request The input to validate
 */
public static KieSession processRequest(Request request) {
    // load up the knowledge base
    KieServices ks = KieServices.Factory.get();
    KieContainer kContainer = ks.getKieClasspathContainer(); // &lt;- Error happens here
    // This name matches the ksessionname of the rules knowledge base in the kmodule.xml file
    String kSessionName = ""ksession-rules"";
    KieSession kSession = kContainer.newKieSession(kSessionName);

    // ...process the rules...
}
</code></pre>

<p>I'm confused, because the <code>com.myproject.webservicepackage</code> WAR file contains the Drools JARs in <code>WEB-INF\lib\</code> the way you would expect, and the last few frames are in the same library with the class that Java can't find the definition for.</p>

<p>The Drools JARs I see in the library folder are:</p>

<ul>
<li>drools-compiler-6.5.0.Final.jar</li>
<li>drools-core-6.5.0.Final.jar</li>
<li>kie-api-6.5.0.Final.jar</li>
<li>kie-internal-6.5.0.Final.jar</li>
</ul>

<p>As far as I can tell, there's no overlap between these, and the first one is the library in question.</p>

<hr>

<p>I've continued debugging this, and it looks like this is only the error encountered the second and subsequent requests. The first request came back with this stack trace:</p>

<pre><code>Caused by: java.lang.LinkageError: loader constraint violation: when resolving method ""org.slf4j.impl.StaticLoggerBinder.getLoggerFactory()Lorg/slf4j/ILoggerFactory;"" the class loader (instance of org/apache/catalina/loader/WebappClassLoader) of the current class, org/slf4j/LoggerFactory, and the class loader (instance of org/apache/catalina/loader/StandardClassLoader) for resolved class, org/slf4j/impl/StaticLoggerBinder, have different Class objects for the type LoggerFactory; used in the signature
    at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:299)
    at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:269)
    at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:281)
    at org.drools.compiler.kie.builder.impl.KieContainerImpl.&lt;clinit&gt;(KieContainerImpl.java:92)
    at org.drools.compiler.kie.builder.impl.KieServicesImpl.newKieClasspathContainer(KieServicesImpl.java:135)
    at org.drools.compiler.kie.builder.impl.KieServicesImpl.getKieClasspathContainer(KieServicesImpl.java:101)
    at org.drools.compiler.kie.builder.impl.KieServicesImpl.getKieClasspathContainer(KieServicesImpl.java:79)
    at com.myproject.helpers.rules.Engine.processRequest(Engine.java:19)
    at com.myproject.helpers.BusinessRuleHelper.checkBusinessRules(BusinessRuleHelper.java:366)
    at com.myproject.helpers.BusinessRuleHelper.checkCriticalErrorBusinessRules(BusinessRuleHelper.java:291)
    at com.myproject.helpers.WebServiceHelper.processWebServiceRequest(WebServiceHelper.java:184)
    at com.myproject.webservicepackage.WebServiceImpl.webService(WebServiceImpl.java:40)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.cxf.service.invoker.AbstractInvoker.performInvocation(AbstractInvoker.java:172)
    at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:88)
    ... 37 more
</code></pre>

<p>It looks like it's caching this failure as not having a class definition.</p>
",https://stackoverflow.com/questions/44188581/what-could-be-causing-my-noclassdeffounderror,"['java', 'tomcat7', 'drools', 'kie']",2477,TRUE,0,1
Ruby on Rails - Adding user in test case,"<p>I am really new to the unit testing and i am trying to wrap my head around it. So the situation I have an article form where user can enter <code>title</code> and <code>description</code> and on clicking <code>Create Article</code> article should get created but only a logged in user can perform this operation so I need to test this.</p>

<p>Since I am new to this so this is what I am thinking,</p>

<ol>
<li>I will create a user first</li>
<li>Save it to session as thats how the system checks if the user is logged in (but then i am also thinking its not a browser so this logic might not work), then how do i submit a form as a logged in user?</li>
</ol>

<p>here is my try</p>

<pre><code>require 'rails_helper'

    RSpec.feature 'adding article' do
      scenario 'allow user to add an article' do
        @user = User.create(:email =&gt; ""saadia1@clickteck.com"", :password =&gt; 'password', :username =&gt; 'saadia1')
        session[:user_id] = @user.id

        visit new_article_path

        # @article = Article.user.to eql(@user = User.find_by(id: 6))
        fill_in ""Title"", with: ""My Title""
        fill_in ""Description"", with: ""My description""


        click_on(""Create Article"")

        expect(page).to have_content(""My Title"")
        expect(page).to have_content(""My description"")

      end
    end
</code></pre>

<p>When i run the command <code>rspec spec/features/add_article_spec.rb</code></p>

<p>I see</p>

<blockquote>
  <p>Failures:</p>
  
  <p>1) adding article allow user to add an article
       Failure/Error: session[:user_id] = @user.id</p>

<pre><code> NameError:
   undefined local variable or method `session' for #&lt;RSpec::ExampleGroups::AddingArticle:0x007f89285e32e8&gt;
 # ./spec/features/add_article_spec.rb:6:in `block (2 levels) in &lt;top (required)&gt;'
</code></pre>
  
  <p>Finished in 0.0197 seconds (files took 1.35 seconds to load) 1
  example, 1 failure</p>
  
  <p>Failed examples:</p>
  
  <p>rspec ./spec/features/add_article_spec.rb:4 # adding article allow
  user to add an article</p>
</blockquote>

<p>So my question is how do i add an article as a logged in user? I will really appreciate any help on this.</p>
",https://stackoverflow.com/questions/43273758/ruby-on-rails-adding-user-in-test-case,"['ruby-on-rails', 'rspec', 'capybara', 'rspec-rails']",799,FALSE,0,2
Strange Python package import behavior in Visual Studio,"<p>I encountered a very strange behavior of Python project in VS 2017.
Suppose, I have a ""library"" Python project and also a unit testing project.
When I add the following lines</p>

<pre><code>import unittest
import Metric.metric as metr    // module from the first project
</code></pre>

<p>into file in the second project it works fine (I even can press F12 on 'unitests' and go to __init_ file of unittest framework, or on 'metr' and see contents of metric.py file) <strong>but only until VS reload</strong>.
After reloading the second line no longer works!!! The first line may work but just for a while. After some time (and may be another VS reload) it also breaks down - neither F12 nor unit test discovery not working</p>

<p>Moreover, after I type 'import' and press Ctrl+Space, a 'unittest' hint string <strong>also no longer available</strong> in IntelliSence popup!</p>

<p>What may be the reason of such a strange problem?
I also tried to reproduce it on another toy example with no success - everything works as expected! So you may also be not able to reproduce the problem. The only hope is for someone's intuition.</p>

<p>My settings (all up-to-date):</p>

<p>Visual Studio 2017 15.5.2</p>

<p>Environment - Python 3.6 (64 bit) (global default)</p>
",https://stackoverflow.com/questions/47895807/strange-python-package-import-behavior-in-visual-studio,"['python', 'visual-studio', 'unit-testing', 'package', 'project']",23,FALSE,0,1
how to run / test java application that contains 100s packages,"<p>Before I get bumped here, please point me to the right forum if question does not conform to post rules. I have an enterprise packaged software application I need to work on. One project that contains multiple components is my focus and that I am trying to understand; it has 100's of packages that are a far cry from the simple MVC or backend programs I have developed. </p>

<p>My question is how to run the code if I want to focus on one package only. I don't even know how to run this application as it contains so many parts. I have a demo installed on my system but that tells me from a user perspective what goes on. How do I test specific lasses without being able to run the application itself. Can someone please point me to resources or tutorials on how to do this></p>

<p>EDIT</p>

<p>So I found a test project attached and some test cases. I tried to just right click and run one test class and it failed with tons of compilation errors related to about a third of the packages. Not familiar with unit testing so can someone guide me on this?</p>
",https://stackoverflow.com/questions/46359419/how-to-run-test-java-application-that-contains-100s-packages,"['eclipse', 'testing']",27,FALSE,0,0
Is this a valid unit test?,"<p>(I know plural of Person is People, I just like Persons more..)</p>

<p>I am trying to understand the essence of testing. I have a toy project and in this toy project I have the following class:</p>

<pre><code>package biz.tugay.jpaExamples.dao;

import biz.tugay.jpaExamples.model.Person;
import biz.tugay.jpaExamples.service.EntityManagerService;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import java.util.List;

public final class PersonDaoImpl {

    private EntityManagerService entityManagerService;

    public List&lt;Person&gt; getAll() {
        final EntityManager entityManager = entityManagerService.entityManager();
        final TypedQuery&lt;Person&gt; selectAllPersons = entityManager.createQuery(""SELECT p FROM Person p"", Person.class);
        final List&lt;Person&gt; persons = selectAllPersons.getResultList();
        entityManager.close();
        return persons;
    }

    public void setEntityManagerService(final EntityManagerService entityManagerService) {
        this.entityManagerService = entityManagerService;
    }
}
</code></pre>

<p>This method works just fine when I run my project. I inject an <code>EntityManagerService</code> to it, and when I call <code>getAll()</code> in <code>PersonDaoImpl</code>, I will get the <code>Persons</code> from the database. This is the implementation I have for <code>EntityManagerService</code>, which is not relevant to the question I believe:</p>

<pre><code>package biz.tugay.jpaExamples.service;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public final class EntityManagerServiceByPersistenceUnitNameImpl implements EntityManagerService {

    private final EntityManagerFactory entityManagerFactory;

    public EntityManagerServiceByPersistenceUnitNameImpl(final String persistenceUnitName) {
        this.entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnitName);
    }

    @Override
    public EntityManager entityManager() {
        final EntityManager entityManager = entityManagerFactory.createEntityManager();
        return entityManager;
    }

    @Override
    public void shutDown() {
        entityManagerFactory.close();
    }
}
</code></pre>

<p>So because I am trying to study / understand unit testing, I wanted to create a unit test for <code>PersonDaoImpl</code>. Here it is:</p>

<pre><code>package biz.tugay.jpaExamples.dao;

import biz.tugay.jpaExamples.model.Person;
import biz.tugay.jpaExamples.service.EntityManagerService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import java.util.ArrayList;
import java.util.List;

@RunWith(MockitoJUnitRunner.class)
public class PersonDaoImplTest {

    @InjectMocks
    private final PersonDaoImpl personDao = new PersonDaoImpl();

    @Mock
    private EntityManagerService entityManagerService;

    @Mock
    private EntityManager entityManager;

    @Mock
    private TypedQuery&lt;Person&gt; typedQuery;

    @Test
    public void testGetAll() throws Exception {
        // Given we have 1 person in the database..
        final List&lt;Person&gt; persons = new ArrayList&lt;Person&gt;();
        final Person person = new Person();
        person.setFirstname(""Koray"");
        person.setLastname(""Tugay"");
        persons.add(person);

        // Given entityManagerService returns a valid EntityManager
        Mockito.when(entityManagerService.entityManager()).thenReturn(entityManager);

        // Given entityManager creates a valid TypedQuery
        Mockito.when(entityManager.createQuery(""SELECT p FROM Person p"", Person.class)).thenReturn(typedQuery);

        // Given typedQuery returns the persons from the database when getResultList is called
        Mockito.when(typedQuery.getResultList()).thenReturn(persons);

        // When personDao.getAll is called..
        final List&lt;Person&gt; all = personDao.getAll();

        // Then the returned List must be of size 1.
        Assert.assertTrue(all.size() == 1);

        // And the person in the List returned from the typedQuery must be equal to the person in the initial List.
        final Person returnedPerson = all.get(0);
        Assert.assertTrue(returnedPerson.getFirstname().equals(""Koray""));
        Assert.assertTrue(returnedPerson.getLastname().equals(""Tugay""));
        Mockito.verify(entityManager).close();
    }
}
</code></pre>

<p>Is this a valid unit test? If not, is it because I have bad design in <code>PersonDaoImpl</code> class, and how do I unit test this method properly?</p>

<p>If it is, can you clarify what it is really testing and how it helps me refactoring or making me confident that I am doing the right thing / I am doing what I am doing right?</p>

<p>Because currently, I see absolutely no benefit in writing this test, but I am pretty sure this is my fault so I am trying to understand.</p>
",https://stackoverflow.com/questions/44202672/is-this-a-valid-unit-test,"['java', 'unit-testing', 'junit', 'mockito']",441,TRUE,0,2
Can I swap QObject child keeping signals and slots connected,"<p>Suppose I have class:</p>

<pre><code>class Foo : public QObject{
Q_OBJECT
public:
  ...
private:
  Bar* m_bar;
}
</code></pre>

<p>And for whatever reason, I'd like to replace m_bar with a pointer to an object of DerivedBar. The use case I most often find is when I want to replace it with an object of MockBar (using the google mock framework) for unit testing. </p>

<p>Now I know in most cases, I could just extend the constructor to be something like:</p>

<pre><code>Foo(Bar* bar, QObject* parent)
</code></pre>

<p>and just set m_bar accordingly. </p>

<p>But the problem I have is when the classes are QWidgets and I'm assembling them via Qt Designer. Imagine Foo and Bar are widgets, and Bar is placed inside of Foo from designer; their connections are also set via designer (ie, stored in the qml file). I've tried something like:</p>

<pre><code>Bar* bar = foo.findChild&lt;Bar*&gt;();
bar = new MockBar(&amp;foo);
</code></pre>

<p>(neglecting any memory leaks here, just trying to get functionality) But when I go to set expectations, it does not seem to be connected like the existing one was. Slots aren't called in response to signals. I don't think this is entirely unexpected due to the way connections are made, but I'm wondering if there's a way to get the effect I'm looking for.</p>

<hr>

<p>(nb: for now, using qt 4.8 and gcc 4.6, which does limit some options for c++</p>
",https://stackoverflow.com/questions/44139429/can-i-swap-qobject-child-keeping-signals-and-slots-connected,"['c++', 'qt', 'googlemock']",177,FALSE,0,1
Finding Quartils with cpp,"<p>Problem:</p>

<p>Find the 3 quartils of a set;</p>

<p>The first line contains an integer, n , denoting the number of elements in the array. 
The second line contains n space-separated integers describing the array's elements.</p>

<p>So what are quartils? There are 3 quartiles, the 2nd one is the median, the middle element of your set, if n%2==0 is the sum of the middle 2 devided by 2, the 1st and the 3rd one, we get the first and the second half of our set and we find the medians of these sets, that basicly all, here is full info( <a href=""https://en.wikipedia.org/wiki/Quartile"" rel=""nofollow noreferrer"">https://en.wikipedia.org/wiki/Quartile</a> ).</p>

<p>So I want to submit my code in hackerrank and I can't seem to find my mistake, the test case passes, I made my test and everything is working find but I can't seem to find my mistake, can you help me find it but generally.. what is the way to debug this type of problem where everything is working but the output is not fine for some output ? Can unit testing help me out here? Here is my code:</p>

<pre><code>#include &lt;cmath&gt;
#include &lt;cstdio&gt;
#include &lt;vector&gt;
#include &lt;iostream&gt;
#include &lt;algorithm&gt;

// A utility function to swap two elements
void swap(int* a, int* b)
{
    int t = *a;
    *a = *b;
    *b = t;
}

/* This function takes last element as pivot, places
   the pivot element at its correct position in sorted
    array, and places all smaller (smaller than pivot)
   to left of pivot and all greater elements to right
   of pivot */
int partition (int arr[], int low, int high)
{
    int pivot = arr[high];    // pivot
    int i = (low - 1);  // Index of smaller element

    for (int j = low; j &lt;= high- 1; j++)
    {
        // If current element is smaller than or
        // equal to pivot
        if (arr[j] &lt;= pivot)
        {
            i++;    // increment index of smaller element
            swap(&amp;arr[i], &amp;arr[j]);
        }
    }
    swap(&amp;arr[i + 1], &amp;arr[high]);
    return (i + 1);
}

/* The main function that implements QuickSort
 arr[] --&gt; Array to be sorted,
  low  --&gt; Starting index,
  high  --&gt; Ending index */
void quickSort(int arr[], int low, int high)
{
    if (low &lt; high)
    {
        /* pi is partitioning index, arr[p] is now
           at right place */
        int pi = partition(arr, low, high);

        // Separately sort elements before
        // partition and after partition
        quickSort(arr, low, pi - 1);
        quickSort(arr, pi + 1, high);
    }
}

int getQuartil(int arr[],int len){
    int q=0;
    if(len%2){
        q=arr[len/2]; 
    }else{
        q=(arr[len/2]+arr[len/2-1])/2;

    }
    return q;
}



int main() {
    int n;
    std::cin &gt;&gt; n;
    int arr[n];
    for(int i =0; i &lt; n; i++){
        std::cin &gt;&gt; arr[i];
    }

    quickSort(arr,0,n);
    int q1=getQuartil(arr,n/2);
    int q2=getQuartil(arr, n);
    int q3=getQuartil(arr, (n+n/2+1));    
    std::cout &lt;&lt; q1 &lt;&lt; std::endl;    
    std::cout &lt;&lt; q2 &lt;&lt; std::endl;    
    std::cout &lt;&lt; q3 &lt;&lt; std::endl; 
    return 0;
}
</code></pre>
",https://stackoverflow.com/questions/43127892/finding-quartils-with-cpp,"['c++', 'arrays', 'algorithm', 'math', 'statistics']",39,FALSE,0,0
How to have useful assertion-failure messages for FsUnit?,"<p>I'm using FsUnit 2.3.2 and I'm not happy with the failure messages. See the examples below:</p>

<pre><code>[&lt;Test&gt;]
let ``test 1``() =
    [1; 3]
    |&gt; should equal [1;2]
</code></pre>

<p>... gives me the not-so-helpful message:</p>

<blockquote>
  <p>Expected and actual are both
  Microsoft.FSharp.Collections.FSharpList`1[System.Int32]</p>
  
  <p>at FsUnit.TopLevelOperators.should[a,a](FSharpFunc`2 f, a x, Object y)
  in d:\GitHub\FsUnit\src\FsUnit.NUnit\FsUnit.fs:line 44 at Program.test
  1() in F:\work\playground\fsunit\fsunit\Program.fs:line 9</p>
</blockquote>

<p>A workaround that I found was to use arrays instead of lists:</p>

<pre><code>[&lt;Test&gt;]
let ``test 2``() =
    [|1; 4|]
    |&gt; should equal [|1;2|]
</code></pre>

<p>...produces</p>

<blockquote>
  <p>Expected and actual are both System.Int32[2]<br>
    Values differ at index [1]<br>
    Expected: 2<br>
    But was:  4  </p>
</blockquote>

<p>A second problem is if I have an ADT defined</p>

<pre><code>type MyT = 
    A of int 
    | B of string

[&lt;Test&gt;]
let ``test 4``() =
    A 10
    |&gt; should equal (B ""abc"")
</code></pre>

<p>...gives me the message:</p>

<blockquote>
  <p>Expected: Program+MyT+B<br>
    But was:  Program+MyT+A</p>
</blockquote>

<p>...which I can workaround by implementing ToString for MyT like this:</p>

<pre><code>override this.ToString() = match this with
    | A i -&gt; sprintf ""A(%d)"" i
    | B s -&gt; sprintf ""B(%s)"" s
</code></pre>

<p>...which will lead to a good message:</p>

<blockquote>
  <p>Expected: B(abc)<br>
    But was:  A(10)  </p>
</blockquote>

<p>...but I would like fsunit to just render MyT values the way (sprintf ""%A"") does.</p>

<p>Anyway, having to do these workarounds is NOT OK.</p>

<p>How can I obtain useful messages for F# lists without using arrays? </p>

<p>How to obtain useful messages for ADTs? </p>

<p>Is there a good fix for the above issues or should I just drop FsUnit?</p>

<p>Do you have a better recommendation for a unit testing library for F# that doesn't have these issues?</p>
",https://stackoverflow.com/questions/43393711/how-to-have-useful-assertion-failure-messages-for-fsunit,"['f#', 'nunit', 'fsunit']",698,TRUE,6,1
Does NUnit re-instantiate classes marked as TestFixtures between each test?,"<p>I have a TestFixture marked class which is Unit testing the functionality of a class named 'HideCurrentTitleBarMessageTask'.</p>

<p>In this class I use a substitute to mock an interface in the [Setup] method, and in SOME tests in the test class I setup a return result from one of that mocked interfaces members.</p>

<pre><code>[TestFixture]
public class TestClass_A {

    private ITitleBarMessageModel model;
    private ITitleBarMessage message;
    private HideCurrentTitleBarMessageTask task;
    private bool taskCompleteFired;


    [SetUp]
    public void SetUp() {
        taskCompleteFired = false;
        model = Substitute.For&lt;ITitleBarMessageModel&gt;();
        message = Substitute.For&lt;ITitleBarMessage&gt;();
        //model.currentlyDisplayedMessage = null;
        task = new HideCurrentTitleBarMessageTask();
        task.Init(model);
        task.Completed += (t) =&gt; { taskCompleteFired = true; };
    }

    [Test]
    public void Test_A() {
        task.Execute();
        Assert.That(taskCompleteFired, Is.True);
    }

    [Test]
    public void Test_B() {
        model.currentlyDisplayedMessage.Returns(message);
        task.Execute();
        message.Received(1).Hide();
        Assert.That(taskCompleteFired, Is.False);
    }
}
</code></pre>

<p>HideCurrentTitleBarMessageTask's Execute function looks like this</p>

<pre><code>public override void Execute() {
        if (model.currentlyDisplayedMessage != null) {
            //Some irrelevant stuff
        } else {
            Completed(this);
        }
}
</code></pre>

<p>Notice that only in Test_B, do I setup a return value with <strong>model.currentlyDisplayedMessage</strong>.</p>

<p>If I breakpoint in line 1 of Test_A, I see in the debugger that <strong>model.currentlyDisplayedMessage</strong> is not null, but in fact assigned.  When it shouldn't be. Even though presumably, the method <strong>SetUp</strong> was called prior, and the line</p>

<pre><code>model = Substitute.For&lt;ITitleBarMessageModel&gt;();
</code></pre>

<p>was executed, effectively reassigning a new mocked instance to the model.
This causes Test_A to fail.</p>

<p>Now, notice the commented out line </p>

<pre><code>//model.curentlyDisplayedMessage = null;
</code></pre>

<p>in the SetUp method. Uncommenting this, fixes the issue by explicitly setting the reference in model to null. (I'm also assuming the same result could be achieved in a [TearDown] marked method).</p>

<p>Does NUnit not wipe out the TestClass and start from scratch in between tests? </p>

<p>If not, can anybody tell me why my call to</p>

<pre><code>model = Substitute.For&lt;ITitleBarMessageModel&gt;();
</code></pre>

<p>in the SetUp() method hasn't provided me with a clean mocked instance of the model, to start my test with?</p>
",https://stackoverflow.com/questions/43349775/does-nunit-re-instantiate-classes-marked-as-testfixtures-between-each-test,"['c#', 'nunit', 'nsubstitute']",1188,TRUE,6,1
How to use Gson instead of Jackson for MockMvc?,"<p>I have spent the past day trying to find a solution to this and could not find any online resource that solves this.</p>

<p>I am using Gson for Message conversion for my application, which works fine outside of unit testing. I even added a <code>HttpMessageConverters</code> bean to take precedence over Jackson instead of writing config values to <code>application.yml</code>. This only works when running the application.</p>

<p>Now my question is, how do I use the Gson serialization/deserialization for <code>MockMvc</code>? I have a class with the <code>@SerializedName(""field_one"")</code> annotation which the value differs from the actual name. The closest I got to finding an answer was the one below which didn't help:</p>

<p><a href=""https://stackoverflow.com/a/20510028/3948882"">https://stackoverflow.com/a/20510028/3948882</a></p>

<p>Any ideas how to replace the <code>ObjectMapper</code> or have <code>MockMvc</code> use Gson instead of Jackson?</p>

<hr>

<p>Edit: To add a little more context:</p>

<p>When I try to send a <code>Model</code> which was converted to Json with Gson, it get's immediately refused (400) because I have <code>@NotNull</code> annotation for each field in the model. When it deserializes in the controller, it sets fields to null. The below example has <code>@Valid</code>, which makes sure the <code>Model</code> checks out.</p>

<pre><code>@RequestMapping(value = ""accept"", method = RequestMethod.POST)
public Model resp(@Valid @RequestBody Model model){
    return model;
}
</code></pre>

<p>On the flip side, when I go to hit an endpoint without <code>@Valid</code>, passing a json that pleases Jackson, and I get the a model back, I cannot check any of the fields:</p>

<pre><code>mockMvc.perform(
    post(""/test/accept"")
        .contentType(MediaType.APPLICATION_JSON)
        .content(json))
    .andExpect(jsonPath(""$.field_one"", is(""Hello world!"")))
</code></pre>

<p>Exception:</p>

<pre><code>java.lang.AssertionError: No value at JSON path ""$.field_one"", exception: No results for path: $['field_one']
</code></pre>
",https://stackoverflow.com/questions/46734229/how-to-use-gson-instead-of-jackson-for-mockmvc,"['java', 'jackson', 'gson', 'mockmvc']",734,TRUE,5,1
Redirect pipe acquired by proc_open() to file for remainder of process duration,"<p>Say, in <strong>PHP</strong>, I have bunch of unit tests.
Say they require some service to be running.</p>

<p>Ideally I want my bootstrap script to:</p>

<ul>
<li>start up this service</li>
<li>wait for the service to attain a desired state</li>
<li>hand control to the unit-testing framework of choice to run the tests</li>
<li>clean up when the tests end, gracefully terminating the service as appropriate</li>
<li>set up some way of capturing all output from the service along the way for logging and debugging</li>
</ul>

<p>I'm currently using <code>proc_open()</code> to initialize my service, capturing the output using the pipe mechanism, checking that the service is getting to the state I need by examining the output.</p>

<p>However at this point I'm stumped - how can I capture the rest of the output (including STDERR) for the rest of the duration of the script, while still allowing my unit tests to run?</p>

<p>I can think of a few potentially long-winded solutions, but before investing the time in investigating them, I would like to know if anyone else has come up against this problem and what solutions they found, if any, without influencing the response.</p>

<h2>Edit:</h2>

<p>Here is a cutdown version of the class I am initializing in my bootstrap script (with <code>new ServiceRunner</code>), for reference:</p>

<pre><code>&lt;?php


namespace Tests;


class ServiceRunner
{
    /**
     * @var resource[]
     */
    private $servicePipes;

    /**
     * @var resource
     */
    private $serviceProc;

    /**
     * @var resource
     */
    private $temp;

    public function __construct()
    {
        // Open my log output buffer
        $this-&gt;temp = fopen('php://temp', 'r+');

        fputs(STDERR,""Launching Service.\n"");
        $this-&gt;serviceProc      = proc_open('/path/to/service', [
            0 =&gt; array(""pipe"", ""r""),
            1 =&gt; array(""pipe"", ""w""),
            2 =&gt; array(""pipe"", ""w""),
        ], $this-&gt;servicePipes);

        // Set the streams to non-blocking, so stream_select() works
        stream_set_blocking($this-&gt;servicePipes[1], false);
        stream_set_blocking($this-&gt;servicePipes[2], false);

        // Set up array of pipes to select on
        $readables = [$this-&gt;servicePipes[1], $this-&gt;servicePipes[2]);

        while(false !== ($streams = stream_select($read = $readables, $w = [], $e = [], 1))) {
            // Iterate over pipes that can be read from
            foreach($read as $stream) {
                // Fetch a line of input, and append to my output buffer
                if($line = stream_get_line($stream, 8192, ""\n"")) {
                    fputs($this-&gt;temp, $line.""\n"");
                }

                // Break out of both loops if the service has attained the desired state
                if(strstr($line, 'The Service is Listening' ) !== false) {
                    break 2;
                }

                // If the service has closed one of its output pipes, remove them from those we're selecting on
                if($line === false &amp;&amp; feof($stream)) {
                    $readables = array_diff($readables, [$stream]);
                }
            }
        }

        /* SOLUTION REQUIRED SOLUTION REQUIRED SOLUTION REQUIRED SOLUTION REQUIRED */
        /* Set up the pipes to be redirected to $this-&gt;temp here */

        register_shutdown_function([$this, 'shutDown']);
    }

    public function shutDown()
    {
        fputs(STDERR,""Closing...\n"");
        fclose($this-&gt;servicePipes[0]);
        proc_terminate($this-&gt;serviceProc, SIGINT);
        fclose($this-&gt;servicePipes[1]);
        fclose($this-&gt;servicePipes[2]);
        proc_close($this-&gt;serviceProc);
        fputs(STDERR,""Closed service\n"");

        $logFile = fopen('log.txt', 'w');

        rewind($this-&gt;temp);
        stream_copy_to_stream($this-&gt;temp, $logFile);

        fclose($this-&gt;temp);
        fclose($logFile);
    }
}
</code></pre>
",https://stackoverflow.com/questions/43808182/redirect-pipe-acquired-by-proc-open-to-file-for-remainder-of-process-duration,"['php', 'pipe', 'file-descriptor']",892,TRUE,5,3
Testing component in Android App SDLC?,"<p>""Automated testing is an integral part of the development lifecycle.""</p>

<p>In android app proejcts we've implemented MVP, Rx with Retrofit and Content Provider/SQLite, dagger. Every android apps will always have server communication, storing data in local database,  complex ui like naviagtion drawer and recycler view etc, and difficult navigation flow of application.</p>

<p>What we want to achieve?</p>

<ul>
<li>Few test cases which should be tested every time before we deliver the apk to client or release on play store?(20-30% automate testing)</li>
<li>List of test cases of business logic, which can not be auto tested because whatever reason like complex ui, navigation flow etc (40-60% manual testing)</li>
<li>Continuous Integration</li>
</ul>

<p>Based on above, there are few questions,</p>

<ul>
<li>What to test in auto and manual, how to decide that?</li>
<li>In automate testing, where to test in MVP - Model-View-Presenter layers?</li>
<li>What kind of general business logic should auto test for mobile apps - like registration, login, forgot password, update profile etc?</li>
<li>What type of testing should perform for android apps - unit testing, functional testing, integration testing, manual testing, performance testing, regression testing</li>
<li>Which tool to use - android testing support library, espresso, uiautomator, Robotium, roboelectric, appium, selendroid, mockito, JUnit</li>
</ul>

<p>(Feel free to improve check list as we don't know best practices for testing module in SDLC for android mobile app.) originally asked, <a href=""https://softwareengineering.stackexchange.com/questions/345061/testing-component-in-android-app-sdlc"">here</a>.</p>
",https://stackoverflow.com/questions/43066372/testing-component-in-android-app-sdlc,"['android', 'testing', 'continuous-integration', 'tdd', 'android-testing']",258,TRUE,11,1
Angular 4 writing test properly for a parent route subscription,"<p>I'm trying to write a <code>unit test</code> in <code>Angular 4.3.6</code>.</p>

<p>I have already looked at the following references: </p>

<ol>
<li><p><a href=""https://stackoverflow.com/questions/45789131/how-can-i-create-mockactivatedroute-for-the-parent-routes-of-activatedroute-in-a"">how can i create MockActivatedRoute for the parent routes of ActivatedRoute in angular 4 Unit testing</a></p></li>
<li><p><a href=""https://stackoverflow.com/questions/40789637/how-to-mock-an-activatedroute-parent-route-in-angular2-for-testing-purposes"">How to mock an activatedRoute parent Route in angular2 for testing purposes?</a></p></li>
<li><p><a href=""https://stackoverflow.com/questions/40950552/testing-angular-2-parent-route"">Testing Angular 2 parent route</a></p></li>
</ol>

<p>Thing is - I don't think (I might be completely wrong) I should mock <code>ActivatedRoute</code> in this scenario, for example:</p>

<p>I have a children component which has a <code>subscribe</code> to a parent activated route, like that:</p>

<pre><code>// children.component.ts
ngOnInit() {
  this.activatedRoute.parent.paramMap
    .map(m =&gt; m.get(""contractId""))
    .distinctUntilChanged()
    .subscribe(contractId =&gt; {
      console.log(contractId);
  });
}
</code></pre>

<p>Now I want to write the following test:</p>

<p><code>should call the parent subscription when contractId changes</code></p>

<p>I thought something like that:</p>

<pre><code>it(""should call the parent subscription when contractId changes"", fakeAsync(() =&gt; {
  // Initializes route with contractId 1000
  router.navigate([""1000"", ""Parent"", ""Children""]);

  tick();

  fixture.detectChanges(); // this calls ngOnInit

  // changes the contractId to 2000
  router.navigate([""2000"", ""Parent"", ""Children""]);

  tick();

  expect(component.contractId).toBe(""2000"");
}));
</code></pre>

<p>I get the following error:</p>

<blockquote>
  <p>TypeError: Cannot read property 'paramMap' of null</p>
</blockquote>

<p>I published a plunker for that: <a href=""https://plnkr.co/edit/2SXzvSDe3OiwvvRJYXfN?p=preview"" rel=""nofollow noreferrer"">https://plnkr.co/edit/2SXzvSDe3OiwvvRJYXfN?p=preview</a></p>

<p>Note that in the plunker I wrote two tests. The first one is running just fine, so the router is working.</p>

<p>How can I watch for changes in the route in the unit test and why is <code>parent</code> null?</p>

<p><strong>EDIT:</strong></p>

<p>I updated my plunker with the mocked <code>ActivatedRoute</code> based on <a href=""https://angular.io/guide/testing#create-an-observable-test-double"" rel=""nofollow noreferrer"">ActivatedRouteStub</a>. Then now I get the following error:</p>

<blockquote>
  <p>TypeError: Cannot read property 'paramMap' of undefined </p>
</blockquote>

<p>That is probably because the <strong>stub</strong> does not define parent, consequently it's undefined.</p>

<p>I could define a <code>parent</code> property in the mock, but would this be correct?</p>
",https://stackoverflow.com/questions/45942899/angular-4-writing-test-properly-for-a-parent-route-subscription,"['angular', 'unit-testing']",1149,FALSE,3,0
Are Test Data Factory Methods Dangerous or Beneficial?,"<p>While unit testing with JUnit, I ran into a problem and I want to know if there is a standard solution.</p>

<p>I began using Podam to generate randomized test data, but a coworker correctly remarked that this could lead to unexpected unit test failures. On the one hand this is obviously bad and could make debugging a real pain. On the other hand it could be doing its job by highlighting a code problem.</p>

<p>I identified what I believe to be 3 approaches to solving the issue. Did I miss any options? Are any of these considered standard practice?</p>

<ol>
<li>Factory Method to Generate Randomized Test Data</li>
<li>Factory Method to Return Standard Data</li>
<li>Handcrafted approach, where there is no factory. Each unit test internally declares its own input data and expected output.</li>
</ol>

<p>Further, I think each approach has the following pros and cons. Am I missing any important design considerations?</p>

<p>Pros:</p>

<ol>
<li>Robust testing, easy creation, semi-deterministic through overriding generated values.</li>
<li>Easy creation, easy debugging.</li>
<li>Moderately robust testing and moderately easy to debug.</li>
</ol>

<p>Cons:</p>

<ol>
<li>Unexpected unit test failure (but at least you caught the issue). Harder to debug.</li>
<li>Non-robust testing</li>
<li>Human error, redundant and verbose code, less maintainable, diverse implementations.</li>
</ol>
",https://stackoverflow.com/questions/42633279/are-test-data-factory-methods-dangerous-or-beneficial,"['java', 'unit-testing', 'design-patterns', 'junit']",1030,TRUE,3,1
Karma is loading page instead of test results,"<p>recently we began to rewrite front of our application in Angular 4. I was tasked to focus on unit testing using jasmine and karma. I'm completely new to this framework and test runner and mostly to the whole front so if I miss something really important - sorry for that. So my problem is test html output. When I was running my tests I usually got some information about which failed and what kind of fail occured - that was fine. Since that I was working on tests to finally make some most simple of them to work. Now I started to work on a component activity which required some simple mocks. So here's my spec.ts</p>

<pre><code>import { WelcomeComponent } from ""app/core/welcome/welcome.component"";
import { ComponentFixture } from ""@angular/core/testing"";
import { TestBed } from ""@angular/core/testing"";
import { async } from ""@angular/core/testing"";
import { BusinessAreasService } from ""app/core/services/business-areas/business-areas.service"";
import { CoreModule } from ""app/core/core.module"";
import { Router } from ""@angular/router"";
import { DebugElement } from ""@angular/core/src/debug/debug_node"";
import { By } from ""@angular/platform-browser"";


describe('WelcomeComponent testing', () =&gt; {

  let component: WelcomeComponent;
  let fixture: ComponentFixture&lt;WelcomeComponent&gt;;
  let de: DebugElement;
  let el: HTMLElement;

  let mockBusinessAreasService;
  let mockRouter;


  beforeEach(async(() =&gt; {

    mockBusinessAreasService = {};
    mockRouter = {};

    TestBed.configureTestingModule({
      providers: [
        {
          provide: BusinessAreasService, useValue:     mockBusinessAreasService
        },
        {
          provide: Router, useValue: mockRouter
        }
      ],
      declarations: [WelcomeComponent]
    }).compileComponents();

  }));
  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(WelcomeComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

    component.ngOnInit();

    mockBusinessAreasService = TestBed.get(BusinessAreasService);
    mockRouter = TestBed.get(Router);
  });

  it('BA list shouldnt be empty'), () =&gt; {
    expect(component.baList.length).toBeGreaterThan(0);
  }

  it('check if WelcomeComponent is created', () =&gt; {
    expect(component).toBeDefined();
  });
});
</code></pre>

<p>now my .ts file containing WelcomeComponent:</p>

<pre><code>import { Component, OnInit } from '@angular/core';
import { BusinessAreasService } from ""app/core/services/business-areas/business-areas.service"";
import { Router } from ""@angular/router/"";

@Component({
  selector: 'app-welcome',
templateUrl: './welcome.component.html',
  styleUrls: ['./welcome.component.css']
})
export class WelcomeComponent implements OnInit {

  baList : string[] = [];

  selectedBa : string = """";

  constructor(private businessAreasService : BusinessAreasService, private router: Router) { }

  ngOnInit() {
    console.log(""In welcome component"")
      this.businessAreasService.getUserBAList().subscribe(resposne =&gt;     this.redirectBasedOnBas(resposne), error =&gt; this.baList = [ 'error' ]); 
  }

  redirectBasedOnBas(baList : string[]) {
    if(baList.length === 1) {
      this.applyBusinessArea(baList[0]);
    } else {
      this.baList = baList;
      this.selectedBa = baList[0];
    }
}

  baChanged(ba : string) {
    console.log(ba);
    this.selectedBa = ba;
  }

  applyBusinessArea(ba : string) {
    localStorage.setItem('ba', ba);
      this.router.navigate(['']);
  }
}
</code></pre>

<p>here's my HTML file:</p>

<pre><code>&lt;div class=""container-fluid""&gt;
  &lt;div class=""col-sm-2""&gt;
    &lt;label for=""name"" class=""cols-sm-2 control-label""&gt;Please select your business Area&lt;/label&gt;
  &lt;/div&gt;
  &lt;form class=""form-inline text-md-center""&gt;
    &lt;div class=""col-sm-6""&gt;
    &lt;div class=""input-group""&gt;
        &lt;select class=""form-control"" id=""exampleSelect1"" (change)=""baChanged($event.target.value)""&gt;
                &lt;option *ngFor=""let ba of baList"" [value]=""ba""&gt;{{ba}}    &lt;/option&gt;
        &lt;/select&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    &lt;div class=""col-sm-3""&gt;
      &lt;button type=""button"" class=""btn btn-primary btn-block""     (click)=""applyBusinessArea(selectedBa)""&gt;Submit&lt;/button&gt;
    &lt;/div&gt;
  &lt;/form&gt;
&lt;/div&gt;
</code></pre>

<p>here's my coreModule, we don't have any dedicated module for welcome window,</p>

<pre><code>import { NgModule, Optional, SkipSelf, OnInit } from '@angular/core';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';
import { EnvironmentService } from ""app/core/services/environment/environment.service"";
import { HttpAdapterService } from ""app/core/services/http-adapter/http-adapter.service"";
import { AuthentificationService } from ""app/core/services/authentification/authentification.service"";
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from ""@angular/forms"";
import { WelcomeComponent } from './welcome/welcome.component';
import { BusinessAreasService } from ""app/core/services/business-areas/business-areas.service"";
import { FakeLoginComponent } from ""app/core/fake-login/fake-login.component"";
import { SharedModule } from ""app/shared/shared.module"";
import { SystemSettingsService } from ""app/core/services/system-settings/system-settings.service"";

const SERVICES = [EnvironmentService, HttpAdapterService,     AuthentificationService, BusinessAreasService, SystemSettingsService];
const COMPONENTS = [ FakeLoginComponent ];


@NgModule({
    imports: [RouterModule, BrowserModule, FormsModule, SharedModule],
    providers: [SERVICES],
    declarations: [ WelcomeComponent, COMPONENTS ],
    exports: [HttpModule, COMPONENTS]
})
class CoreModule implements OnInit {

    constructor( @Optional() @SkipSelf() parentModule: CoreModule) {
        if (parentModule) {
            throw new Error('CoreModule has been already loaded! It should be loaded only once!');
        }
        console.log('CoreModule contruct');
    }

    public ngOnInit(): void {
        console.log('CoreModule init');
    }
}

export { CoreModule };
</code></pre>

<p>So the problem lies here - when I run the test I should get failed stack/positive output from it in my browser, what I get is this:
<a href=""https://i.stack.imgur.com/eNExr.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/eNExr.png"" alt=""enter image description here""></a></p>

<p>I bet problem lies in my configure testing modules becuase modyfing it doesn't show the html output from the welcome file, but instead failed stack trace. However all I want is to make this test pass. Anyone can help me?</p>
",https://stackoverflow.com/questions/45878036/karma-is-loading-page-instead-of-test-results,"['angular', 'unit-testing', 'karma-runner', 'karma-jasmine']",625,FALSE,2,1
Creating new object inside class,"<p>I'm still learning about OOP and dependency injection and there's something that I'm struggling with.</p>

<p>Below is a simple class that has a separate database class injected through the constructor and uses the getAll method to return all articles from the database. I understand that DI is prefered and is best practice as it makes the class easy to test with unit testing and decouples it etc.</p>

<pre><code>class Articles {
    private $Database;

    public function __construct(Database $database) {
        $this-&gt;Database = $database;
    }
    public function getAll() {
        return $this-&gt;Database-&gt;query(""SELECT * FROM Articles"");
    }
}
</code></pre>

<p>But what if I want to iterate over all those items in the array and instantiate a new class for each item inside another class? (Which in this case would be a new task that would then be put in the task queue.) I can inject the queue class and reuse that but I can't inject the Task class as I'm instantiating multiple instances of it, so I'm currently instantiating it directly inside the class without injecting it which is bad. Like so:</p>

<pre><code>class Articles {
    private $Database;
    private $Queue;

    public function __construct(Database $database, Queue $queue) {
        $this-&gt;Database = $database;
        $this-&gt;Queue = $queue;
    }
    public function init() {
        $tasks = [];
        $articles = $this-&gt;getAll():
        foreach ($articles as $article) {
            $item = new Task($article);
            $tasks[] = $item;
        }
        $queue = $this-&gt;Queue($tasks);
    }
    public function getAll() {
        return $this-&gt;Database-&gt;query(""SELECT * FROM Articles"");
    }
}
</code></pre>

<p>So how do I accomplish what I desire? I could instantiate the classes inside a controller, but that means deliberately building logic to expose the iterable array to the controller when I'd like it to be done in the init method of the class so all the logic is grouped together.</p>

<p>Any ideas?</p>
",https://stackoverflow.com/questions/43312534/creating-new-object-inside-class,"['php', 'oop', 'dependency-injection']",169,FALSE,2,2
How to implement the repository pattern the right way?,"<p>When implementing the repository pattern for my ASP.NET project, I encountered some problems on which I can't get my head around. So I have a few questions on how to implement the repository pattern the right way.</p>

<p>From my experience I think that having classes/models without behaviour only in my application, next to their repositories is not good OOP. But, this was the way I implemented the repository pattern. I just make everywhere I need an repository instance, to perform some actions. The result of this approach was that all my domain classes didn't have behaviour.</p>

<p>They were just objects holding data with no methods. My teacher said to me that I was using thin models and that I should strive to make fat models.
In response to that feedback, I implemented some business logic in the classes, but I ran into some problems:</p>

<p><strong>Scenario:</strong></p>

<p>My <code>User</code> class had a list of Friends with User objects in it, to represent the friends of a certain user. When adding a new friend to an user the domain class method checks if the ""friend"" already exists in the friends list. If not, he will be added to the list. These changes need to be sent to the database for persistence.</p>

<p>I know this has to be done in the repository for each domain class, but where do the calls to the repository methods belong in the architecture of the application?</p>

<p>Right now I call the repository methods in the domain class methods itself, to persist changes to the database:</p>

<pre><code>public void AddFriend(User friend)
    {
        foreach(User f in Friends)
        {
            if(f.Username == friend.Username)
            {
                throw new Exception(String.Format(""{0} is already a friend."", friend.Username));
            }
        }

        Friends.Add(friend);
        userRepo.AddFriend(this.Id, friend.Id);
    }
</code></pre>

<p>Is this a good approach, because of some reason I think it's not. Regarding to unit testing, we need with this approach some dependancy injection, which says to me that it is not a independent class (good testable unit). I have read some posts from people saying they use an extra service layer or something. I think these kind of abstraction is needed here, but how does a certain service layer look like? What is in it, which methods etc.?</p>

<p>I have seen some other students making use of static methods in a domain class which provides functionality like adding a new object, updating an object, deleting an object, and getting all objects.</p>

<p>Example:</p>

<pre><code>public class Tram
{
    private static TramRepository Repo = new TramRepository(new DBTram());

    public static void AddTram(int tramID, TramType type, int lineNr)
    {
        Tram tram = new Tram(tramID, type, TramStatus.depot, lineNr, true, null);
        Repo.AddTram(tram);
    }

    public static List&lt;Tram&gt; GetAll()
    { 
        Repo.GetAll();
    }
}
</code></pre>

<p>I find it a weird thing to have a method adding a new entity to the database in a domain class, which is that entity itself. Also for the GetAll() method, I think it's weird to have a method in a class itself that gets all trams. So a tram object can get all trams. I think this is a weird way of implementing the repository pattern. Am I right?</p>

<p>So, what kind of abstraction is needed here? Does there have to be an extra layer? If so, how does this layer look like? (Example code) Or am I searching in the wrong direction and is there another solution that counters the problem of unit testing with the repository pattern?</p>

<p>This architecture problem I encounter every time, made sure I need it to be answered.</p>

<p>I find it hard to explain this problem clearly, but I hope you guys understand it.</p>
",https://stackoverflow.com/questions/41767133/how-to-implement-the-repository-pattern-the-right-way,"['c#', 'asp.net', 'architecture', 'repository-pattern']",1745,TRUE,15,2
Autofac DI for RequestContext.Principal using WebAPI2 in a unit test,"<p>I am using Autofac and OWIN in a WebAPI project which was build from scratch (as apposed to the complete WebAPI template available in VS2015). Admittedly I am new to doing it this way.</p>

<p>In the unit test project, I set up an OWIN Startup class at the start of unit testing:</p>

<pre><code>WebApp.Start&lt;Startup&gt;(""http://localhost:9000/"")
</code></pre>

<p>The Startup class is as follows:</p>

<pre><code>[assembly: OwinStartup(typeof(API.Specs.Startup))]

namespace API.Specs
{
    public class Startup
    {
        public void Configuration(IAppBuilder appBuilder)
        {
            var config = new HttpConfiguration();
            //config.Filters.Add(new AccessControlAttribute());
            config.Services.Replace(typeof(IAssembliesResolver), new CustomAssembliesResolver());

            config.Formatters.JsonFormatter.SerializerSettings = Serializer.Settings;
            config.MapHttpAttributeRoutes();

            // Autofac configuration
            var builder = new ContainerBuilder();

            // Unit of Work
            var unitOfWork = new Mock&lt;IUnitOfWork&gt;();
            builder.RegisterInstance(unitOfWork.Object).As&lt;IUnitOfWork&gt;();

            //  Principal
            var principal = new Mock&lt;IPrincipal&gt;();
            principal.Setup(p =&gt; p.IsInRole(""admin"")).Returns(true);
            principal.SetupGet(p =&gt; p.Identity.Name).Returns('test.user');
            principal.SetupGet(p =&gt; p.Identity.IsAuthenticated).Returns(true);

            Thread.CurrentPrincipal = principal.Object;
            if (HttpContext.Current != null)
            {
                HttpContext.Current.User = new GenericPrincipal(principal.Object.Identity, null);
            }

            builder.Register(c =&gt; principal).As&lt;IPrincipal&gt;();

            .
            .
            .
            // Set up dependencies for Controllers, Services &amp; Repositories
            .
            .
            .

            var container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

            appBuilder.UseWebApi(config);
        }

        private static void RegisterAssemblies&lt;TModel, TController, TService, TRepoClass, TRepoInterface&gt;(ref ContainerBuilder builder, ref Mock&lt;IUnitOfWork&gt; unitOfWork) 
            where TModel : class 
            where TRepoClass : class
            where TService : class
        {
            RegisterController&lt;TController&gt;(ref builder);
            var repositoryInstance = RegisterRepository&lt;TRepoClass, TRepoInterface&gt;(ref builder);
            RegisterService&lt;TService&gt;(ref builder, ref unitOfWork, repositoryInstance);
        }

        private static void RegisterController&lt;TController&gt;(ref ContainerBuilder builder) 
        {
            builder.RegisterApiControllers(typeof(TController).Assembly);
        }

        private static object RegisterRepository&lt;TRepoClass, TRepoInterface&gt;(ref ContainerBuilder builder) 
            where TRepoClass : class
        {
            var constructorArguments = new object[] { DataContexts.Instantiate };
            var repositoryInstance = Activator.CreateInstance(typeof(TRepoClass), constructorArguments);
            builder.RegisterInstance(repositoryInstance).As&lt;TRepoInterface&gt;();

            return repositoryInstance;
        }

        private static void RegisterService&lt;TService&gt;(ref ContainerBuilder builder, ref Mock&lt;IUnitOfWork&gt; unitOfWork, object repositoryInstance)
            where TService : class
        {
            var constructorArguments = new[] { repositoryInstance, unitOfWork.Object};
            var serviceInstance = Activator.CreateInstance(typeof(TService), constructorArguments);

            builder.RegisterAssemblyTypes(typeof(TService).Assembly)
                .Where(t =&gt; t.Name.EndsWith(""Service""))
                .AsImplementedInterfaces().InstancePerRequest();

            builder.RegisterInstance(serviceInstance);
        }
    }
}
</code></pre>

<p>Side note: Ideally I would like to set the Principle as part of the test, so as to be able to pass different users to the controller, but if I absolutely have to keep the setting of the CurrentPrincipal/User in the startup class, I can work around it.</p>

<p>The startup class works fine w.r.t accessing my controllers using DI, however the Principal in <code>RequestContext.Principal</code> is never set. It is always null. The way I intent to use the Request context is as follows:</p>

<pre><code>[HttpGet]
[Route(""path/{testId}"")]
[ResponseType(typeof(Test))]
public IHttpActionResult Get(string testId)
{
    return Ok(_service.GetById(testId, RequestContext.Principal.Identity.Name));
}
</code></pre>

<p>I have also tried injecting the mocked principal class into the constructor of my Controller as a workaround - I used the same method as displayed in the generic method for setting up my services using DI. Again however, I only got null in my constructor.</p>

<p>At this point I have been sitting for about a day with this problem and pulling out my hair. Any help would be appreciated. Thanks in advance.</p>
",https://stackoverflow.com/questions/41458123/autofac-di-for-requestcontext-principal-using-webapi2-in-a-unit-test,"['c#', 'asp.net-web-api', 'dependency-injection', 'owin', 'autofac']",768,TRUE,1,1
Using parameters in unit tests in Python 3.x from IDEA,"<p>We run unit tests in Python that have previously been hard coded with information such as which server we want tests to run on. Instead, I'd like to pass that information to the test via command line argument. The problem is that using the Python unit testing framework, I'm stuck calling my custom parameters as a single parameter which is then caught by utrunner.py which assumes that the parameter is about which tests to run (regarding test discovery).</p>

<p>So running from IDEA I send out this command to start up the test suite:</p>

<pre><code>C:\Users\glenp\AppData\Local\Programs\Python\Python36-32\python.exe C:\Users\glenp\.IntelliJIdea2016.3\config\plugins\python\helpers\pycharm\utrunner.py C:\Root\svn\trunk\src\test\python\test.py ""server=deathStar language=klingon""  true
</code></pre>

<p>This is the parameters that get read back to me from <code>print(sys.argv)</code>:</p>

<pre><code>['C:\\Users\\glenp\\.IntelliJIdea2016.3\\config\\plugins\\python\\helpers\\pycharm\\utrunner.py', 'C:\\Root\\svn\\trunk\\src\\test\\python\\schedulePollTest.py', 'server=deathStar language=klingon', 'true']
</code></pre>

<p>Note, I'm not actually calling my own test, I'm calling the utrunner.py with my test as one of the arguments to it.</p>

<p>I get a FileNotFound error: <code>FileNotFoundError: [Errno 2] No such file or directory: 'server=deathStar language=klingon'</code> which kills the test before I get to run it.</p>

<p>I think I need to modify either this:</p>

<pre><code>if __name__ == ""__main__"":
  unittest.main()
</code></pre>

<p>or this:</p>

<pre><code>class testThatWontRun(unittest.TestCase):
</code></pre>

<p>I COULD modify imp.py, which is throwing the error, but I happen to be on a team and modifying core Python functionality isn't going to scale well at all. (And everyone on the team will be sad)</p>

<p>So, is there a way to phrase my arguments in a way that utrunner.py (and imp.py) will ignore those parameters?</p>
",https://stackoverflow.com/questions/41948041/using-parameters-in-unit-tests-in-python-3-x-from-idea,"['python', 'python-3.x', 'unit-testing']",37,FALSE,1,1
Order of objects retrieved from working memory in Drools,"<p>We have been coding a rule that changes the status of billed items that are repeated on the same day and that should only be billed once a day. All items have a status of 2 or 3 to begin with.</p>

<p>If a duplicated code is detected on an item with status 2 or 3, the item will get status 4 and the item in the working memory is updated.</p>

<p>When realising unit testing we can see the results are correct, but once we retrieve the objects from the working memory it seems the order of the items has changed to pretty much random.
Is this normal and why does it happen? (Obviously, the anomaly, if any, could be corrected by just reordering the list again).</p>

<p>Objects are inserted this way:</p>

<pre><code>Iterator&lt;Object&gt; it = objects.iterator();
while (it.hasNext()) {
    sessionStatefull.insert(it.next());
}
</code></pre>

<p>Its log is achieved by adding a logger to the KieSession:</p>

<pre><code>public static KieSession getStatefulKnowledgeSessionWithCallback(KieContainer kieContainer, String sessionName) {
   KieSession kieSession = null;
    try {
        kieSession = getStatefulKnowledgeSession(kieContainer, sessionName);
        kieSession.addEventListener(new RuleRuntimeEventListener() {
            OutputDisplay outputDisplay = new OutputDisplay();

            @Override
            public void objectInserted(ObjectInsertedEvent objectInsertedEvent) {
                outputDisplay.showText(""getStatefulKnowledgeSessionWithCallback.INSERT"", objectInsertedEvent.getObject().toString());               
            }
</code></pre>

<p>The input is always the same:</p>

<pre><code>Item [date=Tue Jul 25 00:00:00 CEST 2017, status=2, id=150107315169800, units=1.0, code=1   ]
Item [date=Tue Jul 25 00:00:00 CEST 2017, status=2, id=150107315169801, units=1.0, code=1   ]
Item [date=Tue Jul 25 00:00:00 CEST 2017, status=2, id=150107315169802, units=1.0, code=2   ]
Item [date=Tue Jul 25 00:00:00 CEST 2017, status=2, id=150107315169803, units=1.0, code=2   ]
Item [date=Tue Jul 25 00:00:00 CEST 2017, status=2, id=150107315169804, units=1.0, code=6358]
Item [date=Tue Jul 25 00:00:00 CEST 2017, status=2, id=150107315169805, units=1.0, code=6007]
Item [date=Tue Jul 25 00:00:00 CEST 2017, status=2, id=150107315169806, units=1.0, code=6007]
Item [date=Tue Jul 25 00:00:00 CEST 2017, status=2, id=150107315169807, units=1.0, code=6385]
Item [date=Tue Jul 25 00:00:00 CEST 2017, status=2, id=150107315169808, units=1.0, code=6005]
Item [date=Tue Jul 25 00:00:00 CEST 2017, status=2, id=150107315169809, units=1.0, code=6225]
</code></pre>

<p>The output is obtained this way:</p>

<pre><code>    List&lt;Object&gt; list = new ArrayList&lt;Object&gt;((Collection&lt;Object&gt;) sessionStatefull.getObjects());
</code></pre>

<p>Its log is obtained with an Iterator:</p>

<pre><code>    Iterator&lt;Object&gt; it2 = list.iterator();
    while (it2.hasNext()) {
        Object object = it2.next();
        outputDisplay.showText(""Result: "", object.toString());
    }
</code></pre>

<p>The printed output always seems to have a random order:</p>

<p>Example 1:</p>

<pre><code>Item [date=Tue Jul 25 00:00:00 CEST 2017, status=2, id=150107315169809, units=1.0, code=6225]
Item [date=Tue Jul 25 00:00:00 CEST 2017, status=4, id=150107315169801, units=1.0, code=1   ]
Item [date=Tue Jul 25 00:00:00 CEST 2017, status=2, id=150107315169800, units=1.0, code=1   ]
Item [date=Tue Jul 25 00:00:00 CEST 2017, status=4, id=150107315169803, units=1.0, code=2   ]
Item [date=Tue Jul 25 00:00:00 CEST 2017, status=2, id=150107315169802, units=1.0, code=2   ]
Item [date=Tue Jul 25 00:00:00 CEST 2017, status=2, id=150107315169807, units=1.0, code=6385]
Item [date=Tue Jul 25 00:00:00 CEST 2017, status=2, id=150107315169805, units=1.0, code=6007]
Item [date=Tue Jul 25 00:00:00 CEST 2017, status=2, id=150107315169804, units=1.0, code=6358]
Item [date=Tue Jul 25 00:00:00 CEST 2017, status=4, id=150107315169806, units=1.0, code=6007]
Item [date=Tue Jul 25 00:00:00 CEST 2017, status=2, id=150107315169808, units=1.0, code=6005]
</code></pre>

<p>Example 2:</p>

<pre><code>Item [date=Tue Jul 25 00:00:00 CEST 2017, status=2, id=150107315169804, units=1.0, code=6358]
Item [date=Tue Jul 25 00:00:00 CEST 2017, status=4, id=150107315169803, units=1.0, code=2   ]
Item [date=Tue Jul 25 00:00:00 CEST 2017, status=4, id=150107315169806, units=1.0, code=6007]
Item [date=Tue Jul 25 00:00:00 CEST 2017, status=2, id=150107315169805, units=1.0, code=6007]
Item [date=Tue Jul 25 00:00:00 CEST 2017, status=4, id=150107315169801, units=1.0, code=1   ]
Item [date=Tue Jul 25 00:00:00 CEST 2017, status=2, id=150107315169808, units=1.0, code=6005]
Item [date=Tue Jul 25 00:00:00 CEST 2017, status=2, id=150107315169807, units=1.0, code=6385]
Item [date=Tue Jul 25 00:00:00 CEST 2017, status=2, id=150107315169800, units=1.0, code=1   ]
Item [date=Tue Jul 25 00:00:00 CEST 2017, status=2, id=150107315169809, units=1.0, code=6225]
Item [date=Tue Jul 25 00:00:00 CEST 2017, status=2, id=150107315169802, units=1.0, code=2   ]
</code></pre>

<p>The logger class is defined like this:</p>

<pre><code>public class OutputDisplay {

    public void showText(String source, String text) {
        try {
            long time = System.currentTimeMillis();
            Date date = new Date(time);
            writeLog(time+"" ""+date.toString()+"" A message from ""+source+"": ""+text);

        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
</code></pre>

<p><em>writeLog</em> opens a file and adds the line. We haven't paid any attention yet to some more sophisticated logging (i.e. logback...).</p>
",https://stackoverflow.com/questions/45328278/order-of-objects-retrieved-from-working-memory-in-drools,"['drools', 'rule']",463,TRUE,0,1
Grabbing text between either double/single quote in Python regex,"<p>I have a bunch (thousands) of old unit testing scripts written with the Selenium RC interface in JavaScript. Since we're upgrading to Selenium 3, I want to try and get rid of some of the RC methods in an automated fashion using Python scripts. I'm iterating through these scripts line by line, picking up the Selenese methods, deconstructing them then attempting to rebuild with the WebDriver interface. For example:</p>

<pre><code>selenium.type(""xpath=//*[text()='test, xpath']"", ""test, text"");
</code></pre>

<p>Would be output as...</p>

<pre><code>driver.findElement(By.xpath(""//*[text()='test, xpath']"")).sendKeys(""test, text"");
</code></pre>

<p>I have a system for automatically identifying the Selenese methods, storing whitespace and separating the method from the parameters, so what I'm left with is the following string:</p>

<pre><code>(""xpath=//*[text()='test, xpath']"", ""test, text"")
</code></pre>

<p>A problem I'm running into is, these aren't always consistent. Sometimes there are double-quotes nested in single-quotes, or vice-versa, or escaped double-quotes nested in double-quotes, etc. For example:</p>

<pre><code>(""xpath=//*[text()=\""test, xpath\""]"", ""test, text"")
('xpath=//*[text()=\'test, xpath\']', 'test, text')
('xpath=//*[text()=""test, xpath""]', 'test, text')
</code></pre>

<p>These are all valid. I want to be able to always match the arguments passed into the method, whether double-quotes are used or single-quotes, plus ignore nested quotes opposite of what's used to open the string as well as escaped quotes, then return them as lists.</p>

<pre><code>['xpath=//*[text()=""test, xpath""]', 'test, text']
</code></pre>

<p>...etc. I've attempted to use the re.findall using the following expression.</p>

<pre><code>([\""'])(?:(?=(\\?))\2.)*?\1
</code></pre>

<p>What I'm getting back is this.</p>

<pre><code>&gt;&gt;&gt; print arguments
[('""', ''), ('""', '')]
</code></pre>

<p>Is there something I'm missing?</p>
",https://stackoverflow.com/questions/46610883/grabbing-text-between-either-double-single-quote-in-python-regex,"['python', 'selenium', 'webdriver']",225,FALSE,0,1
Which approach to use to unit-test this component ? Sociable vs solitary?,"<p>I need to implement a feature that extracts a Zip subfolder into a folder. A candidate interface could be (Java): </p>

<pre><code>interface ZipExtractor {
    void extract(File zipFile, String subfolderName, File targetFolder);
}
</code></pre>

<p>As I intend to implement this interface, I will have two related sub-components: a class that is able to list the files in a zip subfolder, and a class that can extract a single file from a zip.</p>

<p>I googled a lot for best practices in this case and have found some interesting debates like :</p>

<ul>
<li>solitary vs sociable unit tests</li>
<li>mockist vs classic style</li>
<li>""file system access should always be mocked"" vs ""it's OK while test suite run time is not much impacted""</li>
</ul>

<p>What is the best choice :</p>

<ul>
<li>using ZipExtractor as is, give it a real file existing on the file system, and check that files are correctly extracted ? It sounds more like a mini-integration test but the code is smaller and simpler and I test the whole feature.</li>
<li>mock the subcomponents of ZipExtractor to return a fake list of subfiles and not write on the file system, and also add tests on subcomponents ? This is real unit testing but needs some more config from tests so the code is more verbose.</li>
</ul>

<p>My personal feeling would be to use the first approach, but I want other opinions with arguments. Thanks</p>
",https://stackoverflow.com/questions/43718037/which-approach-to-use-to-unit-test-this-component-sociable-vs-solitary,"['java', 'unit-testing', 'junit']",1041,TRUE,0,3
How to test that class __init__ method raises exception using fixture in pytest (Python),"<p>I am trying to get some more skills with pytest (unit testing).</p>

<p>I try to test if an exception is raised when a class is instantiated without a must have parameter.</p>

<p>I tried to create a fixture for that but this leads to a problem that when the fixture is called it tries to create the class inside it with missing parameter and raises my exception before pytest actually asserts that the exception was raised.</p>

<p>I managed to overcome this by not using fixture and just instantiating the class inside the test function but I wonder if there is a more elegant way of using a fixture for that.</p>

<p>Example class:</p>

<pre><code>class MyClass(object):

    def __init__(self, must_have_parameter=None):

    if not must_have_parameter:

        raise ValueError(""must_have_parameter must be set."")
</code></pre>

<p>When trying to use this fixture in a test I naturally get an error.</p>

<pre><code>@pytest.fixture()
def bad_class_instantiation():

    _bad_instance = MyClass()

    return _bad_instance
</code></pre>

<p>Then there is a test:</p>

<pre><code>def test_bad_instantiation(bad_class_instantiation):

    with pytest.raises(ValueError, message=""must_have_parameter must be set.""):

        bad_class_instantiation()
</code></pre>

<p>This test fails as the class gets instantiated before the test case runs (That is my interpretation)?
It still shows that a ValueError occured and the custom message gets displayed.. </p>

<p>If I change the test case to:</p>

<pre><code>def test_bad_instantiation():

    with pytest.raises(ValueError, message=""must_have_parameter must be set.""):

        bad_instance = MyClass()
</code></pre>

<p>Then the test passes.</p>

<p>Is there a way of using a fixture for this or I should just call the class inside the test function and call it a day ?</p>

<p>Thanks for your time.</p>

<p>Tomasz</p>
",https://stackoverflow.com/questions/46720199/how-to-test-that-class-init-method-raises-exception-using-fixture-in-pytest,"['python', 'unit-testing', 'instantiation']",978,TRUE,0,1
Using WordPress outside of WordPress (wp-load.php): &quot;Cannot modify header information - headers already sent&quot;,"<p>I'm trying to use PHP Unit to test an API class that I've written to work with an addon for the WordPress plugin Gravity Forms. The class is dependent on several functions from WordPress such as wp_remote_request(). </p>

<p>In order to have access to these WordPress dependencies, I'm trying to require wp-load.php in my PHP Unit test class using: </p>

<pre><code>define( 'WP_USE_THEMES', false );
require '../../../wp-load.php';
</code></pre>

<p>However, when I try this, I get the following output in my terminal upon running phpunit:</p>

<pre>

    Cannot modify header information - headers already sent by (output started at phar:///usr/local/Cellar/phpunit/6.4.2/libexec/phpunit-6.4.2.phar/phpunit/Util/Printer.php:112)

    ../wp-includes/functions.php:3760
    ../wp-includes/load.php:422
    ../wp-settings.php:110
    ../wp-config.php:228
    ../wp-load.php:37
    ../wp-content/plugins/gravity-dpo/tests/TestCaseAddon.php:37

</pre>

<p>Looking at the wp-includes/functions.php file, I can see the following class at line 3760 within the function dead_db(), which is what causes the error:</p>

<pre><code>header( 'Content-Type: text/html; charset=utf-8' );
</code></pre>

<p>Surely it should be trivial to require wp-load.php so I can test a class with some WordPress dependencies using PHP Unit? I would appreciate any pointers as to what I'm doing wrong here. I'm trying to avoid having to create a fully fledged WordPress unit testing set up because I just want to test one or two functions from my API class.</p>
",https://stackoverflow.com/questions/47460011/using-wordpress-outside-of-wordpress-wp-load-php-cannot-modify-header-inform,"['wordpress', 'phpunit']",1059,TRUE,0,1
JSON posted in body of http.request comes up null on ASP.NET server side,"<p>I am having an issue with posting JSON to my web server I have a ASP.NET web application running on a server that utilizes attribute routing to route requests. Here's the problem area of that project:</p>

<pre><code>[HttpPost]
[Route(""users/new"")]
public string PostDataModel([FromBody] dataModel jsonObj)
{
   try
     {
         WebApiApplication.db.AddToDatabase(jsonObj);
         return ""successfully inserted into database"";
     }
     catch (Exception ex)
     {
         Tools.Logger.log(""[POST DATA][ERROR] : "" + ex.Message);
         return ex.Message;
     }
}
</code></pre>

<p>As of now, using Postman to manually send a POST request with the JSON inserted into the request body, and the Content-Type set to application/json, the function successfully parses the JSON into the correct object specified ([FromBody] DataModel). Also I do have accessors for all the properties in DataModel. </p>

<p>The issue comes in with my unit tests. I created a Node.js project to do some unit testing against the API. I am using the http module to do this. Heres where the requests are made:</p>

<pre><code>req = http.request(options, (response) =&gt; {
     var body = '';

     response.on('data', (d) =&gt; {
        body += d;
     });
     response.on('end', () =&gt; {
        if (options.method == 'POST') {
           options.body = JSON.stringify(options.body);
     });
)};
</code></pre>

<p>the ""options"" parameter is defined as:</p>

<pre><code> var options = {
     method: 'POST',
     host: customSite,
     path: '/users/new',
     headers: { 'Content-Type' : 'application/json' },         
     body: {
            'UserId': ""xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"",
            'UserName': ""Testing Suite"",
            'Name': ""Tester"",
            'Email': ""tester@test.com"",
            'Password': ""fake,"",
            'BirthDate': ""1/1/0001 12:00:00 AM"",
            'NumberOfItems': 0,
            'Links': [],
            'TotalLikes': 100
     },        
 }
</code></pre>

<p>Now when I run the unit test the API throws an exception which is caught which comes out as : <b>""Object reference not set to an instance of an object.""</b></p>

<p>The JSON I'm passing in the unit test is literally copied and pasted from the POST request i used in Postman, which worked. I cannot figure out what the issue is that is causing the API to fail when hit from my Node.js unit tests and to succeed when hit from Postman.</p>
",https://stackoverflow.com/questions/42291059/json-posted-in-body-of-http-request-comes-up-null-on-asp-net-server-side,"['c#', 'json', 'node.js', 'http', 'asp.net-web-api']",409,FALSE,0,0
How to trigger onCreate in Firestore cloud functions shell without using an existing document,"<p>I am using the firebase-tools shell CLI to test Firestore cloud functions.</p>

<p>My functions respond to the onCreate trigger for all documents in a certain collection, by using a wildcard, and then mutate that document with an update call.</p>

<pre><code>firestore
    .document(`myCollection/{documentId}`)
    .onCreate(event =&gt; {
      const ref = event.data.ref
      return ref.update({ some: ""mutation""})
    })
</code></pre>

<p>In the shell I run something like this, (passing some fake auth data required by my database permissions):</p>

<pre><code>myFunction({some: ""data""}, { auth: { variable: { uid: ""jj5BpbX2PxU7fQn87z10d4Ks6oA3"" } } } )
</code></pre>

<p>Hoever this results in an error, because the update tries to mutate a document that is not in the database. </p>

<blockquote>
  <p>Error: no entity to update</p>
</blockquote>

<p>In the <a href=""https://firebase.google.com/docs/functions/unit-testing"" rel=""nofollow noreferrer"">documentation about unit testing</a> it is explained how you would create mocks for event.data in order to execute the function without touching the actual database.</p>

<p>However I am trying to invoke a real function which <em>should</em> operate on the database. A mock would not make sense, otherwise this is nothing more then a unit test.</p>

<p>I'm wondering what the strategy should be for invoking a function like this? </p>

<p>By using an existing id of a document the function can execute successfully, but this seems cumbersome because you need look it up in the database for every test, and it might not be there anymore at some point.</p>

<p>I think it would be very helpful if the shell would somehow create a new document from the data you pass in, and run the trigger from that. Would this be possible maybe, or is there another way?</p>
",https://stackoverflow.com/questions/47346877/how-to-trigger-oncreate-in-firestore-cloud-functions-shell-without-using-an-exis,"['firebase', 'google-cloud-functions', 'google-cloud-firestore']",2766,FALSE,4,1
Micro service architecture for Angular2,"<p>If we take an enterprise  angular 2 web app it has several modules(screens) such as Customer management, Reservations, Booking management, Reporting and etc....</p>

<p>What we normally do is we create common components in a component library and use them on main angular application. The main angular app contains all the modules(screens) with REST API integrations(assuming backed is REST). When app is getting bigger &amp; bigger compile time and rendering consuming more time &amp; resources. Also if one particular area is having a issue we cannot have a release since all are bundle to one app.</p>

<p>As you all know <strong>Micro service architecture</strong> is a method of developing software systems that has grown in popularity. So, my question is can we apply same architecture for these type of enterprise angular 2 apps?. </p>

<p>It is like this. We have a customer management as a separate angular app. Again Booking management is another angular app. Reporting is another app. These apps are going to be separate war files when deploying to the web server. </p>

<p>Once we have developed such loosely coupled apps this will reduce the over head of project size, compile time &amp; resources. Also this will make unit testing more easier. Particular set of developers are only considering the only one unit of the module.</p>

<p>Kindly share your expert thoughts about this</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/46404449/micro-service-architecture-for-angular2,"['angular', 'design-patterns', 'architecture', 'microservices']",1057,TRUE,4,1
Injecting request ID in Web API,"<p>I want to maintain an ID (<code>Guid.NewGuid()</code> will suffice) throughout processing request so later I can check logs for a given ID. I'm also returning the ID to the caller in response headers (and messages) in case of an error, they have a reference.</p>

<p>First I did this in the application's Global.asax <code>Application_BeginRequest()</code> method, where I put the ID in the <code>HttpContext.Current.Items</code> collection.</p>

<pre><code>protected void Application_BeginRequest(object sender, EventArgs e)
{
    var context = HttpContext.Current;
    if (context != null)
    {
        var reqguid = Guid.NewGuid().ToString(""D"");
        context.Items.Add(""sessionid"", reqguid);
    }
}
</code></pre>

<p>This worked fine in previous applications, but I felt a bit iffy about using <code>HttpContext</code> in a ""modern"" Web API application.</p>

<p>Then I turned to Action Filters, because apparently that's the bees knees for Web API</p>

<pre><code>public class ManageRequestHeadersFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        actionContext.Request.Properties.Add(""sessionid"", Guid.NewGuid().ToString(""D""));
    }

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        var sessionId = actionExecutedContext.Request.Properties[""sessionid""].ToString();
        if (sessionId != null)
        {
            actionExecutedContext.Response.Headers.Add(""App-Session-Id"", sessionId);
        }
    }
}
...
config.Filters.Add(new ManageRequestHeadersFilter());
</code></pre>

<p>This worked OK too, until I wanted to get to the <code>Request</code> object in the <code>ApiController</code> constructor to set a helper property to the ID. Since the controller constructor runs before the filter, the <code>Request</code> object is null. Again, I could probably use the <code>HttpContext.Current</code> way, but that beats the purpose of filters.</p>

<p>I also thought of using dependency injection (already using Autofac) to inject the ID into the constructor, which again, worked, but now I'd be doing things a bit backwards which feels weird to my original train of thought.</p>

<p>My feeling is that passing in the ID as a controller constructor parameter will ultimately be the winner, because when Unit Testing, I shouldn't be relying on anything HTTP anyway.</p>

<p>Is there already a best practice for this?</p>
",https://stackoverflow.com/questions/42696383/injecting-request-id-in-web-api,"['c#', 'asp.net-web-api2']",2677,FALSE,4,0
achilles Cassandra mock server: no libsigar-universal64-macosx.dylib in java.library.path,"<p>I use a <a href=""https://github.com/doanduyhai/Achilles"" rel=""nofollow noreferrer"">archilles cassandra mock server</a> to perform unit testing for my java maven project and everything works fine except I get an exception printed out in the console:</p>

<blockquote>
  <p>org.hyperic.sigar.SigarException: no libsigar-universal64-macosx.dylib
  in java.library.path  at
  org.hyperic.sigar.Sigar.loadLibrary(Sigar.java:172)   at
  org.hyperic.sigar.Sigar.(Sigar.java:100)  at
  org.apache.cassandra.utils.SigarLibrary.(SigarLibrary.java:47)
    at
  org.apache.cassandra.utils.SigarLibrary.(SigarLibrary.java:28)
    at
  org.apache.cassandra.service.StartupChecks$7.execute(StartupChecks.java:216)
    at
  org.apache.cassandra.service.StartupChecks.verify(StartupChecks.java:112)
    at
  org.apache.cassandra.service.CassandraDaemon.setup(CassandraDaemon.java:187)
    at
  org.apache.cassandra.service.CassandraDaemon.activate(CassandraDaemon.java:585)
    at
  info.archinnov.achilles.embedded.ServerStarter.lambda$start$0(ServerStarter.java:164)
    at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)</p>
</blockquote>

<p>This problem does influence the test results but I don't like to see it in the console, especially because my colleagues are likely to see it when they perform maven install. </p>

<p>I have seen some solutions to this problem however they involve local  configurations in my machine (e.g. manually adding a jar file to some local directory). This is not an option because I don't want my colleagues to reproduce this problem and I don't want to force them to do those configurations. </p>

<p>Therefore, I am looking for a fix that involves only the project itself (e.g. add one or more dependencies to my pom.xml to make this exception go away), so that the next pulled version of my project from the repository does not print this exception during build, without any local configuration.</p>

<p>Thank you for your help.</p>
",https://stackoverflow.com/questions/45141640/achilles-cassandra-mock-server-no-libsigar-universal64-macosx-dylib-in-java-lib,"['java', 'maven', 'unit-testing', 'cassandra', 'sigar']",1237,FALSE,4,0
Angular 1.x Testing with Jasmine: Compiling a template not working to verify data output in template,"<p>I am trying to unit test an html template that has variables in paragraph, anchor tags, and <code>{{header.title || translate}}</code> however no matter what posts I have tried it does not seem to work. I get the retrieved HTML template and when it is compiled it is still the same. In the template I still see <code>{{user}}</code> for example. It seems none of them are actually being compiled.</p>

<p><strong>Current Template Output:</strong></p>

<pre><code>&lt;h1&gt;{{header.title | translate}}&lt;/h1&gt;
&lt;h2&gt;{{homeCtrl.name}}&lt;/h2&gt;
</code></pre>

<p><strong>Expected Output:</strong></p>

<pre><code>&lt;h1&gt;Cake Blogger&lt;/h1&gt;
&lt;h2&gt;Alexandria&lt;/h2&gt;
</code></pre>

<p><strong>Test Suite:</strong></p>

<pre><code>(function() {
  'use strict';

  describe('home.tpl.html', function() {
    var scope, controller, createController, template, element, rootScope;

    beforeEach(module('Templates'));
    beforeEach(module('mainApp'));

    /**
      @name: home.tpl.html
      @description: Inject and set test related objects
      @param {Service} rootScope - Used to get the language
      @param {Compiler} $templateCache - Holding the compiled template
      @param {Injector} $compile - Compiles an HTML string or DOM
    */
    beforeEach(inject(
      function(_$controller_, _$rootScope_, $templateCache, $compile) {
        scope = _$rootScope_.$new();
        createController = function() {
          return _$controller_('homeCtrl', {
            '$scope': scope
         });
      };

      controller = createController();

      rootScope = _$rootScope_;
      template = $templateCache.get('home.tpl.html');
      element = $compile(template)(rootScope);

      // var ctrl = element.controller('homeCtrl');
      rootScope.$digest();
      console.log(""home page"", element);
  }));

  /**
    @name: Describe Block - home.tpl.html
    @description: Test cases related to home.tpl.html
  */
  describe('home.tpl.html tests', function() {
    fit('should have ""Alexandria""', function() {
      expect(element.html()).toContain(""Alexandria"");
    });
  });
});
})();
</code></pre>

<p><strong>Karma File:</strong></p>

<pre><code>files: ['list of files'],

port: 8080,

browsers: [
  'PhantomJS'
],

plugins: [
  'karma-phantomjs-launcher',
  'karma-jasmine',
  'karma-ng-html2js-preprocessor',
],

preprocessors: {
  'app/**/*.tpl.html': 'html2js'
},

ngHtml2JsPreprocessor: {
  'moduleName': 'Templates',
  'stripPrefix': 'app/'
}
</code></pre>

<p><strong>package.json</strong></p>

<pre><code>{
  ""name"": """",
  ""private"": true,
  ""devDependencies"": {
    ""autoprefixer-core"": ""^5.2.1"",
    ""grunt"": ""^0.4.5"",
    ""grunt-angular-templates"": ""^0.5.7"",
    ""grunt-concurrent"": ""^1.0.0"",
    ""grunt-contrib-clean"": ""^0.6.0"",
    ""grunt-contrib-compass"": ""^1.0.0"",
    ""grunt-contrib-concat"": ""^0.5.0"",
    ""grunt-contrib-connect"": ""^0.9.0"",
    ""grunt-contrib-copy"": ""^0.7.0"",
    ""grunt-contrib-cssmin"": ""^0.12.0"",
    ""grunt-contrib-htmlmin"": ""^0.4.0"",
    ""grunt-contrib-imagemin"": ""^1.0.0"",
    ""grunt-contrib-jshint"": ""^0.11.0"",
    ""grunt-contrib-uglify"": ""^0.7.0"",
    ""grunt-contrib-watch"": ""^0.6.1"",
    ""grunt-filerev"": ""^2.1.2"",
    ""grunt-google-cdn"": ""^0.4.3"",
    ""grunt-jscs"": ""^1.8.0"",
    ""grunt-karma"": ""*"",
    ""grunt-modernizr"": ""^1.0.2"",
    ""grunt-newer"": ""^1.1.0"",
    ""grunt-ng-annotate"": ""^0.9.2"",
    ""grunt-ng-constant"": ""^2.0.1"",
    ""grunt-postcss"": ""^0.5.5"",
    ""grunt-svgmin"": ""^2.0.0"",
    ""grunt-usemin"": ""^3.0.0"",
    ""grunt-wiredep"": ""^2.0.0"",
    ""jasmine-core"": ""^2.4.1"",
    ""jit-grunt"": ""^0.9.1"",
    ""jshint-stylish"": ""^1.0.0"",
    ""karma"": ""^0.13.22"",
    ""karma-coverage"": ""^0.5.5"",
    ""karma-fixture"": ""^0.2.6"",
    ""karma-jasmine"": ""*"",
    ""karma-json-fixtures-preprocessor"": ""0.0.6"",
    ""karma-json-preprocessor"": ""^0.3.3"",
    ""karma-junit-reporter"": ""^1.2.0"",
    ""karma-ng-html2js-preprocessor"": ""~0.1.0"",
    ""karma-phantomjs-launcher"": ""*"",
    ""phantomjs"": ""^2.1.7"",
    ""time-grunt"": ""^1.0.0""
  },
  ""engines"": {
    ""node"": ""&gt;=0.10.0""
  },
  ""scripts"": {
    ""test"": ""grunt test""
  },
  ""dependencies"": {}
}
</code></pre>

<p>According to posts I have read such as this plunker from a post <a href=""http://plnkr.co/edit/lBvAkNgYTaEMEHqW3yMZ?p=preview"" rel=""nofollow noreferrer"">plunker example</a>, this should be working correctly. I am thinking perhaps the controller is not binding to the scope so that when <code>$digest</code> runs the template cannot find the controller maybe.</p>

<p><strong>Helpful Information:</strong></p>

<ul>
<li>Where it says <code>rootscope.$digest()</code> I also tried it as <code>scope.$digest()</code>, I also tried using <code>$apply()</code>.</li>
<li>I am using <code>ngHtml2JsPreprocessor</code></li>
<li>I am using <code>TemplateCache</code></li>
<li>I am using <code>$compile</code></li>
</ul>

<p><strong>Links viewed:</strong></p>

<ul>
<li><a href=""https://stackoverflow.com/questions/39914201/how-to-access-controller-in-directive-jasmine"">how to access controller in directive [jasmine]</a></li>
<li><a href=""https://stackoverflow.com/questions/27238220/compile-not-compiling-templates-in-karma-jasmine"">$compile not compiling templates in Karma/Jasmine</a></li>
<li><a href=""https://stackoverflow.com/questions/31827101/dont-work-compile-in-jasmine-karma-angular"">Don&#39;t work $compile in Jasmine Karma Angular</a></li>
<li><a href=""https://stackoverflow.com/questions/15214760/unit-testing-angularjs-directive-with-templateurl"">Unit Testing AngularJS directive with templateUrl</a></li>
</ul>

<p>The template returns but the angular in the template is never compiled. Always seeing <code>{{homeCtrl.name}}</code> instead of <code>Alexandria</code>.</p>

<p><strong>Update 1.1</strong></p>

<p>I am thinking perhaps since the translate <code>{{header.title | translate}}</code> is not working that maybe <code>angular-translate</code> (module: <code>pascalprecht.translate</code>) is not actually working correctly and is then causing the controller to also fail binding. Will continue investigation.</p>
",https://stackoverflow.com/questions/44809743/angular-1-x-testing-with-jasmine-compiling-a-template-not-working-to-verify-dat,"['angularjs', 'unit-testing', 'jasmine', 'karma-jasmine', 'angular-templatecache']",640,TRUE,3,1
"PHPUnit test error, cannot find class","<p>I'm new in PHPUnit and unit-testing, so I was install PHPUnit and phar via composer and everything had been going fine until I was try to start my simple test. I'm using PhpStorm where I can see all classes were autoload, but when I trying to start my test I got an error: </p>

<pre><code>Fatal error: Class 'PharIo\Manifest\Simple' not found in C:\xampp\htdocs\mydocs\
</code></pre>

<p>I don't understand why he is looking for It in folder upper than PHPUnit is exists ? </p>

<p>I was trying to configure autoload section in composer.json and checking settings in phpunit.xml but nothing works.</p>

<p><strong>Add:</strong></p>

<p>I have to reinstall PHPUnit without PharIO, so now I have a little bit of progress, now I have a situation where I can test my class if I make require_once line with a name of the tested class. It looks like:</p>

<pre><code>require_once '../src/Simple.php';

class SimpleTest extends PHPUnit_Framework_TestCase
{

    public function testAdd() {

        $sum = new Simple();

        $this-&gt;assertEquals(5, $sum-&gt;add(2, 3));

    }

}
</code></pre>

<p>So my simple class is:</p>

<pre><code>class Simple {

public function add($a, $b) {

    return (int) $a + (int) $b;

}

}
</code></pre>

<p>But, of course, I want to use namespaces. I try to make some changes based on this question: <a href=""https://stackoverflow.com/questions/15710410/autoloading-classes-in-phpunit-using-composer-and-autoload-php"">Autoloading classes in PHPUnit using Composer and autoload.php</a> (I was try even use that repo for test, but an error is still exists) but nothing works for me. I was try to edit my autoload section in the composer.json like this</p>

<pre><code>""autoload"": {
    ""psr-4"": {
        ""app\\"": ""src/""
    }

},
</code></pre>

<p>But an error is still exists, another words autoload cannot see It. I was create phpunit.xml and phpunit.dist.xml with a same settings</p>

<pre><code>&lt;phpunit
        xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
        xsi:noNamespaceSchemaLocation=""http://schema.phpunit.de/3.7/phpunit.xsd""
        backupGlobals=""true""
        backupStaticAttributes=""false""
        colors=""true""
        convertErrorsToExceptions=""true""
        convertNoticesToExceptions=""true""
        convertWarningsToExceptions=""true""
        processIsolation=""false""
        stopOnFailure=""false""
        syntaxCheck=""false""
        bootstrap=""./tests/bootstrap.php""&gt;

        &lt;testsuites&gt;
                &lt;testsuite name=""The project's test suite""&gt;
                        &lt;directory&gt;./tests&lt;/directory&gt;
                &lt;/testsuite&gt;
        &lt;/testsuites&gt;
&lt;/phpunit&gt;
</code></pre>

<p>and I made tests/bootstrap.php too with</p>

<pre><code>require_once '../vendor/autoload.php';
</code></pre>
",https://stackoverflow.com/questions/41816506/phpunit-test-error-cannot-find-class,"['php', 'unit-testing', 'phpunit', 'phpstorm', 'autoload']",9450,TRUE,3,3
xUnit Tests skipped,"<p>In my <code>VS2017</code> solution I have several unit test projects.
In on of them my <code>xUnit</code> tests do not get discovered by <code>mstest</code> and therefore are not run.</p>

<p>I do get the warning:</p>

<blockquote>
  <p>Warning: [xUnit.net 00:00:00.7641189] Skipping: Testing.UnitTests (could not find dependent assembly 'Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.0.0')</p>
</blockquote>

<p>But <strong><em>Microsoft.VisualStudio.QualityTools.UnitTestFramework</em></strong> is referenced in the project in exactly that version.
I have multiple unit testing projects. Many of them contain xUnit tests as well, but they get found and executed without any problems.</p>

<p>All projects containing xUnit tests have the same xUnit nuget packages assigned, especially <code>xunit.runner.visualstudio</code></p>

<p>I am also using NCrunch and NCrunch has no problem discovering and execution the xUnit tests in question.</p>

<p>What could possibly be the reason to my problems?</p>

<p><strong>Further Findings:</strong></p>

<ul>
<li>After upgrading <strong><em>Microsoft.VisualStudio.QualityTools.UnitTestingFramework</em></strong> to version 10.1.0.0, the xUnit tests were found but then I suddenly had 438 from 2447 failing. Those failing tests -mostly not xUnit - were previously working fine.</li>
<li>After shutting down an restarting visual studio the UnitTeestingFramework was automatically reset to version 10.0.0</li>
<li>opening the Reference Manager (Add References) all the project references are shown by selected checkboxes except of <strong><em>Microsoft.VisualStudio.QualityTools.UnitTestingFramework</em></strong> which only shows up if I previously add e.g. ""Quality"" to the search box, but then I see <strong><em>Microsoft.VisualStudio.QualityTools.UnitTestingFramework</em></strong> three times. One checked (version 10.0.0.0) an other one with same version, but different path and one with version 10.1.0.0</li>
</ul>

<p>All together looks quite odd to me...</p>
",https://stackoverflow.com/questions/47098513/xunit-tests-skipped,"['c#', 'visual-studio-2017', 'xunit.net']",2564,TRUE,3,1
Dependency Injection in Node with many imports,"<p>I'm trying to figure out where dependency injection has it's place in Node. I can't seem to get my head around it even though I know how it works in Java and I've been reading countless blogs.</p>

<p>The examples on the net imo are to <em>trivial</em>. they don't really show Why DI is needed. I'd prefer a complicated example.</p>

<p>I've looked at the following frameworks:</p>

<p><a href=""https://github.com/young-steveo/bottlejs"" rel=""nofollow noreferrer"">https://github.com/young-steveo/bottlejs</a></p>

<p><a href=""http://inversify.io/"" rel=""nofollow noreferrer"">http://inversify.io/</a></p>

<p>Now, Node uses the module pattern. When I do an import it receives a singleton since that's what node does, it caches modules, unless the factory pattern is used to return a new instance (return new MyThing()).</p>

<p>Now dependency injections primary function is to decouple everything.</p>

<p>When people say that, I get the notion that the goal is... To remove <em>all</em> the imports from the top of a module.</p>

<p>How I write today:</p>

<pre><code>'use strict';

// node modules
import os from 'os';
...8 more modules here
import fs from 'fs';
// npm modules
import express from 'express';
...8 more modules here
import _ from 'lodash';
// local modules
import moduleOne from './moduleOne';
...8 more modules here
import moduleTen from './moduleTen';

//...rest of my code
</code></pre>

<p>Having 30 imports is a pain to change. Having the same 30 in multiple files is an even bigger pain.</p>

<p>I was reading <a href=""https://blog.risingstack.com/fundamental-node-js-design-patterns/"" rel=""nofollow noreferrer"">https://blog.risingstack.com/fundamental-node-js-design-patterns/</a> and I looked at the dependency injection area. In the example 1 dependency is passed, fine. What about <em>30</em>? I don't think that would be good practice?</p>

<p>How would one structure such an application with so many dependencies? And make it friendly for unit testing and mocking?</p>
",https://stackoverflow.com/questions/41543585/dependency-injection-in-node-with-many-imports,"['node.js', 'dependency-injection']",730,FALSE,2,1
Testing Async Methods with Jasmine - Wrong Test Case Failing,"<p>I'm unit testing a function in angluar2 which returns a Promise. Below is a simplified version of my function:</p>

<pre><code>getItems(orderId: string): Promise&lt;ItemsModel&gt; {
    return this.authHttp.get('https://my-api-url').toPromise&lt;ItemsResponseModel&gt;().then(ItemsResponseModel =&gt; {
        let itemsModel = new ItemsModel();

        // Mapping values from ItemsResponseModel to ItemsModel

        return itemsModel;
    });
}
</code></pre>

<p>authHttp is the service from angular2-jwt which returns an Observable after each method call.</p>

<p>This is how I mock my service:</p>

<pre><code>let callback: string;

beforeEach(() =&gt; {
    itemsResponseModel = new ItemsResponseModel();
    mockAuthHttp = jasmine.createSpyObj('mockAuthHttp', ['get']);
    mockAuthHttp.get.and.callFake((url: string) =&gt; {
        callbackUrl = url;
        return Observable.of(itemsResponseModel);
    });
    myService = new MyService(mockAuthHttp);
});
</code></pre>

<p>Now, I want to test this function. So, this is the way with which I'm testing it:</p>

<pre><code>it('should call with correct url', (done: any) =&gt; {
    myService.getItems('123').then(itemsModel =&gt; {
        expect(callbackUrl).toBe('https://my-api-url');
        done();
    });
});

it('should have correct value1', (done: any) =&gt; {
    myService.getItems('123').then(itemsModel =&gt; {
        expect(itemsModel.value1).toBe('something');
        done();
    });
});
</code></pre>

<p>These simple test cases were also failing until I added that ""done"" function and then they passed.</p>

<p>The problem is when I want to use my new it_multiple function for a test, I can't pass a ""done"" function. I wrote that function to support multiple test cases in just one test. I don't know how I can extend this function to accept a ""done"" function. I hope after passing ""done"" function in a correct way, I wouldn't have problems with tests written by this function.</p>

<pre><code>function it_multiple(description: string, callback: any, testCases: Array&lt;Array&lt;any&gt;&gt;): void {
    for (let i = 0; i &lt; testCases.length; i++) {
        let testCase = testCases[i];
        it (`${description} (${testCase.join(', ')})`, () =&gt; {
            callback.apply(null, testCase);
        });
    }
}

it_multiple('should have correct value1 for different item ids', (itemId: string, expectedValue1: string) =&gt; {
    myService.getItems(itemId).then(itemsModel =&gt; {
        expect(itemsModel.value1).toBe(expectedValue1);
    });
}, [
    [null, 'nothing'],
    [undefined, 'nothing'],
    ['123', 'something']
]);

it('some other tests', () =&gt; {
    expect(true).toBeTruthy();
});
</code></pre>

<p>Currently, not also do these test cases fail, but also Jasmine shows the next ""it"" description as the failed test. It says ""some other tests"" has failed plus two of those three cases in it_multiple! Any ideas how I can have a ""done"" function for my it_multiple? I had the same issue with ""it"" before that ""done"". I think that's the problem here too. If you think otherwise, please also let me know...</p>
",https://stackoverflow.com/questions/44514426/testing-async-methods-with-jasmine-wrong-test-case-failing,"['unit-testing', 'typescript', 'jasmine', 'angular2-services']",159,FALSE,2,0
Add optional message parameter to assertEquals,"<p>Disclaimer: I'm totally new to Haxe, but I have experience in many other languages.</p>

<p>I have tests similar to the following:</p>

<pre><code>  function doTest(type:SomethingMagic, tests:Array&lt;Array&lt;Int&gt;&gt;) {
    for (t in tests) {
      var res = DoSomeMagicalWork(t[0], t[1], t[2], t[3], t[4], t[5], t[6], t[7]);
      assertEquals(type, res.type);
    }
  }
</code></pre>

<p>The problem with this is that the unit test framework, when run on many different arrays, doesn't give me the correct line for which the test failed. In other words, if I'm running this method with a bunch of arrays, like:</p>

<pre><code> doTest(SOME_MAGIC_TYPE,
    [[0, 0, 0, 1625, 0, 35, 0, 0, 0, 0, 0],
    ...
 ]);
</code></pre>

<p>and one of these lines fails, it doesn't tell me <em>which</em> line failed. Now, I know that I could probably restructure these tests to be a bit more intuitive anyway, but this was written by someone else, and I don't have the ability to change each of these at the moment.</p>

<p>What I'd like to do is the following:</p>

<pre><code>  function doTest(type:SomethingMagic, tests:Array&lt;Array&lt;Int&gt;&gt;) {
    var number = 0;
    for (t in tests) {
      var res = DoSomeMagicalWork(t[0], t[1], t[2], t[3], t[4], t[5], t[6], t[7]);
      assertEquals(type, res.type, ""Test #"" + number + "" for type "" + type);
      number++;
    }
  }
</code></pre>

<p>So, basically, I'd like to be able to pass in some extra messaging information to the <code>assertEquals</code> function, similar to what one can do in other unit testing frameworks. Then, upon failure, it would output the standard assertion message, possibly appended by the additional message I sent as a parameter to the function. Originally, I thought it was as simple as sub-classing <code>haxe.TestCase</code>, but that doesn't appear to be quite as simple as I thought, due to the way Haxe interprets types (apparently).</p>

<p>Has anyone had success with something similar to this that could give me a recommendation on how to accomplish it?</p>
",https://stackoverflow.com/questions/41558556/add-optional-message-parameter-to-assertequals,"['unit-testing', 'haxe']",549,TRUE,2,2
Mocking dependencies inside of an AOP object using Testbox and AOP/1,"<p>I am curious if there is an easier way to mock the dependencies inside a component that uses AOP.</p>

<p>For example I have a component that uses CRUD methods to persist changes to the database. For audit logging I figured I could use AOP so I didn't have to put my logging calls inside of the methods. The issue that I am running into is during unit testing when I want to mock the database and session storage used inside the object that provides the AOP. The only way I have been able to figure out how to fake the database and session is to create a new mock component file that extends the original and then overrides the init method. Using this method is not very flexible as I have to create several extra files for a simple unit test. Below is some of the test code:</p>

<p>This is the bean that gets created with the di/1 bean factory:</p>

<pre><code>//customerBean.cfc
component accessors=""true"" extends=""models.abstracts.AbstractModel"" displayname=""Customer"" {
    property name=""ID""  type=""numeric"" default=""0"";
    property name=""Name"" type=""string"" length=""100"" default=""&lt;Unknown&gt;"" logEvents=""update"";
    property name=""Type"" type=""string"" default=""Homeowner"" logEvents=""update"";
    property name=""Status"" type=""string"" default=""Active"" logEvents=""update"";

    public any function init(customerDAO) {
        variables.DAO = arguments.customerDAO;
    }

}
</code></pre>

<p>Here is the component that the customerBean extends:</p>

<pre><code>//abstractModel.cfc
component accessors=""true"" {

    public any function doCreate(required struct data) {
        setID(save());
        return getID();
    }
}
</code></pre>

<p>This is the AOP component that has two dependencies that need to be mocked:</p>

<pre><code>//customerLogger.cfc
component accessors=""true"" {
    property name=""tableToLogTo"" default=""CustomerLogs"" setter=""false"";

    public any function init(LoggerServiceDAO, scopeStorage) {
        variables.loggerServiceDAO = arguments.loggerServiceDAO;
        variables.scopeStorage = arguments.scopeStorage;
    }


    public any function after(targetBean, methodName, args, result) {
        variables.loggerServiceDAO.insertLog(method=arguments.methodName, user=variables.scopeStorage.get('session.user.id'));
    }
}
</code></pre>

<p>Here is the code I use to get the CustomerBean:</p>

<pre><code>bf = new framework.aop(
    folders=""/models,/system,/tests/Mocks"", config={transients=[""entity"", ""process"", ""transients"", ""report"", ""forms""],transientPattern=""Bean$""}
);
bf.intercept('CustomerBean', 'CustomerLoggerMock', 'doCreate');
customerBean = bf.getBean('CustomerBean', {customerDAO: customerDAOMock});
</code></pre>

<p>Ideally what I would like to do is use Testbox to mock the two objects and use the nice built in verification methods. Is this possible or am I stuck creating all of these mock files?</p>
",https://stackoverflow.com/questions/47271667/mocking-dependencies-inside-of-an-aop-object-using-testbox-and-aop-1,"['unit-testing', 'coldfusion', 'aop', 'lucee']",147,FALSE,1,0
Does this angular 4 unit test meet current convention?,"<p>I'm unit testing a basic <code>@Injectable</code> service in ng 4.  Tutorials use varying conventions (for example the use of <code>TestBed</code> vs <code>debugElement.injector</code>).  While these tests pass, my setup feels cobbled together and probably uses bad conventions.</p>

<p><strong>Here are my concerns:</strong></p>

<ol>
<li>The declaration of <code>providers</code> seems verbose, but <code>providers: [MockProgressServer]</code> led to a karma error.</li>
<li>Should the first test <code>expect(component).ToBeTruthy</code> always be included when testing a component?  This seems autogenerated by ng cli in other modules.</li>
<li>The line <code>fixture.debugElement.injector.get(ProgressService)</code> seems itnerchangible with <code>TestBed.get(ProgressService)</code>.  Which is preferrable?</li>
<li>Should tests like this always be declared as <code>async()</code> as a rule of thumb?</li>
</ol>

<hr>

<p>The class we're testing is <code>ProgressService</code> in <code>progress.service.ts</code>.  It is trivial and contains a single <code>currentState</code> field with <code>getters</code> and <code>setters</code>.</p>

<pre><code>import { Injectable } from '@angular/core';

@Injectable()
export class ProgressService {
    private currentState: string = '1';

    constructor() {
    }

    setCurrentState(state: string) {
        this.currentState = state;
    }

    getCurrentState(){
        return this.currentState
    }    
}
</code></pre>

<p>Because this class is trivial, the corresponding <code>Mock</code> overrides nothing.</p>

<pre><code>import {ProgressService} from ""../../../progress.service"";

export class MockProgressService extends ProgressService {
}
</code></pre>

<p>I've cobbled together the following <code>progress.spec.ts</code> class to unit test the getters and setters.</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { ProgressComponent } from './progress.component';
import {MockProgressService} from ""../shared/services/progress/progress.mock1"";
import {ProgressService} from ""../progress.service"";

describe('ProgressComponent', () =&gt; {
  let component: ProgressComponent;
  let fixture: ComponentFixture&lt;ProgressComponent&gt;;
  let mockService: ProgressService;

  beforeEach(async() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ ProgressComponent ],
      providers: [{provide: ProgressService, useValue: new MockProgressService()}]
    }).compileComponents()

    fixture = TestBed.createComponent(ProgressComponent);
    component = fixture.componentInstance;
    mockService = fixture.debugElement.injector.get(ProgressService)

    fixture.detectChanges();
  });

  fit('The component should be created', () =&gt; {
    expect(component).toBeTruthy();
  });

  fit('ProgressService default currentState is ""1""', () =&gt;{
    expect(mockService.getCurrentState()).toEqual('1')
  })

  fit('ProgressService new currentState is ""5""', () =&gt;{
    mockService.setCurrentState('5')
    expect(mockService.getCurrentState()).toEqual('5')
  })
});
</code></pre>

<p><code>npm test</code> shows that these pass</p>

<p><a href=""https://i.stack.imgur.com/ZSCba.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ZSCba.png"" alt=""enter image description here""></a></p>

<p>Thanks.  I want to get this locked down before moving on to non-trivial cases.</p>

<p>PS, is there any way to change the styling of the Karma browser report?  (EG make the font bigger?)</p>

<h2>Updated solution based on estus answers</h2>

<p>Split test modules.  <strong>First, test the service:</strong></p>

<pre><code>import {async, ComponentFixture, getTestBed, TestBed} from '@angular/core/testing';

import { ProgressComponent } from './progress.component';
import {ProgressService} from ""../progress.service"";

describe('ProgressComponent', () =&gt; {
  let injector: TestBed;
  let service: ProgressService;

  beforeEach(async() =&gt; {
    TestBed.configureTestingModule({
     providers: [ProgressService]
    }).compileComponents()

    injector = getTestBed()
    service= injector.get(ProgressService)    

  });    
  fit('ProgressService default currentState is ""1""', () =&gt;{
    expect(service.getCurrentState()).toEqual('1')
  })

  fit('ProgressService new currentState is ""5""', () =&gt;{
    service.setCurrentState('5')
    expect(service.getCurrentState()).toEqual('5')
  })
});
</code></pre>

<p><em>Two things:</em></p>

<ol>
<li><p>Is my use of provider/TestBed.get() correct?  Why couldn't I just instantiate an instance of ProgressService myself?  Does the TestBed ensure that a singleton is created?</p></li>
<li><p>Not sure where your suggestion of <code>fakeAsync</code> would fit in...</p></li>
</ol>

<p>Next, <strong>test the component</strong>:</p>

<pre><code>import {async, ComponentFixture, getTestBed, TestBed} from '@angular/core/testing'

import { ProgressComponent } from './progress.component'
import {MockProgressService} from ""../shared/services/progress/progress.mock1""
import {ProgressService} from ""../progress.service""

describe('ProgressComponent', () =&gt; {
  let injector: TestBed
  let mockService: ProgressService
  let fixture: ComponentFixture&lt;ProgressComponent&gt;
  let component: ProgressComponent

  beforeEach(async() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ ProgressComponent ],
      providers: [{provide: ProgressService, useClass: MockProgressService}]
    }).compileComponents()

    injector = getTestBed()
    fixture = TestBed.createComponent(ProgressComponent)
    component = fixture.componentInstance
    mockService = injector.get(ProgressService)

    fixture.detectChanges();
  });

   fit('The component should be created', () =&gt; {
     expect(component).toBeTruthy();
   });

   fit('The service should be an instance of MockService', () =&gt; {
     expect(mockService instanceof MockProgressService).toBeTruthy()
   })
});
</code></pre>
",https://stackoverflow.com/questions/46942013/does-this-angular-4-unit-test-meet-current-convention,"['angular', 'unit-testing', 'typescript']",92,TRUE,1,1
Integration tests sporadically timeout on Heroku hobby-dev,"<p>Since we do not get any helpful support from help.heroku.com we make the last try here.</p>

<p>We are developping a classic web app consisting of:</p>

<pre><code>    -----        -----        ----
    |WEB| &lt;----&gt; |API| &lt;----&gt; |DB|
    -----        -----        ----
</code></pre>

<p>We currently are working with the following Heroku Dynos/Datastores </p>

<ul>
<li>Heroku Postgres: Hobby Basic</li>
<li>Heroku API Dyno: Hobby</li>
<li>Heroku WEB Dyno: Hobby</li>
</ul>

<p>The tech stack is:</p>

<ul>
<li>runtime: nodejs (4.4.0)</li>
<li>db: postgres (9.6.1)</li>
<li>testframework: jasminejs (2.5.1)</li>
<li>query builder: knexjs (0.10.0)</li>
</ul>

<p>We recently moved to from self hosted docker environment to Heroku and configured the Herokus CI pipeline which works fine for unit testing - but not integration testing.
The tests sporadically fails with timeouts (in average every 3rd test of the same commit). This is not stable enough to build up CI/CD.</p>

<p>Here the error messages we get:</p>

<pre><code>**************************************************
*                    Failures                    *
**************************************************
1) integration test collections repository create() should return AUTHENTICATION_REQUIRED if user is anonymous
  - Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
  - Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
2) integration test collections repository create() should return AUTHORIZATION_REQUIRED if user is not space MEMBER
  - Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
  - Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
  - Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
3) integration test collections repository create() should return collection if user is space MEMBER
  - Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
  - Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
  - Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
</code></pre>

<p>For testing purposes we configured knex connection pooling to use one connection only:</p>

<pre><code>export default {
    client: 'pg',
    connection: DB_URL,
    pool: {
    max: 1,
    min: 1
    }
};
</code></pre>

<p>The typical integration test setup is:</p>

<pre><code>describe('integration test', () =&gt; {
    describe('collections repository create()', () =&gt; {
        //////////////////////////////////////////////////////////////////////
        //Before the test block is execute all fixtures are loaded into the DB
        //////////////////////////////////////////////////////////////////////
        beforeAll((callback) =&gt; {
            seed(path.join(__dirname, 'fixtures'))
            .then(callback)
            .catch((error) =&gt; {
                fail(error);
                callback();
            });
        });

        ////////////////////////////////////////////////////////////////////////
        //Truncate all data from the DB before the next test block gets executed
        ////////////////////////////////////////////////////////////////////////
        afterAll(resetDB);

        it('should return AUTHENTICATION_REQUIRED if user is anonymous', (callback) =&gt; {
            testUtils.testAsync({
                callback,
                catchTest: (error) =&gt; {
                    expect(error).toEqual(jasmine.any(repositoryErrors.AUTHENTICATION_REQUIRED));
                },
                runAsync: create({ props: { space: { id: 1 } } })
            });
        });

        it('should return AUTHORIZATION_REQUIRED if user is not space MEMBER', (callback) =&gt; {
            testUtils.testAsync({
                callback,
                catchTest: (error) =&gt; {
                    expect(error).toEqual(jasmine.any(repositoryErrors.AUTHORIZATION_REQUIRED));
                },
                runAsync: create({ props: { space: { id: 1 } }, userId: 1 })
            });
        });

        it('should return collection if user is space MEMBER', (callback) =&gt; {
            testUtils.testAsync({
                callback,
                runAsync: create({ props: { space: { id: 1 } }, userId: 2 }),
                thenTest: (outcome) =&gt; {
                    expect(outcome).toEqual({ id: '1' });
                }
            });
        });
    ...
</code></pre>

<p>seed:</p>

<pre><code>const tableOrder = [
    'users',
    'guidelines',
    'collections',
    'spaces',
    'details',
    'files',
    'guidelinesAuthors',
    'collectionsUsers',
    'spacesUsers',
    'guidelinesCollections',
    'spacesCollections',
    'guidelinesDetails',
    'guidelinesFiles',
    'comments',
    'commentsReplies',
    'notifications'
];

export default function seed(path) {
    return db.raw('BEGIN;')
    .then(() =&gt; {
        return tableOrder.reduce((promise, table) =&gt; {
        return promise
            .then(() =&gt; slurp({ path, table }))
            .then(() =&gt; {
                updateIdSequence(table)
                    .catch((error) =&gt; {
                        // eslint-disable-next-line no-console
                        console.log(
                            `Updating id sequence for table '${table}' failed! Error: `,
                            error.message
                            );
                    });
            });
        }, Promise.resolve()).then(() =&gt; db.raw('COMMIT;'));
    })
    .catch((error) =&gt; {
        // eslint-disable-next-line no-console
        console.log('SEED DATA FAILED', error);

        return db.raw('ROLLBACK;');
    });
}
...
</code></pre>

<p>resetDB:</p>

<pre><code>export default function resetDB(callback) {
    const sql = 'BEGIN; '
    + 'SELECT truncateAllData(); '
    + 'SELECT restartSequences(); '
    + 'COMMIT;';

    return db.raw(sql)
    .then(callback)
    .catch((error) =&gt; {
        // eslint-disable-next-line no-console
        console.log('TRUNCATE TABLES FAILED', error);

        return db.raw('ROLLBACK;');
    });
}
</code></pre>

<p>Until now, these test have been running on local machines (Linux/Mac) and Codeship without any problem.</p>

<p>After almost two weeks of trying to get this work we made zero progress on this issue. I can't see anything wrong with this configuration and I start to belive Heroku has a serious issue with the datastores...</p>

<p>Has anybody experienced similar issues on Heroku?
Any idea what we can try else to get this work?</p>
",https://stackoverflow.com/questions/45636916/integration-tests-sporadically-timeout-on-heroku-hobby-dev,"['node.js', 'postgresql', 'heroku', 'jasmine', 'timeout']",157,FALSE,1,0
Why my AngularJS async test in Jasmine 1.3.x is not working?,"<p>Hi I have a feature complete web-app written using AngularJS (1.5.11) and now I'm getting started with unit testing using karma (0.12.37), grunt-karma (0.8.3), karma-chrome-launcher (0.1.12), karma-phantomjs-launcher (1.0.4), <strong>phantomjs-prebuilt</strong> (2.1.14), jasmine-promise-matchers (2.3.0) and karma-jasmine (0.1.6), with a 1.3.x Jasmine version.</p>

<p>I'm not very confident in testing asynchronous stuff, so I started googling around and I always end up seeing the only mandatory thing to run AngularJS async tests is a <code>$rootScope/$scope.$apply/$digest</code> right after the async function has been called.</p>

<p>Eventually I found <a href=""https://stackoverflow.com/questions/33467485/how-to-test-that-an-angular-factory-function-using-a-promise-is-throwing-an-erro/33499275?noredirect=1#comment77031514_33499275"">someone suggesting me to use runs() and waitsFor()</a> and the test in this <a href=""http://plnkr.co/edit/veE92Qb7g5uQALDF8ux7?p=info"" rel=""nofollow noreferrer"">plunkr</a> in particular runs smoothly when using the chrome-launcher but fails when using phantomjs-launcher, throwing an error like the following:</p>

<pre><code>Expected { myError : { error : 'error_message' }, line : &lt;factory's line of code which throws the error&gt;, sourceURL : 'path/to/factory.js', stack :

     &lt;function throwing error&gt; B@path/to/factory.js:&lt;factory's line of code which throws the error&gt;
     &lt;""async"" function&gt; A@path/to/factory.js:&lt;factory's line of code which calls B()&gt;
     path/to/factory-spec.js:&lt;the following line of code: var promise = HandleService.A();&gt;
     invoke@path/to/angular/angular.js:4771:24
     WorkFn@path/to/angular-mocks/angular-mocks.js:3130:26
     execute@path/to/node_modules/karma-jasmine/lib/jasmine.js:1145:22
     next_@path/to/node_modules/karma-jasmine/lib/jasmine.js:2177:38
     start@path/to/node_modules/karma-jasmine/lib/jasmine.js:2130:13
     execute@path/to/node_modules/karma-jasmine/lib/jasmine.js:2458:19
     next_@path/to/node_modules/karma-jasmine/lib/jasmine.js:2177:38
     start@path/to/node_modules/karma-jasmine/lib/jasmine.js:2130:13
     execute@path/to/node_modules/karma-jasmine/lib/jasmine.js:2604:19
     next_@path/to/node_modules/karma-jasmine/lib/jasmine.js:2177:38
     start@path/to/node_modules/karma-jasmine/lib/jasmine.js:2130:13
     execute@path/to/node_modules/karma-jasmine/lib/jasmine.js:2604:19
     next_@path/to/node_modules/karma-jasmine/lib/jasmine.js:2177:38
     onComplete@path/to/node_modules/karma-jasmine/lib/jasmine.js:2173:23
     finish@path/to/node_modules/karma-jasmine/lib/jasmine.js:2561:15
     path/to/node_modules/karma-jasmine/lib/jasmine.js:2605:16

     next_@path/to/node_modules/karma-jasmine/lib/jasmine.js:2187:24
     onComplete@path/to/node_modules/karma-jasmine/lib/jasmine.js:2173:23
     finish@path/to/node_modules/karma-jasmine/lib/jasmine.js:2561:15
     path/to/node_modules/karma-jasmine/lib/jasmine.js:2605:16

     next_@path/to/node_modules/karma-jasmine/lib/jasmine.js:2187:24
     onComplete@path/to/node_modules/karma-jasmine/lib/jasmine.js:2173:23
     finish@path/to/node_modules/karma-jasmine/lib/jasmine.js:2432:15
     path/to/node_modules/karma-jasmine/lib/jasmine.js:2459:16

     next_@path/to/node_modules/karma-jasmine/lib/jasmine.js:2187:24
     path/to/node_modules/karma-jasmine/lib/jasmine.js:2167:23' }, pending : undefined, processScheduled : false } } to be rejected with { myError : { error : 'error_message' } }.
</code></pre>

<p>So I started to think Chrome results were false positive, and I needed to rewrite the async tests: hence I tried with something like this <a href=""http://plnkr.co/edit/bApcZnR9SYaaWtesEoOi?p=info"" rel=""nofollow noreferrer"">plunkr</a>, but now the tests fail both in PhantomJs and Chrome with the expected timeout message:</p>

<pre><code>timeout: timed out after 1500 msec waiting for A should catch an error
</code></pre>

<p><strong>N.B.:</strong> <strong>I can't update Jasmine to version 2.0 and use the <code>done</code> parameter mechanism now</strong> and if I got it right I should not even manually trigger a <code>$rootScope.$apply/$digest</code> when using <a href=""https://github.com/bvaughn/jasmine-promise-matchers#overview"" rel=""nofollow noreferrer"">jasmine-promise-matchers</a>.</p>

<h2>How can I write my async tests properly for this kind of async functions catching custom errors and async functions in general?</h2>
",https://stackoverflow.com/questions/45058499/why-my-angularjs-async-test-in-jasmine-1-3-x-is-not-working,"['javascript', 'angularjs', 'unit-testing', 'asynchronous', 'jasmine']",522,TRUE,1,1
How to choose Delphi ADO Cursor location and Cursor Type,"<p>we have migrated a Delphi Project(Banking Application) from BDE to ADO and we have kept all the default properties as is and while unit testing there are issues.</p>

<p>One issue is <strong>""Row cannot be located for updating. Some values may have been changed since it was last read""</strong></p>

<p>the Issue is coming while updating a table. Table employee is having Update trigger and it is updating same table(Employee) based on some checks.whether trigger updates the table or not system is throwing above error.</p>

<p>Most Suggested Solution : 
<code>ADODataSet1.Properties['Update Criteria'].value :=adCriteriaKey;</code> and it didnt work.</p>

<p>After googling we have come to know there are some properties like Cursor location and Cursor Type which are important while working with ADO.</p>

<p>we have just changed Cursor Location to clUseServer from clUseClient and it started working(magic) and we dont know why it is working. </p>

<p>now we are super confued what cursor location or Cursor type to use.</p>

<p><strong>About My Application:</strong></p>

<p>1) List view or DBGrid to show the records to user.</p>

<p>2) we are using data aware controls(more controls).</p>

<p>3) there are lots of inserts , updates and deletions</p>

<p>3) there are around 1000 users who uses this application.</p>

<p>4) Same user can work on same screen/Record.</p>

<p>after going through <a href=""https://msdn.microsoft.com/en-us/library/aa266531(v=vs.60).aspx"" rel=""nofollow noreferrer"">Client-Side Cursors Versus Server-Side Cursors</a> we are planning to for Server Side cursors.</p>
",https://stackoverflow.com/questions/43497781/how-to-choose-delphi-ado-cursor-location-and-cursor-type,"['sql-server', 'delphi', 'delphi-7', 'ado']",3618,TRUE,1,1
Can one use an Enum within a @Value,"<p>I'm trying to solve a problem.  We are storing our Properties in the database and when our application starts, we have multiple ""@Value"" throughout the code.  If someone forgets to have that Properties put into the database, it doesn't let the application start.  So I'm looking for a solution to do a check to see if all the Properties are existing that the application is expecting.  My current path is to use this from the applicationContext.xml - the ""AppPropertiesConfigurer"" extends PropertySourcesPlaceholderConfigurer and implements BeanPostProcessor</p>

<pre><code>&lt;!-- Configure CH Properties --&gt;
&lt;bean id=""applicationPropertyConfigurer"" class=""com.chw.base.spring.AppPropertiesConfigurer""
    depends-on=""propertiesSessionFactory""&gt;
    &lt;property name=""applicationCode"" value=""xyz"" /&gt;
    &lt;property name=""sessionFactory"" ref=""propertiesSessionFactory"" /&gt;
    &lt;property name=""locations""&gt;
        &lt;list&gt;
            &lt;value&gt;/WEB-INF/build.properties&lt;/value&gt;
        &lt;/list&gt;
    &lt;/property&gt;
&lt;/bean&gt;
</code></pre>

<p>What I've done is created this class that extends that class above. This is will do my checking to see if all the Properties are loaded, if not, an error message is logged.</p>

<pre><code>import java.io.IOException;
import java.util.HashMap;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.chg.base.util.CHGProperties;
import com.chw.base.spring.ChwPropertiesConfigurer;
import com.chw.dbobjects.manager.PropertiesId;


public class MyAppPropertiesConfigurer
        extends AppPropertiesConfigurer
{

    private static Log aLog = LogFactory.getLog(PxiPropertiesConfigurer.class);
    private final String aPropertyNotValid = ""Property not valid"";
    private final String aPropertyNotFound = ""Property not found"";
    private HashMap&lt;String, String&gt; aPropertiesMap = new HashMap();

    @Override
    protected void 
    loadProperties(Properties pProps)
    throws IOException
    {
        super.loadProperties(pProps);

        getProperties();

        int count = 1;
        for (PropertiesId properties : PropertiesId.values())
        {
            aLog.error(""Property "" + count + "":"" + properties.getPropertiesName());
            testProperty(properties.getPropertiesName());
        }
        try
        {
            Thread.sleep(60000);
        }
        catch (InterruptedException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public final void testProperty(String pKey)
    {
        Properties lPropertiesList = CHGProperties.getMappedProperties();
        Object lObject = lPropertiesList.getProperty(pKey);
        if (lObject == null)
        {
            aLog.error(aPropertyNotFound + "" "" + pKey);
        }
    }
}
</code></pre>

<p>Above there is a reference to ""PropertiesId"" - which is this Enum.</p>

<pre><code>public enum PropertiesId
{
    CLEAR_VTD_FLAG(""clear.vtd.flag""),
    MAIL_FROM(""app.mailfrom""),
    FAKE_PROPERTY(""fake.property"");

    private final String propertiesName;

    PropertiesId(String propertiesName) 
    { 
        this.propertiesName = propertiesName;
    }

    public String getPropertiesName()
    {
        return propertiesName;
    }
}
</code></pre>

<p>Now in another class I have many @Values that are used throughout the app.  We created a class to house all of them to help with Unit testing, but in hind sight, it is nice to just have them all in one place instead of scattered through the code.  So, I'd like to do this, but Eclipse complains about it.  Is there a simplier way to do this?  </p>

<pre><code>@Value(""${"" + PropertiesId.CLEAR_VTD_FLAG + ""}"")
private boolean aClearVtdFlag;

@Value(""${"" + PropertiesId.CLEAR_VTD_FLAG + ""}"")
private boolean aFake;
@Value(""${clear.vtd.flag:true}"")
private boolean aClearVtdFlag;
</code></pre>

<p>Perhaps there is a different way to verify that all the Properties exist for an app?</p>

<p>Thanks, Michael</p>

<p>PS: Running Spring 3.2</p>
",https://stackoverflow.com/questions/47781201/can-one-use-an-enum-within-a-value,"['java', 'spring', 'enums']",4321,FALSE,1,2
Testing unexposed functions in a Promise chain,"<p>I have UI component that calls a method <code>getUserInfo()</code> which returns a chain of promises. When I first built this I thought it was a good idea, and I wrote a bunch
of code without test. <code>getUserInfo()</code> takes a couple of input parameters and returns the following. It is the beginning of a long chain of promises that resolves to an array of strings.
Now I'm trying to test but I'm having quite a bit of trouble ...</p>
<h3>utilities.js</h3>
<pre><code>...
// function geocodeLocation(zipcode){...};
// function getPlace(coordinates){...};
// ... etc
...

const utilities = {
    getUserInfo: function (zipcode, gender) {
        return geocodeLocation(zipcode)
            .then(coordinates =&gt; getPlaces(coordinates))
            .then(placeData =&gt; getDistanceFromEachPlace(origin, placeData))
            .then(places =&gt; getMembersFromPlaces(places, gender))
            .then(members =&gt; sortMembersByAge(members))
            .then(sortedMembers =&gt; selectMembers(sortedMembers, gender))
    }
};

module.exports = utilities;
</code></pre>
<p><code>getUserInfo</code> is located within a <code>utilities</code> module and is the only function exposed. I'm a bit lost when it comes to testing this. <code>getUserInfo</code> is the start of a
long chain of functions. Most of the functions that are chained make external API calls, some of which are wrapped around promises. If the functions aren't making external API calls, they are munging
data and creating new data sets (in other words, functions that should be unit tested). Stubbing and mocking seems appropriate here, but I get confused as to what to stub out and what to mock.
Should I mock out each of the functions, and test end result of the promise?</p>
<p>Also, since <code>getUserInfo</code> is the only function exposed in the module, individual unit testing does not seem feasible here. How can i go about testing all the intermediary functions like getDistanceFromEachPlace when
they aren't exposed?</p>
<h3>testfile.js</h3>
<pre><code>import utilities from '../util/utilities'
import sinon from 'sinon'
import mocha from 'mocha'

describe('___api', () =&gt; {
  it('should return a promise', () =&gt; {
    const zipcode = '90210'
    const gender = 'male'
    // stub( other api functions here?? )
    expect(utilities.getUserInfo(zipcode, gender).to.be.a('promise')
  });
});
</code></pre>
<p>Can I even test this thing now?</p>
",https://stackoverflow.com/questions/47583086/testing-unexposed-functions-in-a-promise-chain,"['javascript', 'mocha.js', 'es6-promise', 'sinon']",158,FALSE,0,1
Circular dependencies on angular modules using typescript,"<p>I'm facing this issue where i have 2 angular 1.5 modules that depend on each other, which is fine by angularjs, but when i import them using typescript &amp; webpack, i get circular typescript-module dependencies and the modules are not loaded properly.
I dont have circular dependencies in the angular services between the modules, therefor there should be no problem depending the angular-modules on each other.</p>

<pre><code>//first.module.ts
import {SecondModule} from ""second.module.ts"";
let FirstModule = angular.module(""firstModule"",[SecondModule.name]);
export {FirstModule};

//second.module.ts
import {FirstModule} from ""first.module.ts"";
let SecondModule = angular.module(""secondModule"",[FirstModule.name]);
export {SecondModule};
</code></pre>

<p>In the example above, i get ""cannot get 'name' of undefined"" on the last line, since FirstModule is not exported yet.</p>

<p>One solution i saw online is just to not define the SecondModule as a dependency of FirstModule, but make them both dependencies of a parent module (my main app module), the problem is that i cant mock FirstModule using ngMock for unit testing - since it does not register SecondModule as a dependent sub-module. so i have to mock my whole main app which is big and messy.</p>

<p>Other solution i saw was to wrap the angular-modules with typescript classes, and put the angular module creation in the constructor of this class, so i can control when the module is created, but then i have to refactor my whole application to create objects of those wrapped modules, and i have no idea how will this affect writing unit tests using ngMock.</p>

<p>Are there any best practices for this situation?</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/45906867/circular-dependencies-on-angular-modules-using-typescript,"['angularjs', 'unit-testing', 'typescript', 'angular-mock', 'angular-module']",432,TRUE,0,1
"Is there a way to use Maven Scope &#39;provided&#39; when deploying to WAR, but &#39;compile&#39; when running in IDE?","<p>I am creating a Spring Boot application that will be running inside a Tomcat server. I am using the <code>@SpringBootApplication</code> tag on my main class, and in the pom.xml file I am using scope <code>compile</code> for the Tomcat dependency.</p>

<pre><code>    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-tomcat&lt;/artifactId&gt;
        &lt;scope&gt;compile&lt;/scope&gt;
    &lt;/dependency&gt;
</code></pre>

<p>This way, when running inside my IDE (IntelliJ), the application starts its own Tomcat server so I can easily test the application. When deploying to a WAR file I edit the pom.xml file and set the scope for tomcat to 'provided', since I load the WAR file into an existing Tomcat container on the server.</p>

<p>I create the WAR file by running <code>./mvnw clean package</code> from the commandline.</p>

<p>When setting the scope to 'provided' and running inside the IDE, I get the following error:</p>

<pre><code>...
2017-05-02 10:40:19.529  WARN 14508 --- [  restartedMain] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [be.test.test.Test]; nested exception is java.lang.IllegalStateException: Failed to introspect annotated methods on class org.springframework.boot.web.support.SpringBootServletInitializer$ErrorPageFilterConfiguration
2017-05-02 10:40:19.534 ERROR 14508 --- [  restartedMain] o.s.b.f.s.DefaultListableBeanFactory     : Destroy method on bean with name 'org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory' threw an exception

java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.context.annotation.AnnotationConfigApplicationContext@7e1b02ea: startup date [Tue May 02 10:40:19 CEST 2017]; root of context hierarchy
    at org.springframework.context.support.AbstractApplicationContext.getApplicationEventMulticaster(AbstractApplicationContext.java:404) [spring-context-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    ...
</code></pre>

<p>Is there some way to set this up in a way that I can run this in ""test mode"" in the IDE, but can create the WAR file without changing the pom.xml file? I have seen the scope ""test"" is also available, but from what I understand this is only used during Unit Testing? Or is that exactly what I am looking for?</p>

<p>Disclaimer:<br>
I am <em>very</em> new to all of this, so bear with me if I'm getting all kinds of basics wrong and kindly point me to the concepts and technologies I should look into ;)</p>

<p><strong>Pom.xml</strong></p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;project xmlns=""http://maven.apache.org/POM/4.0.0"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
    xsi:schemaLocation=""http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd""&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;

    &lt;groupId&gt;be.test.test&lt;/groupId&gt;
    &lt;artifactId&gt;test&lt;/artifactId&gt;
    &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
    &lt;packaging&gt;war&lt;/packaging&gt;

    &lt;name&gt;test&lt;/name&gt;
    &lt;description&gt;test&lt;/description&gt;

    &lt;parent&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
        &lt;version&gt;1.5.1.RELEASE&lt;/version&gt;
        &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
    &lt;/parent&gt;

    &lt;properties&gt;
        &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;
        &lt;project.reporting.outputEncoding&gt;UTF-8&lt;/project.reporting.outputEncoding&gt;
        &lt;java.version&gt;1.8&lt;/java.version&gt;
    &lt;/properties&gt;

    &lt;dependencies&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-jdbc&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.session&lt;/groupId&gt;
            &lt;artifactId&gt;spring-session&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-thymeleaf&lt;/artifactId&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;com.h2database&lt;/groupId&gt;
            &lt;artifactId&gt;h2&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;
            &lt;artifactId&gt;lombok&lt;/artifactId&gt;
            &lt;optional&gt;true&lt;/optional&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-devtools&lt;/artifactId&gt;
        &lt;/dependency&gt;

        &lt;!-- Added to be able to load into Tomcat as a Servlet: https://stormpath.com/blog/tutorial-spring-boot-war-files --&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-tomcat&lt;/artifactId&gt;

            &lt;!-- Use 'provided' when deploying to .WAR for Tomcat --&gt;
                &lt;!-- This is much like compile, but indicates you expect the JDK or a container to provide the dependency at runtime. --&gt;
            &lt;!-- Use 'compile'  when working in IntelliJ for development --&gt;
                &lt;!-- This is the default scope, used if none is specified. Compile dependencies are available in all classpaths of a project. Furthermore, those dependencies are propagated to dependent projects. --&gt;
            &lt;scope&gt;compile&lt;/scope&gt;

        &lt;/dependency&gt;

    &lt;/dependencies&gt;

&lt;!-- Commenting this out to deploy to the existing Tomcat server: https://spring.io/blog/2014/03/07/deploying-spring-boot-applications
    &lt;build&gt;
        &lt;plugins&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
                &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
            &lt;/plugin&gt;
        &lt;/plugins&gt;
    &lt;/build&gt;--&gt;


&lt;/project&gt;
</code></pre>
",https://stackoverflow.com/questions/43683281/is-there-a-way-to-use-maven-scope-provided-when-deploying-to-war-but-compile,"['maven', 'intellij-idea', 'spring-boot', 'dependency-management']",903,FALSE,0,0
How to do a right unit test for the Presenter in MVP,"<p>I'm using the MVP pattern. And faced with a problem of covering the Presenter with unit testing.</p>

<p>Behavior:
View(Form) has two buttons on it - Ok and Apply.</p>

<p>If Ok button is pressed then the Data must be validated and in a case of success the Data must be saved and View must be closed.</p>

<p>If Apply button is pressed then the Data must be validated and in a case of success the Data must be saved then the Data must be reloaded and the View must be refreshed.</p>

<p>Presenter has two methods which are called by the View in case of Ok and Apply buttons are pressed. They are OkButtonPressed and ApllyButtonPressed respectively.</p>

<p>This is a pseudo code of the Presenter</p>

<pre><code>private
  // view intreface
  View : IView; 
  function TrySaveChanges: boolean {
    //Validate data by calling Model's methods
    //Save data by calling Model's methods
    // In case of any error call View to show an error message
  }      
  function RefreshData: boolean {
    //Load data by calling Model's methods
  };
  function RefershView: boolean {
    //Call View's methods to refresh the data on it
  };

public
  procedure OkButtonPressed {
    if TrySaveChanges {
      View.Close;
    }
  }
  procedure ApplyButtonPressed {
    If TrySaveChanges {
      RefreshData;
      RefershView;
    }  
  }
</code></pre>

<p>How cover such code with unit test?
Roy Osherove says to test public methods as public methods call private ones. So via tests for public the behavior of private can be tested. 
But in the example above few Presenter's public methods call the same private method.
What should exact be tested for the OkButtonPressed and ApplyButtonPressed methods?
Regarding to Roy behavior of TrySaveChanges must be tested in tests for OkButtonPressed and ApplyButtonPressed methods. But will this produce tests ""duplicates""?
If I do not test the TrySaveChanges methods behavior in tests for OkButtonPressed and ApplyButtonPressed methods then where I should test it?
Maybe the problem is in the Presenter itself?</p>
",https://stackoverflow.com/questions/47569700/how-to-do-a-right-unit-test-for-the-presenter-in-mvp,"['unit-testing', 'mvp', 'presenter']",107,FALSE,0,1
How to make Moq understand that the type constraint is acceptable for the Verified call?,"<blockquote>
  <p><strong>Summary</strong></p>
</blockquote>

<p>I'm currently writing some integration code so that I can interact with an accounting system.</p>

<p>The accounting system in question is Acceo Acomba, using its SDK which turns to be distributed COM objects.</p>

<p>I have written a generic class that serves the purpose of a generic repository for any given Acomba entity.</p>

<pre><code>public abstract class AcombaRepository&lt;TEntity, TNativeRepository&gt;
    where TEntity : class
    where TNativeRepository : IBaseDataKey {
    public AcombaRepository( TNativeRepository nativeRepository, IMapper entityMapper ) {
        // Guard clauses...
        NativeRepository = nativeRepository;
        this.entityMapper = entityMapper;
    }

    protected readonly TNativeRepository NativeRepository;

    public TEntity Create( TEntity toCreate ) {
        NativeRepository.ReserveCardNumber(); // Insert
        entityMapper.Map( toCreate, NativeRepository ); // Assigning props 
        NativeRepository.AddCard(); // Save or commit to Acomba
    }
}
</code></pre>

<p><strong>IBaseDataKey</strong></p>

<p>This interface is the base entity for any given accessible entity within the system. In order to make sure I have access to its basics, I put this type constraint on my generic repository.</p>

<p><strong>AcombaProductsRepository</strong></p>

<p>This is the code under test which actually use the base method as-is.</p>

<pre><code>public class AcombaProductsRepository : AcombaRepository&lt;MyProduct, IProduct022&gt; {
    public AcombaPRoductsRepository( IProduct022 nativeRepository, IMapper productMapper ) 
        : base( nativeRepository, productMapper ) { 
    }
}
</code></pre>

<blockquote>
  <p><strong>Unit Testing</strong></p>
</blockquote>

<p>In order to make sure that my code uses the Acomba SDK adequately to create a new entity within the Acomba underlying data store, I verify that certain steps are strictly respected.</p>

<pre><code>public class AcombaProductsRepositoryTests {
    private readonly Mock&lt;IProduct022&gt; nativeRepositoryMock;
    private readonly AcombaProductsRepsoitory sut;

    public AcombaProductsRepositoryTests() {
        nativeRepositoryMock = new Mock&lt;IProduct022&gt;();
        sut = new AcombaProductsRepository( nativeRepositoryMock.Object );
    }

    [Fact]
    public void Create_Should_Reserve_A_Card_Number() {
        var toCreate = new MyProduct();
        nativeRepositoryMock.Setup( r =&gt; r.ReserveCardNumber() ).Verifiable();

        sut.Create( toCreate );

        nativeRepositoryMock.Verify( r =&gt; r.ReserveCardNumber() );
    }
}
</code></pre>

<p>Here, although the interface <code>IProduct022</code> derives from <code>IBaseDataKey</code>, Moq states that the expected invocation </p>

<ul>
<li><strong><code>IProduct022.ReserveCardNumber</code></strong></li>
</ul>

<p>was never performed. Besides, it also states that the performed invocation was </p>

<ul>
<li><strong><code>IBaseDataKey.ReserveCardNumber</code></strong></li>
</ul>

<p>For the essence of the unit test itself, it doesn't actually matter whether the performed invocation was either, as long as the <code>ReserveCardNumber</code> is called upon.</p>

<blockquote>
  <p><strong>How to make this test pass?</strong></p>
</blockquote>

<hr>

<blockquote>
  <p><strong>Further Details (edit)</strong></p>
</blockquote>

<p>Here's the error message from the test result.
<a href=""https://i.stack.imgur.com/uUirJ.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/uUirJ.jpg"" alt=""Test Result Error Message""></a></p>

<p>As I take it, Moq performs the invocation of the base <code>IBaseDataKey</code> class instead of the <code>IProduct022</code> derived one because of the type constraint, I suspect.</p>
",https://stackoverflow.com/questions/44549027/how-to-make-moq-understand-that-the-type-constraint-is-acceptable-for-the-verifi,"['c#', 'unit-testing', 'generics', 'moq']",185,FALSE,0,1
NUnit Not Utilizing Paramaters and Settings in .runsettings File,"<p>I'm trying to switch over an existing Selenium solution to use NUnit due to it's support of parallelization of tests within the same class. The problem I'm having is that it doesn't seem to be using the selected <code>.runsettings</code> file, despite the fact that it's <a href=""https://github.com/nunit/nunit3-vs-adapter/issues/145"" rel=""noreferrer"">supported by NUnit</a>. By this, I mean that <code>TestContext.Parameters.Count</code> is always 0, and it doesn't store results in the path specified in the <code>&lt;ResultDirectory&gt;</code> node of my .runsettings file.</p>

<p>I've looked over the documentation and the reference to <a href=""https://github.com/nunit/nunit3-vs-adapter/blob/master/src/NUnitTestAdapter/AdapterSettings.cs#L143"" rel=""noreferrer"">AdapterSettings</a> (which has logic for parsing the .runsettings file) and I can't f figure out why my <code>TestContext.Paramaters</code> are never populated in my test when I use a <code>.runsettings</code> file.</p>

<p>I created a bare-bones test solution just as a sanity check and POC and it's still not populating.</p>

<p>I have <br/>
-<code>NUnit 3.7.1</code><br/>
-<code>NUnit3TestAdapter 3.7.0</code><br/>
-<code>VisualStudio Professional 2017</code><br/></p>

<p>My .runsettings file is:</p>

<pre class=""lang-xml prettyprint-override""><code>&lt;?xml version=""1.0"" encoding=""utf-8""?&gt;
&lt;RunSettings&gt;
&lt;!-- Parameters used by tests at runtime --&gt;
  &lt;TestRunParameters&gt;
    &lt;Parameter name =""testParameter1"" value=""value1"" /&gt;
    &lt;Parameter name =""testParameter2"" value=""value2"" /&gt;
  &lt;/TestRunParameters&gt;
&lt;/RunSettings&gt;
</code></pre>

<p>All I'm trying to do in the test:</p>

<pre class=""lang-c# prettyprint-override""><code>using System;
using NUnit.Framework;

namespace ClassLibrary1
{
    [TestFixture]
    public class UnitTestClass1
    {
        [Test]
        [Parallelizable(ParallelScope.All)]
        public void Class1TestMethod1()
        {
            // Below always returns 0
            Console.WriteLine(TestContext.Parameters.Count);

            // Below returns null
            Console.WriteLine(TestContext.Parameters[""testParameter1""]);
        }
    }
}
</code></pre>

<p>I could really use some other suggestions on how to troubleshoot. We use .runsettings files extensively for our test suite with the built-in Visual Studio Unit Testing tools (and with vstest.console.exe), so I'm pretty confident I'm using it correctly.</p>

<p><strong>Update:</strong><br/>
I replaced all references to Visual Studios test attributes in my <em>actual</em> test solution to use NUnits attributes. Now I'm getting the parameters! However, that leaves me still baffled as to why it doesn't work in my other bare-bones solution (with files shown above). </p>

<p>I really only care about my real solution obviously, but I still want to understand why it's not working in my dummy solution. </p>

<p>Also - I still am not sure where to find the <code>TestResultDirectory</code> path in NUnit.</p>
",https://stackoverflow.com/questions/45105409/nunit-not-utilizing-paramaters-and-settings-in-runsettings-file,"['visual-studio', 'nunit', 'nunit-3.0']",2012,FALSE,9,0
"Typescript, import, &quot;new&quot;, constructor and interfaces?","<p>The problem is not about the ""new"" keyword in the <a href=""https://stackoverflow.com/questions/11878924/is-new-still-not-recommended-in-javascript"">""problematic aspect""</a>, but more in the practical approach.</p>

<p>I'm fighting a bit with my C# and JavaScript mindsets when defining classes (ES2015). In C# I use dependency injection to inject the dependencies in the class' constructor. In JavaScript, due to its prototypical nature, I learned there's no need for you to inject a dependency into the constructor; you can safely use <code>import</code>, because you can later mock the method later for Unit Testing. </p>

<p>Therefore many modules ""just work"" out of the box, without the need to instantiate them. (Node modules are examples)</p>

<p>I've been using TypeScript in my project. As you know, you can use Interfaces with it. What I’ve been doing as of now, is setting the interface as a property and then setting the class in question to it. </p>

<p>To better illustrate what I'm saying, imagine I have class A:</p>

<pre><code>class A implements Letter {
    hello(){
        console.log(""Hello World"");
    }
}
</code></pre>

<p>And its interface ""Letter"":</p>

<pre><code>interface Letter {
    hello(): void
}
</code></pre>

<p>Then I have a class ""Book"" which uses the approach I'm saying.</p>

<pre><code>export class Book{
    letter : Letter
    constructor(){
        this.letter = A; 
    }
    Read(){
        console.log(""We're about to read this chapter!"");
        this.letter.hello();
    }
}
</code></pre>

<p>And it can be used like this:</p>

<pre><code>import {Book} from './book' 
let book = new Book();
    book.Read();
</code></pre>

<p>On the other hand, I have ""BookVersionJs"" who doesn't use any interface and implements it directly:</p>

<pre><code>import {A} from './a.ts';

export class BookVersionJs{
    Read(){
        console.log(""We're about to read this chapter!"");
        A.Hello(); 
    }
}
</code></pre>

<p>Then we can use it like this:</p>

<pre><code>  import {BookVersionJs} from './BookVersionJs'    
    BookVersionJs.Read(); 
</code></pre>

<p>But I loose the ""theoretical"" loose coupling that the interfaces give me. Theoretical because JavaScript could overwrite them with a prototype. </p>

<p>There's a difference in practicality. Which should I aim for in TypeScript/JavaScript? Or is it a matter of opinion? </p>
",https://stackoverflow.com/questions/44687125/typescript-import-new-constructor-and-interfaces,"['javascript', 'typescript', 'import', 'constructor']",3417,TRUE,2,1
Can I mock SqlConnection.BeginTransaction c#?,"<p>I have to work with some legacy code that I cannot change. I have to write classes of that implement an interface called ""ITask"" that has a method called ""RunTask"" that accepts a concrete type called Schedule e.g;</p>

<pre><code> public void RunTask(Schedule thisSchedule)
 {
     //I have to do stuff with thisSchedule, no I can't fix that name...
 }
</code></pre>

<p>Although the legacy code does not use unit testing I would dearly like to use it for my work but the problem is ""thisSchedule"". I have made a fake version of Schedule that derives from it and am attempting to take control over how all the methods within it function (it is probably a fool's errand). So far I have been successful by exploiting the alarming number of virtual methods or by using reflection but I have hit my first show-stopper</p>

<p>I cannot connect to the real database and I have a method that is often called;</p>

<pre><code>public void BeginTransaction()
{
    MyTransaction = MyConnection.BeginTransaction(IsolationLevel.RepeatableRead);
}

internal SqlConnection MyConnection = new System.Data.SqlClient.SqlConnection();
</code></pre>

<p>This throws an exception because the connection is closed, Ideally I would like to be able to set a flag stating that the method was called and then just swallow the exception but I would be happy to simply ignore the exception. </p>

<p>Anything, no matter how nasty that will allow me to get past this method call would be an acceptable answer. It's that or defeat.</p>

<p>I am not allowed to use paid-for services like typeMock or shims in visual studio enterprise.</p>

<p>EDIT</p>

<pre><code>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Data;
using System.Data.SqlClient;

namespace PredictionServicesTests
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void BeginTransaction_WhenCalled_SetsTransactionStartedToTrue()
        {
            Schedule schedule = new FakeSchedule();

            schedule.BeginTransaction(); //It would be enough to simply get past this line to the Assert

            Assert.IsTrue(((FakeSchedule)schedule).TransactionStarted); //This would be nice, but isn't vital
        }

        class Schedule
        {
            private SqlTransaction MyTransaction;
            internal SqlConnection MyConnection = new System.Data.SqlClient.SqlConnection();
            public void BeginTransaction()
            {
                MyTransaction = MyConnection.BeginTransaction(IsolationLevel.RepeatableRead);
            }
        }

        class FakeSchedule : Schedule
        {
            public bool TransactionStarted { get; set; }
        }
    }
}
</code></pre>

<p>Please remember I cannot change the Schedule class, if only things could be that simple!</p>

<p>The ITask interface;</p>

<pre><code>    interface ITask
    {
        void RunTask(Schedule thisSchedule);
    }
</code></pre>
",https://stackoverflow.com/questions/43350993/can-i-mock-sqlconnection-begintransaction-c,"['c#', 'unit-testing']",2427,TRUE,2,3
cudaMemcpy error when copying from device to host after __device__ class member function alters value of device variable,"<p>I am confused as to the behavior of the CUDA code I have written. I am in the midst of writing tests for my <code>__device__</code> functions in a class called <code>DimmedGridGPU</code>. This class is templated on an <code>int DIM</code> and the function I have trouble with is meant to return the value of the grid at the point nearest the input value, <code>x</code>. I have this kernel namespace for unit testing purposes, to call each <code>__device__</code> function in isolation.</p>
<p>The desired behavior of this code would be to return the value <code>3.0</code> from the <code>do_get_value(x, grid_)</code> call, and set <code>d_target[0]</code> to this value, then transfer it back to the host side for unit test assertions. The whole of the kernel seems to function properly, but when I do the final transfer back to the host side, I receive a <code>cudaErrorInvalidValue</code> error, and I do not understand why.</p>
<p>Here is a minimal example of the code, preserving the structure of the class and its features:</p>
<pre><code>#include &lt;cuda_runtime.h&gt;
#include &lt;fstream&gt;

#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true)
{
   if (code != cudaSuccess) 
   {
     fprintf(stderr,&quot;GPUassert: \&quot;%s\&quot;: %s %s %d\n&quot;, cudaGetErrorName(code), cudaGetErrorString(code), file, line);
      if (abort) exit(code);
   }
}


template &lt;int DIM&gt;
class DimmedGridGPU{

public:
  size_t grid_size_;//total size of grid
  int b_derivatives_;//if derivatives are going to be used
  int b_interpolate_;//if interpolation should be used on the grid
  double* grid_;//the grid values
  double* grid_deriv_;//derivatives    
  double dx_[DIM];//grid spacing
  double min_[DIM];//grid minimum
  double max_[DIM];//maximum
  int grid_number_[DIM];//number of points on grid
  int b_periodic_[DIM];//if a dimension is periodic
  int* d_b_interpolate_;
  int* d_b_derivatives_;


  DimmedGridGPU(const double* min, 
        const double* max, 
        const double* bin_spacing, 
        const int* b_periodic, 
        int b_derivatives, 
        int b_interpolate) :   b_derivatives_(b_derivatives), b_interpolate_(b_interpolate), grid_(NULL), grid_deriv_(NULL){
    
    size_t i;

    for(i = 0; i &lt; DIM; i++) {
      min_[i] = min[i];
      max_[i] = max[i];
      b_periodic_[i] = b_periodic[i];

      grid_number_[i] = (int) ceil((max_[i] - min_[i]) / bin_spacing[i]);
      dx_[i] = (max_[i] - min_[i]) / grid_number_[i];
      //add one to grid points if 
      grid_number_[i] = b_periodic_[i] ? grid_number_[i] : grid_number_[i] + 1;
      //increment dx to compensate
      if(!b_periodic_[i])
    max_[i] += dx_[i];
    }

    grid_size_ = 1;
    for(i = 0; i &lt; DIM; i++)
      grid_size_ *= grid_number_[i];
    gpuErrchk(cudaMallocManaged(&amp;grid_, grid_size_ * sizeof(double)));
    if(b_derivatives_) {
      gpuErrchk(cudaMallocManaged(&amp;grid_deriv_, DIM * grid_size_ * sizeof(double)));
      if(!grid_deriv_) {
    printf(&quot;Out of memory!! gpugrid.cuh:initialize&quot;);   
      }
    }
    
    gpuErrchk(cudaMalloc((void**)&amp;d_b_interpolate_, sizeof(int)));
    gpuErrchk(cudaMemcpy(d_b_interpolate_, &amp;b_interpolate, sizeof(int), cudaMemcpyHostToDevice));
    gpuErrchk(cudaMalloc((void**)&amp;d_b_derivatives_, sizeof(int)));
    gpuErrchk(cudaMemcpy(d_b_derivatives_, &amp;b_derivatives, sizeof(int), cudaMemcpyHostToDevice));
  }

  ~DimmedGridGPU(){
    gpuErrchk(cudaDeviceSynchronize());
    if(grid_ != NULL){
      gpuErrchk(cudaFree(grid_));
      grid_ = NULL;//need to do this so DimmedGrid's destructor functions properly
    }
    
    if(grid_deriv_ != NULL){
      gpuErrchk(cudaFree(grid_deriv_));
      grid_deriv_ = NULL;
    }
      
    gpuErrchk(cudaDeviceReset());
  }
//gets the value of the grid closest to x
  __host__ __device__ double do_get_value( double* x, double* grid_) {

    size_t index[DIM];
    get_index(x, index);
    printf(&quot;do_get_value was called on the GPU!, and index[0] is now %d\n&quot;, index[0]);
    printf(&quot;but multi2one(index) gives us %d\n&quot;, multi2one(index));
    double value = grid_[multi2one(index)];
    printf(&quot;and value to be returned is %f\n&quot;, value);
    return value;
  }
//gets grid's 1D index from an array of coordinates
   __host__ __device__ void get_index(const double* x, size_t result[DIM]) const {
    size_t i;
    double xi;
    printf(&quot;get_index was called on the GPU in %i dimension(s)\n&quot;, DIM);
    for(i = 0; i &lt; DIM; i++) {
      xi = x[i];
      printf(&quot;xi is now %f, min_[i] is %f and dx_[i] is %f\n&quot;,xi, min_[i], dx_[i]);
      if(b_periodic_[i]){
    xi -= (max_[i] - min_[i]) * gpu_int_floor((xi - min_[i]) / (max_[i] - min_[i]));
      }
      result[i] = (size_t) floor((xi - min_[i]) / dx_[i]);
    }
  }
//takes a multidimensional index to a 1D index
  __host__ __device__ size_t multi2one(const size_t index[DIM]) const {
    size_t result = index[DIM-1];

    size_t i;    
    for(i = DIM - 1; i &gt; 0; i--) {
      result = result * grid_number_[i-1] + index[i-1];
    }
    
    return result;
    
  }

};

__host__ __device__ int gpu_int_floor(double number) {
  return (int) number &lt; 0.0 ? -ceil(fabs(number)) : floor(number);
}


namespace kernels{
  template &lt;int DIM&gt;
  __global__ void get_value_kernel(double* x, double* target_arr, double* grid_, DimmedGridGPU&lt;DIM&gt;  g){
    target_arr[0] = g.do_get_value(x, grid_);
    printf(&quot;get_value_kernel has set target[0] to be %f\n&quot;, target_arr[0]);//check if the value is set correctly
    return;
  }
}


int main(){
  using namespace kernels;
  double min[] = {0};
  double max[] = {10};
  double bin_spacing[] = {1};
  int periodic[] = {0};
  DimmedGridGPU&lt;1&gt; g (min, max, bin_spacing, periodic, 0, 0);
  for(int i = 0; i &lt; 11; i++){
    g.grid_[i] = i;
    printf(&quot;g.grid_[%d] is now %f\n&quot;, i, g.grid_[i]);
  }
  gpuErrchk(cudaDeviceSynchronize());
  double x[] = {3.5};
  
  double* d_x;
  gpuErrchk(cudaMalloc(&amp;d_x, sizeof(double)));
  gpuErrchk(cudaMemcpy(d_x, x, sizeof(double), cudaMemcpyHostToDevice));
  double target[] = {5.0};
  double* d_target;
  gpuErrchk(cudaMalloc((void**)&amp;d_target, sizeof(double)));
  gpuErrchk(cudaMemcpy(d_target, target, sizeof(double), cudaMemcpyHostToDevice));
  gpuErrchk(cudaDeviceSynchronize());
  get_value_kernel&lt;1&gt;&lt;&lt;&lt;1,1&gt;&gt;&gt;(d_x, d_target, g.grid_, g);
  gpuErrchk(cudaDeviceSynchronize());
  gpuErrchk(cudaMemcpy(target, d_target, sizeof(double), cudaMemcpyDeviceToHost));
  printf(&quot;and after GPU stuff, target[0] is now %f\n&quot;, target[0]);
  return(0);
}
</code></pre>
<p>So, why does this line (the last <code>cudaMemcpy</code>) throw an error &quot;<code>CudaErrorInvalidValue</code>&quot;, when the print statements I have included clearly demonstrate that the correct values are being used on the device, and the value returned by the <code>do_get_value(x, grid_)</code> call is correct?</p>
<p>I have already tried using <code>cudaMemcpyFromSymbol</code>, thinking that perhaps the assignment was creating a symbol instead of passing and changing a value somehow, but that is not the case, as <code>d_target</code> is not a valid symbol.</p>
<p>Here is sample output from my code:</p>
<blockquote>
<p><code>g.grid_[0] is now 0.000000</code></p>
<p><code>g.grid_[1] is now 1.000000</code></p>
<p><code>g.grid_[2] is now 2.000000</code></p>
<p><code>g.grid_[3] is now 3.000000</code></p>
<p><code>g.grid_[4] is now 4.000000</code></p>
<p><code>g.grid_[5] is now 5.000000</code></p>
<p><code>g.grid_[6] is now 6.000000</code></p>
<p><code>g.grid_[7] is now 7.000000</code></p>
<p><code>g.grid_[8] is now 8.000000</code></p>
<p><code>g.grid_[9] is now 9.000000</code></p>
<p><code>g.grid_[10] is now 10.000000</code></p>
<p><code>get_index was called on the GPU in 1 dimension(s)</code></p>
<p><code>xi is now 3.500000, min_[i] is 0.000000 and dx_[i] is 1.000000</code></p>
<p><code>do_get_value was called on the GPU!, and index[0] is now 3</code></p>
<p><code>but multi2one(index) gives us 3</code></p>
<p><code>and value to be returned is 3.000000</code></p>
<p><code>get_value_kernel has set target[0] to be 3.000000</code></p>
<p><code>GPUassert: &quot;cudaErrorInvalidValue&quot;: invalid argument gpugrid.cu 166</code></p>
</blockquote>
",https://stackoverflow.com/questions/42844997/cudamemcpy-error-when-copying-from-device-to-host-after-device-class-member,"['c++', 'class', 'templates', 'cuda', 'gpu']",1363,TRUE,1,1
Karma + PhantomJS + Jasmine + Kendo UI component not rendering during test,"<p>Relatively lengthy question here, so bear with me please.</p>

<p>I have been trying to add unit testing to our client-side code for awhile now, and finally got the go ahead to take the time to do it.  We use AMD (requirejs) as of now, but that is also something I am exploring switching out of.  So the past few days I have been working on getting some of the testing infrastructure in place for our current setup, and am using phantomJS, Karma, and Jasmine to test from the terminal.  I have run into a problem with the rendering of Kendo components, so before I dive any deeper, I wanted to ask here to see if anybody know if:</p>

<ol>
<li>What is the problem caused by.</li>
<li>How to fix it in our setup files.</li>
</ol>

<p>Some background on:
All our library scripts are loaded locally with requirejs. jQuery and kendoui are loaded statically via script tags (something to do with globalization not working correctly when doing it via requirejs).</p>

<p>When I try to test a Marionette View that wraps a Kendo component, I get ""$el.kendoGrid"" is not a function.  The ""kendo"" global is however attached to window.</p>

<p>karma.conf.js:</p>

<pre><code>// Karma configuration
// Generated on Wed Dec 28 2016 13:38:24 GMT-0600 (Central Standard Time)

module.exports = function (config) {
    ""use strict"";
    config.set({
    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',
    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],
    // list of files / patterns to load in the browser
    files: [
        // Loads jQuery and kendoui statically via a script tag so the globals are available as expected by our
        // source JavaScript files.
        'web-libs-common/src/main/resources/META-INF/resources/static/js/lib/jquery/jquery.js',
        'web-libs-common/src/main/resources/META-INF/resources/static/js/lib/kendoui/kendo.all.js',

        // Load requirejs and its karma adapter after making the above scripts available.
        'node_modules/requirejs/require.js',
        'node_modules/karma-requirejs/lib/adapter.js',

        //The following patterns make the files available to be loaded by requireJS.
        {pattern: 'healthems-web/test/js/**/*.js', included: false}, //Make the test files available, but do not load.
        //Make the source files available, but do not load
        {pattern: 'healthems-web/src/main/resources/META-INF/resources/static/js/**/*.js', included: false},
        //Make the library files available but do not load.
        {
            pattern: 'web-libs-common/src/main/resources/META-INF/resources/static/js/lib/**/*.js',
            included: false
        },
        //Make the html templates available but do not load.
        {pattern: 'healthems-web/src/main/resources/META-INF/resources/static/html/**/*.html', included: false},
        //Make the test_utils directory available, but do not load.
        {pattern: 'test_utils/*.js', included: false},

        {pattern: 'node_modules/squirejs/src/Squire.js', included: false},


        'test-main.js'
    ],


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


    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {},


    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['spec'],


    // web server port
    port: 9876,


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


    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO ||
    // config.LOG_DEBUG
    logLevel: config.LOG_ERROR,


    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,


    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['PhantomJS'],

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

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
});
</code></pre>

<p>};</p>

<p>test-main.js:</p>

<pre><code>""use strict"";

var allTestFiles = [];
var TEST_REGEXP = /(spec|test)\.js$/i;

// Get a list of all the test files to include
Object.keys(window.__karma__.files).forEach(function (file) {
    if (TEST_REGEXP.test(file)) {
        // Normalize paths to RequireJS module names.
        // If you require sub-dependencies of test files to be loaded as-is (requiring file extension)
        // then do not normalize the paths
        var normalizedTestModule = file.replace(/^\/base\/|\.js$/g, '');
        allTestFiles.push(normalizedTestModule);
    }
});

var baseLibPath = ""web-libs-common/src/main/resources/META-INF/resources/static/js/"";
var baseAppPath = ""healthems-web/src/main/resources/META-INF/resources/static/js/"";
var baseTemplatePath = ""healthems-web/src/main/resources/META-INF/resources/static/"";

require.config({
    // Karma serves files under /base, which is the basePath from your config file
    baseUrl: '/base',
    map: {
        '*': {
            underscore: 'lodash'
        }
    },
    paths: {
        'app': baseAppPath + 'app',
        'backbone': baseLibPath + 'lib/backbonejs/backbone',
        'backbone.marionette': baseLibPath + 'lib/backbonejs/backbone.marionette',
        'backbone.paginator': baseLibPath + 'lib/backbonejs/backbone.paginator',
        'backbone.validation': baseLibPath + 'lib/backbonejs/backbone.validation',
        'format': baseAppPath + 'format',
        'jquery.ui': baseLibPath + 'lib/jquery/jquery.ui',
        'jquery.waypoints': baseLibPath + 'lib/jquery/jquery.waypoints',
        'jquery.waypoints.sticky': baseLibPath + 'lib/jquery/jquery.waypoints.sticky',
        'kendoui': baseLibPath + 'lib/kendoui/kendo.all',
        'json3': baseLibPath + 'lib/json3',
        'jstz': baseLibPath + 'lib/jstz',
        'jszip': baseLibPath + 'lib/kendoui/jszip.min',
        'jquery': baseLibPath + 'lib/jquery/jquery',
        'lodash': baseLibPath + 'lib/lodash',
        'mocks': 'test_utils/defaultMocks',
        'moment': baseLibPath + 'lib/momentjs/moment-with-locales',
        'moment.timezone': baseLibPath + 'lib/momentjs/moment-timezone-with-data',
        'rsvp': baseLibPath + 'lib/rsvp',
        'sockjs': baseLibPath + 'lib/sockjs',
        'spin': baseLibPath + 'lib/spin',
        'stomp': baseLibPath + 'lib/stomp',
        'Squire': 'node_modules/squirejs/src/Squire',
        'template': baseTemplatePath + 'html/template',
        'text': baseLibPath + 'lib/requirejs-text/text',
        'util': baseAppPath + 'util',
        'sprintf': baseLibPath + 'lib/sprintf'
    },
    shim: {
        'jstz': {
            exports: 'jstz'
        },
        'jquery.waypoints': {
            deps: ['jquery'],
            exports: 'Waypoint'
        },
        'jquery.waypoints.sticky': {
            deps: ['jquery.waypoints'],
            exports: 'Waypoint.Sticky'
        },
        'spin': {
            exports: 'Spinner'
        },
        'stomp': {
            exports: 'Stomp'
        },
        'sprintf': {
            exports: 'sprintf'
        }
    }

    // dynamically load all test files
    //deps: allTestFiles,

    // we have to kickoff jasmine, as it is asynchronous
    //callback: window.__karma__.start
});

require(allTestFiles, function () {
    window.__karma__.start();
});
</code></pre>

<p>Our main app requirejs config:</p>

<pre><code>global.requirejs.config({
        map: {
            '*': {
                underscore: 'lodash'
            }
        },
        paths: {
            'backbone': 'lib/backbonejs/backbone',
            'backbone.marionette': 'lib/backbonejs/backbone.marionette',
            'backbone.paginator': 'lib/backbonejs/backbone.paginator',
            'backbone.validation': 'lib/backbonejs/backbone.validation',
            'jquery.ui': 'lib/jquery/jquery.ui',
            'jquery.waypoints': 'lib/jquery/jquery.waypoints',
            'jquery.waypoints.sticky': 'lib/jquery/jquery.waypoints.sticky',
            'json3': 'lib/json3',
            'jstz': 'lib/jstz',
            'jszip': 'lib/kendoui/jszip.min',
            'lodash': 'lib/lodash',
            'moment': 'lib/momentjs/moment-with-locales',
            'moment.timezone': 'lib/momentjs/moment-timezone-with-data',
            'rsvp': 'lib/rsvp',
            'sockjs': 'lib/sockjs',
            'spin': 'lib/spin',
            'stomp': 'lib/stomp',
            'template': '../html/template',
            'text': 'lib/requirejs-text/text',
            'sprintf': 'lib/sprintf'
        },
        shim: {
            'jstz': {
                exports: 'jstz'
            },
            'jquery.waypoints': {
                deps: ['jquery'],
                exports: 'Waypoint'
            },
            'jquery.waypoints.sticky': {
                deps: ['jquery.waypoints'],
                exports: 'Waypoint.Sticky'
            },
            'spin': {
                exports: 'Spinner'
            },
            'stomp': {
                exports: 'Stomp'
            },
            'sprintf': {
                exports: 'sprintf'
            }
        }
    });

define('jquery', [], function() {
    return window.jQuery;
});
define('kendoui', [], function() {
    window.kendo.culture(""en-US"");
    window.kendo.culture().numberFormat.currency.pattern[0] = ""-$n"";

    return window.kendo;
});
</code></pre>

<p>I am very new to node, and have limited experience with karma, jasmine, and phantomJS, so I've been rolling around on my back for awhile now trying to figure this out, so any help would be excellent. Thanks!</p>
",https://stackoverflow.com/questions/41475511/karma-phantomjs-jasmine-kendo-ui-component-not-rendering-during-test,"['kendo-ui', 'jasmine', 'phantomjs', 'karma-runner', 'karma-jasmine']",258,FALSE,1,0
how to mock a method decorated with Python Flask route(),"<p>I need to unit test whether a method decorated by a Flask <code>route()</code> gets called or not.</p>

<p>I'd like to do this <em>without</em> modifying the original code under test, if possible, so mocking the method would suite my requirements perfectly.</p>

<p>Hence I am asking this <em>specific</em> question about how to mock a decorated request method (I want to stress this to try to avoid people wasting their time with less specific answers)...</p>

<p>Sample application <code>jflask.py</code>:</p>

<pre><code>from flask import Flask
app = Flask(__name__)
app.config.from_object(__name__)

@app.route('/hello')           # This method represents the code under test.
def hello():                   # I want to assert that this method gets
    return 'Hello, World'      # called without modifying this code.

if __name__ == ""__main__"":
    app.run()
</code></pre>

<p>In the unit test I'm using <code>@patch()</code> to mock the method so I can assert it was called, but the assertion fails. I.e. the mock method doesn't get called, when I expect it to.</p>

<p>Sample unit test <code>test_hello.py</code>:</p>

<pre><code>import unittest
import jflask
from unittest.mock import patch

class jTest(unittest.TestCase):
    def setUp(self):
        #jflask.app.testing = True
        self.app = jflask.app.test_client()

    @patch('jflask.hello')                # mock the hello() method
    def test_hello(self, mock_method):
        rv = self.app.get('/hello')
        mock_method.assert_called()    # this assertion fails
</code></pre>

<p>What am I doing wrong ?</p>

<hr>

<p><em>Background</em></p>

<p>Some background information about the <em>actual</em> behaviour I'm trying to test
(since the above is just a condensed test case, and may not seem entirely sane by itself).</p>

<p>In the actual code I am unit testing, there is a <code>before_request()</code> handler
installed for the app. This gets called by Flask before each request is handled, and in
certain situations this handler has been designed to return a response value, which
causes Flask request processing to stop (in this application's case, this feature is used to centrally validate request parameters), so that the usual routed request handler will (deliberately) not get called.</p>

<p>My unit tests need to assert that request processing gets stopped
or continues, appropriately depending on the situation.
Hence, my test needs to mock the real request handler and assert whether
it was called or not.</p>
",https://stackoverflow.com/questions/47621974/how-to-mock-a-method-decorated-with-python-flask-route,"['flask', 'mocking', 'python-unittest']",2704,FALSE,7,2
Is it possible to call npm CLI app&#39;s main JS file as if it was ran within a subfolder?,"<p>I have a <a href=""https://github.com/codsen/chlu-cli"" rel=""nofollow noreferrer"">small npm CLI library</a> which fixes errors in <code>changelog.md</code>'s sitting at the same directory where CLI is called. I'm trying to write at least one unit test for it's CLI part (its API is a separate library and it's well-tested).</p>

<p>It's easy to <em>trigger</em> CLI's main JS file using <code>execa</code> library, like:</p>

<pre><code>execa.sync('./cli.js')
</code></pre>

<p>but <strong>how do you trigger <code>cli.js</code> sitting in a root and meant to be looking for a <code>./changelog.md</code> in a root, to execute on a different test file in a subfolder (<code>/test/changelog.md</code>)</strong>?</p>

<p>Mind you, there's real <code>changelog.md</code> file in the root which has nothing to do with unit test.</p>

<p>(Worst case scenario, we could copy cli.js into <code>/test/</code>, call it there via <code>execa</code> and delete later, but this looks not DRY solution)</p>

<hr>

<p>My current AVA unit test is below. <code>seed</code> is incorrect <code>changelog.md</code> file. <code>intended</code> is correct <code>changelog.md</code> against which we'll compare later. I write <code>seed</code> contents into <code>/test/changelog.md</code> and want to run a CLI on it. Problem: how do I run <code>./cli.js</code> against <code>/test/package.json</code>? Mind you, I still want my CLI API to be simple, not accept any arguments with paths (what could be a last resort solution — to accept custom path arguments).</p>

<p>My current test is nearly there, but it runs against root, <code>./package.json</code> contents, not <code>/test/package.json</code> (which is how API would behave for end-user):</p>

<pre><code>import path from 'path'
import fs from 'fs'
import test from 'ava'
import execa from 'execa'

test('01.01 - reads and writes correctly', t =&gt; {
  var seed = fs.readFileSync(path.join('test', 'seed.md'), 'utf8')
  var intended = fs.readFileSync(path.join('test', 'intended.md'), 'utf8')
  fs.writeFileSync(path.join('test', 'changelog.md'), seed, 'utf8')

  execa.sync('./cli.js') // &lt;&lt;&lt; PROBLEM, this runs on root, not on ./test/changelog.md!

  t.deepEqual(
    fs.readFileSync(path.join('test', 'changelog.md'), 'utf8'),
    intended,
    '01.01'
  )
})
</code></pre>

<p>How do you execute an npm CLI package on a different directory when unit testing, if it's meant to be ran on file present at the same level as CLI's JS file?</p>

<p>Thank you.</p>
",https://stackoverflow.com/questions/44058508/is-it-possible-to-call-npm-cli-apps-main-js-file-as-if-it-was-ran-within-a-subf,"['javascript', 'node.js', 'unit-testing', 'npm', 'command-line-interface']",24,FALSE,1,0
Mocking module dependencies in AngularJS unit tests,"<p>I have an angular 1.5 project with many modules and each module may depend on other modules. Trying to unit test say a controller which is part of a module I would do import the module like this:</p>

<pre><code>angular.mock.module('SaidModule');
</code></pre>

<p>...then provide and inject its services where needed.</p>

<p>The problem is that <code>SaidModule</code> depends on <code>AnotherModule1</code>, <code>AnotherModule2</code>, <code>AnotherModule3</code>....</p>

<pre><code>angular.module('SaidModule', ['AnotherModule1', 'AnotherModule2', 'AnotherModule3']);
</code></pre>

<p>So naturally when I call SaidModule the other modules are also invoked which is out of scope in terms of Unit testing</p>

<p>In the unit test I have tried the following solution</p>

<pre><code>angular.module('AnotherModule1',[]);
angular.module('AnotherModule2',[]);
angular.module('AnotherModule3',[]);
angular.mock.module('SaidModule');
</code></pre>

<p>and although for the current unit test I have successfully decoupled the dependencies I have also destroyed 
the actual AnotherModule1, AnotherModule2, AnotherModule3 so when its there turn to be unit tested they are
not even visible in the angular project which seems correct to me. as I am using angular.module to define a 
new module which just happens to override the actual module. 
This solution though is also suggested here mocking module dependencies</p>

<p>In the angular docs it states see angular docs mock module
If an object literal is passed each key-value pair will be registered on the module via $provide.value, 
the key being the string name (or token) to associate with the value on the injector.</p>

<p>So it seems to me that the solution is using somehow angular.mock.module somehow to override the dependent 
modules but so far I have not found a solution. 
Any help much appreciated</p>
",https://stackoverflow.com/questions/43664305/mocking-module-dependencies-in-angularjs-unit-tests,"['javascript', 'angularjs', 'unit-testing', 'module', 'mocking']",2278,FALSE,1,1
Webpack host redirecting requests to google app engine backend,"<p>I am trying to use Angular2 CLI to help scaffold and create my angular 2 project. This includes a great setup for testing suite, webpack, etc.</p>

<p>I also have developed an API in Python on Google App Engine. Unfortunately, if I solely use GAE to host my front end, I lose some of the niceness of webpack (auto-detect, reload, unit testing).</p>

<p>I tried to use a proxy config to redirect my requests to my backend.</p>

<pre><code>{
  ""/api"" :{
    ""target"": ""http://localhost:8080"",
    ""secure"": false,
    ""loglevel"": ""debug""
  },
  ""/_ah"" :{
    ""target"": ""http://localhost:8080"",
    ""secure"": false,
    ""loglevel"": ""debug""
  }
}
</code></pre>

<p>I reference the proxy config with <code>ng serve --proxy-config proxy.config.json</code>.
This works for requests that I have defined using webapp2 directly. Those requests are held at the /api level.</p>

<p>This fails however for the requests I have defined behind /_ah, which I use the endpoints library to define.</p>

<pre><code>ModuleDoesNotExistError('localhost:4200',)
Traceback (most recent call last):
  File ""/usr/lib/google-cloud-sdk/platform/google_appengine/lib/cherrypy/cherrypy/wsgiserver/wsgiserver2.py"", line 1302, in communicate
    req.respond()
  File ""/usr/lib/google-cloud-sdk/platform/google_appengine/lib/cherrypy/cherrypy/wsgiserver/wsgiserver2.py"", line 831, in respond
    self.server.gateway(self).respond()
  File ""/usr/lib/google-cloud-sdk/platform/google_appengine/lib/cherrypy/cherrypy/wsgiserver/wsgiserver2.py"", line 2117, in respond
    for chunk in response:
  File ""/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/endpoints/endpoints_server.py"", line 121, in __call__
yield self.dispatch(request, start_response)
  File ""/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/endpoints/endpoints_server.py"", line 151, in dispatch
return self.call_spi(request, start_response)
  File ""/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/endpoints/endpoints_server.py"", line 324, in call_spi
spi_request.source_ip)
  File ""/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/dispatcher.py"", line 639, in add_request
headers_dict['Host'], urlparse.urlsplit(relative_url).path)
  File ""/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/dispatcher.py"", line 713, in _resolve_target
raise request_info.ModuleDoesNotExistError(hostname)
ModuleDoesNotExistError: localhost:4200
</code></pre>

<p>I am hoping there is a configuration that I can setup with GAE, to allow the requests from port 4200. Or some other way, that I can keep the value of angular cli / webpack combo, while hosting the local api with GAE.</p>

<hr>

<p><strong>UPDATE</strong></p>

<p>I did something pretty gross to get it to work, but I still feel like I am missing a configuration file.</p>

<p>My hack to get it to work was updating an app server py file:
<code>""/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/dispatcher.py""</code> </p>

<p>I changed line 685 to this hard coded option <code>if not hostname or hostname == default_address or hostname == 'localhost:4200':</code></p>

<p>This now, no longer throws an error, but is terrible fix. Any help would be appreciated, so I can back this out, and use the tool properly.</p>
",https://stackoverflow.com/questions/42599296/webpack-host-redirecting-requests-to-google-app-engine-backend,"['angular', 'google-app-engine', 'proxy', 'angular-cli', 'google-app-engine-python']",313,TRUE,1,1
dependency injection best practice,"<p>I'm getting into unit testing, and searching for days to find an answer, I found none.
I'm writing an app which reads the file system, searching for images and videos.
Then I want to instantiate a model for each image.</p>

<pre><code>class A 
{
   private function readFS ($path)
   {
       ... read file system, collect the media into an array ...
       foreach($files as $currentFile) {
            $return[$file-&gt;type][] = $file;
       }
       return $return;
   }

   // type can either be Image or Video
   private function instantiateModels ($type, $file)
   {
    return new $type(['file' =&gt; $file]);
   }

   public function processFolder ($path)
   {
    $files = $this-&gt;readFS($path);

    foreach($files as $type =&gt; $files) {
        foreach($files as $currentFile) {
            $type[] = $this-&gt;instantiateModels($type, $currentFile);
        }
    }

    ... then every media instance is saved to the database by calling it's save method: e.g.: Image::save() ...
}
</code></pre>

<p>then various data will be retrieved from the Image | Video instance and will be stored in a database.</p>

<p>Now, what is the best practice to do?<br>
Do I use Dependency Injection, or simply instantiate the models as it written in the example above?<br>
Then how do I unit test this class? If I understand right, because of blackbox testing and encapsulating, I should mock the instantiateModels() method, but private method shouldn't be tested or mocked.</p>

<p>If I dependency inject a factory, which can instantiate either an Image model or a Video model:</p>

<pre><code>class A 
{
      public function __construct (Factory $mediaFactory)
      {
             $this-&gt;factory = $mediaFactory;
      }

      private function instantiateModels ($type, $file)
      {
            return $this-&gt;factory-&gt;build($type, $file);
      }

      ...
}
</code></pre>

<p>then I can mock the factory, but as far as I understand it, that will be  a service locator, which is an anti pattern.</p>

<p>What do I do in this situation?</p>

<p>EDIT:
Or maybe the problem is, that my class A wants to do too many things at once, hence not meeting the 'single responsibility' principle?
May I create a class B which will search for media files and a class C that is a factory, which can instantiate Image and Video instances, and class A should take class B and class C as dependencies?
But then again, how do I unit test the factory class?</p>
",https://stackoverflow.com/questions/43435227/dependency-injection-best-practice,"['php', 'unit-testing', 'dependency-injection', 'service-locator']",133,FALSE,1,0
undefined is not a constructor in Mocha / Chai / Sinon on PhantomJS with Array.prototype.find,"<p>I'm at serious head scratching point with this now. I have a line of code in a method I'm trying to test which I just cannot get to pass whatever I do. It works! There is nothing wrong with it in 'the real world'.</p>

<p>I find everytime I delve into JS Unit Testing I hit snags like this and it makes me wonder if it's really worth it.</p>

<p>Here's the method I'm trying to test...</p>

<pre><code>    _mapStopsAroundHub(managerContext, soCode, homePostcode, homeStops, changeLinkedStopCallback) {
    homeStops = homeStops || [];
    MappingDataGateway.getNearbyStops(soCode, homePostcode, Cfg.DefaultNearbyStopDistance, (stops, status, xhr) =&gt; {
        if(status == MappingDataGateway.Status.OK) {
            stops.forEach((element) =&gt; {
                let isHomeStop = homeStops.length &gt; 0 &amp;&amp; (homeStops.find(hs =&gt; hs.id === element.id) !== undefined);
                let markerColor = isHomeStop ? ""green"" : ""orange"";
                let marker = managerContext.addBusStopMarker(element, markerColor);
                if (changeLinkedStopCallback) {
                    managerContext._api.event.addListener(marker, 'click', () =&gt; {
                        let newIcon = marker.icon.includes(""orange"") ? `/images/fa-bus-green.png` : `/images/fa-bus-orange.png`;
                        marker.setIcon(newIcon);
                        changeLinkedStopCallback(marker.data);
                    })
                }
            });
        }
        else if (errorCallback) { errorCallback(xhr); }
    });
}
</code></pre>

<p>I've added the 'isHomeStop' variable and the totally unnecessary homeSTops.length check to let some of the test cases pass but I can't test the case where the homeStops array contains data as Mocha falls over with it's ever so helpful error message 'undefined is not a constructor' type messages. The full error is as follows...</p>

<blockquote>
  <p>PhantomJS 2.1.1 (Windows 8 0.0.0) MapsManager can interract with a loaded map to map the stops around a hub point directly with a linked stop mapping all selectable stops in the area showing selected linked stops in a different colour FAILED
          undefined is not a constructor (evaluating 'homeStops.find(function (hs) {
                                      return hs.id === element.id;
                                  })')</p>
</blockquote>

<p>The test that's failing looks like this...</p>

<pre><code>  it(""directly with a linked stop mapping all selectable stops in the area showing selected linked stops in a different colour"", () =&gt; {
            let allStops = [{ id: 1 }, { id: 2 }, { id: 3 }];
            let homeStops = [{ id: 2 }];
            let mappingDataStub = Sinon.stub(MappingDataGateway, 'getNearbyStops');
            mappingDataStub.yields(allStops, ""OK"");
            let addMarkerStub = Sinon.stub(objUt, 'addBusStopMarker');

            objUt._mapStopsAroundHub(objUt, testSoCode, testPostCode, homeStops);
            mappingDataStub.restore();
            addMarkerStub.restore();

            Sinon.assert.calledThrice(addMarkerStub);
            Sinon.assert.calledWith(addMarkerStub, allStops[0], ""orange"");
            Sinon.assert.calledWith(addMarkerStub, allStops[1], ""green"");
            Sinon.assert.calledWith(addMarkerStub, allStops[2], ""orange"");
        });
</code></pre>

<p>I've put undefined checks in the code to check the state of the object and it's there - it seems that it's falling over on the lambda expression within find.</p>

<p>ADDITIONAL INFO: This only seems to happen with PhantomJS - If I use Chrome all runs fine (although this isn't a viable CI option!).</p>
",https://stackoverflow.com/questions/42145104/undefined-is-not-a-constructor-in-mocha-chai-sinon-on-phantomjs-with-array-p,"['javascript', 'ecmascript-6', 'phantomjs', 'mocha.js', 'chai']",2045,TRUE,1,3
TSQLT Test Run Timeout,"<p>I recently started using TSQLT through Redgate's SQL Test to create and run unit tests. I have run into a problem though. Unit tests that take more than a couple minutes to execute will time out, which halts the execution of all other unit tests.</p>

<p>How can I extend the length of the timeout  for tSQLt?</p>

<p>My ""unit testing"" is probably not actually unit testing, but I am not familiar with another testing methodology that fits better.</p>

<p>I am working on a project to improve the speed of the nightly refresh of our data warehouse. Currently, this process takes five hours. Through rearranging the tasks to run in parallel where possible, I have cut that time down to two hours. My problem is that unless I can find a way to prove that the new process has the exact same end result as the old process, QA will spend the next year checking every value in every column in every row in every table. Either that or the project will be scrapped as being ""too hard"".</p>

<p>So the testing that I have come up with is this:
I have a database where I run a script to copy over the resulting tables after they are processed in our testing environment using the new method that I created. Then, back in the testing environment, I run the old process to update the tables. Then, I run one unit test per table to prove that the contents of the archived tables processed using the new method is exactly identical to the contents of the tables re-processed using the old method.</p>

<p>Unfortunately due to the size of some of these tables (millions of rows) some of the unit tests are timing out. The following is the error that I am recieving:</p>

<blockquote>
  <p>Test Procedure: [HR360_unitTest1].[HR360_DW_Job6].[test
  fact_group_clients Identical Contents] on emr\preprod
  System.Data.SqlClient.SqlException (0x80131904): Timeout expired.  The
  timeout period elapsed prior to completion of the operation or the
  server is not responding. ---> System.ComponentModel.Win32Exception
  (0x80004005): The wait operation timed out    at
  System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
  Boolean breakConnection, Action`1 wrapCloseInAction)    at
  System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
  exception, Boolean breakConnection, Action`1 wrapCloseInAction)    at
  System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
  stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)    at
  System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,
  SqlCommand cmdHandler, SqlDataReader dataStream,
  BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
  stateObj, Boolean&amp; dataReady)    at
  System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,
  RunBehavior runBehavior, String resetOptionsString)    at
  System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior
  cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean
  async, Int32 timeout, Task&amp; task, Boolean asyncWrite, SqlDataReader
  ds, Boolean describeParameterEncryptionRequest)    at
  System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
  cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
  method, TaskCompletionSource<code>1 completion, Int32 timeout, Task&amp; task,
  Boolean asyncWrite)    at
  System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource</code>1
  completion, String methodName, Boolean sendToPipe, Int32 timeout,
  Boolean asyncWrite)    at
  System.Data.SqlClient.SqlCommand.ExecuteNonQuery()    at
  RedGate.SQLTest.tSQLt.FrameworkWrapper.#kz(SqlCommand #LGj)    at
  RedGate.SQLTest.tSQLt.FrameworkWrapper.#7qHc(String #2xAd,
  SqlParameter[] #LvPb)    at
  RedGate.SQLTest.tSQLt.FrameworkWrapper.#qd4b(String #LGxc)    at
  RedGate.SQLTest.tSQLt.TestRunner.Execute(SqlConnection connection)
  ClientConnectionId:519569ed-03ce-4510-b226-9ff18e0f1d8d Error
  Number:-2,State:0,Class:11</p>
</blockquote>

<p>If there is no way to increase the timeout for tSQLt, then I will either have to find another way to automatically test that the contents of these tables is identical (in a way that is repeatable at-will) or abandon the project.</p>
",https://stackoverflow.com/questions/45744870/tsqlt-test-run-timeout,"['sql-server', 'unit-testing', 'tsqlt']",478,TRUE,1,2
how to test complex asynchronous networked code and follow tdd,"<p>What would be the best practices for unit testing networked asynchronous code? I am trying to do/learn tdd</p>

<p>I am currently planning this part of a library, but in principle:
This is a ssh client library. I want it to be asynchronous. Ssh connection process is very complex, actually. My connect method would set some connection state variables in atomic way, then use some kind of task executor to schedule a connection task. The connection requires connecting to the server, introducing by sending and receiving ssh protocol version and stuff, then completing a key exchange process, that itself is divided into few cases, because there are few key exchange algorithms each requiring different packets to be exchanged.</p>

<p>Although I heard that I should test public api, and test private methods by testing public methods that use it, but in this case it seems difficult, as the task is quite complex and it is probably easier to fake only parts of a negotiation versus the whole connection/negotiation, just to check each possible result of a connect method including results of every key exchange algorithm.</p>

<p>Is it a good justification to split the larger connect tasks into smaller ones, even though they are not publicly available to the user, and test each separate connection stage instead of just the whole connect method all at once? Does it somehow break best practices, or how to do it in a different way? For example is it testing implementation details?</p>
",https://stackoverflow.com/questions/48009074/how-to-test-complex-asynchronous-networked-code-and-follow-tdd,"['java', 'tdd']",76,TRUE,0,1
Where should Full stack JS beginner start?,"<p>So I won't say I'm a complete beginner, as I know the very basics and have a CS degree(that I'm very rusty at) but I have gone back through and refreshed myself with the CS50 Harvard course.</p>

<p>The last project is to build something, and I've gotten more into learning JS for unit testing at work and while we mostly use rails...I'm interested in learning the new emergent stuff.</p>

<p>I've heard the 70/30 rule applies to full stack devs, and I can't imagine if ever be good with front end stuff so I'd imagine that would be my ""30"". However with ES6 out and all these new conventions and frameworks I'm a bit lost where I should start?</p>

<p>There is a highly rated JS and Jquery book on Amazon I've been eyeing, but it's quite old. And I wonder about backend frameworks too.</p>

<p>My ideal learning ""stack"" would be node/react and mongo (with express for node) but it seems like a bad idea to learn them all at once. If I'm interested in backend should I just stick with learning node/express first? </p>

<p>Do I need to worry about ES6 as a beginner? I guess I'm just stuck where to start and in general which path I should take. I've done some dabbling in express but it seems like getting at least decent with JS and Jquery makes sense first?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/42990952/where-should-full-stack-js-beginner-start,['javascript'],99,TRUE,-4,1
Passing arguments to dotnet test project?,"<p>I have the test class below in a .NET Core 1.1 Unit Test project (not an xUnit Test project) in Visual Studio 2017. How do I pass command line arguments to <code>TestMethod</code>?</p>
<pre><code>[TestClass]
public class TestClass
{
    [TestMethod]
    public void TestMethod()
    {
        var args = Environment.GetCommandLineArgs();
        var json = JsonConvert.SerializeObject(args);
        throw new Exception(json);
    }
}
</code></pre>
<p>Lots of places on the internet make it sound like you can just put a <code>--</code> in front of the arguments you want to pass in, but I can't get it to work.</p>
<p>These are the commands I've tried:</p>
<ul>
<li><code>dotnet test TestProject.csproj -- hello=world</code></li>
<li><code>dotnet test TestProject.csproj -- --hello world</code></li>
<li><code>dotnet test TestProject.csproj -- -hello world</code></li>
</ul>
<p>But all of them output this message every time. Note how neither <code>hello</code> nor <code>world</code> are present:</p>
<blockquote>
<p>[&quot;C:\Users\____\.nuget\packages\microsoft.testplatform.testhost\15.0.0\lib\netstandard1.5\testhost.dll&quot;,&quot;--port&quot;,&quot;55032&quot;,&quot;--parentprocessid&quot;,&quot;24440&quot;]</p>
</blockquote>
<p>The first string is just the name of the running assembly -- <a href=""https://learn.microsoft.com/en-us/dotnet/api/system.environment.getcommandlineargs#System_Environment_GetCommandLineArgs"" rel=""nofollow noreferrer"">pretty standard for the first command line argument</a>. I don't know where the <code>--port</code> or <code>--parentprocessid</code> arguments are coming from.</p>
<p>Also, these variations make <code>dotnet test</code> choke with <code>One or more runsettings provided contain invalid token</code> (sic):</p>
<ul>
<li><code>dotnet test TestProject.csproj -- -hello=world</code></li>
<li><code>dotnet test TestProject.csproj -- --hello=world</code></li>
</ul>
<hr />
<p>Edit: It looks like <code>GetCommandLineArgs()</code> <a href=""https://stackoverflow.com/a/9288040/3063273"">isn't that great of an option</a>, even if it did work here.</p>
<p>Also, <a href=""https://social.msdn.microsoft.com/Forums/en-US/441920ee-eb35-4bdc-b777-044f0cbfe6e3/setting-commandline-arguments-for-a-unittest-project?forum=vststest"" rel=""nofollow noreferrer"">the answer to this question on social.msdn.microsoft.com from 2006</a> says:</p>
<blockquote>
<p>The way those classes are instantiated so VS can do unit testing against them is entirely different than normal execution.  The executable is not run like normal, and <strong>neither you nor VS can provide arguments to it</strong>. The classes are instantiated indepdently of program execution by using the binary as a class library. (sic)</p>
</blockquote>
<p>I wonder if this still applies to <code>dotnet test</code>?</p>
<p>In other news, <a href=""https://stackoverflow.com/a/181404/3063273"">this guy on SO</a> was doubtful that command line arguments could be passed to DLLs at all, but <a href=""https://support.microsoft.com/en-us/help/164787/info-windows-rundll-and-rundll32-interface"" rel=""nofollow noreferrer"">he's wrong</a>:</p>
<blockquote>
<p>[Prototype for the &lt;entrypoint&gt; function:] void CALLBACK EntryPoint(HWND hwnd, HINSTANCE hinst, <strong>LPSTR lpszCmdLine</strong>, int nCmdShow);</p>
<p>[Rundll] calls the &lt;entrypoint&gt; function, <strong>passing the command line tail</strong> which is the &lt;optional arguments&gt;.</p>
</blockquote>
",https://stackoverflow.com/questions/42992148/passing-arguments-to-dotnet-test-project,"['c#', 'automated-tests', 'integration-testing', '.net-core']",12113,TRUE,12,3
Resolving a promise in Angular Service,"<p>We have a service, lets call it <code>AccountService</code> which exposes a method called <code>getAccounts(customerId)</code> among others.</p>

<p>In its implementation all it does is to fire up a $http GET request and return a promise to the calling controller which will put the returned array of accounts in the controller scope once resolved.</p>

<p>On a simplified view all looks like below:</p>

<pre><code>// The service
.factory('AccountService', ['$http', function($http) {
    var _getAccounts = function(customerId) {
        var request = {
            'method': 'GET',
            'url': 'http://localhost:8081/accounts/' + customerId
        };
        return $(request);
    };

    return {
        getAccounts: _getAccounts
    };
}]);

// Inside the conntroller
AccountService.getAccounts($scope.customerId)
    .then(function(response) {
        $scope.accounts = response.data;
    });
</code></pre>

<p>So once the promise will resolve the controller scope will get populated with the list of accounts.</p>

<p>Note that I kept the above code as simple as I could to get you the idea of what my problem is but in reality it will be code to deal with exceptions, watcher to refresh, etc. Everything works fine.</p>

<p>My problem is that this AccountService is used from lots of controllers and putting the promise resolve in all of these looks to me not only repeating all this boiler plate resolver code but also complicating the unit testing as I am obliged to r/test both successful and exception scenarios in every single controller test.</p>

<p>So my question is:
Is there a nice way to resolve the promise in the service and return the response to the controller, not the promise?</p>

<p>Please note I am a very beginner with Angular and JS so please be gentle if my question looks naive. I have heaps of java experience and my mind seems to go java like everywhere which may not be the case.</p>

<p>Thank you in advance for your inputs</p>
",https://stackoverflow.com/questions/41733157/resolving-a-promise-in-angular-service,"['javascript', 'angularjs']",1989,TRUE,0,3
Creating auto initialized static objects in Java,"<p>I'm trying to create a subclass which auto creates itself. I defined <code>Base</code> which holds a list of instances. Then I defined <code>Derived</code> with a static member <code>reg</code>. <code>reg</code> is in place initialized by calling <code>Base.Register()</code>, which adds it to the instances list.</p>

<p>In the <code>main()</code> I'm printing the instances list of <code>Base</code>. But there is no initialization and I get an error - the instances list is <code>null</code>.</p>

<p>In a further attempt, I added a list of <code>Booleans</code> to <code>Base</code>. Whenever I register an instance, I'm changing this list. I also print this list in the program. I expected it to force the execution of the <code>Base.register()</code>, but to no avail.</p>

<p>I did find a solution that worked, but I don't appreciate - I could print the result of the <code>Base.register()</code> as saved in the <code>Derived</code>. That would force the static initialization. However, I intend to use the solution for a bunch of derived classes, and I wouldn't want to have to call each derived class directly.</p>

<p>Is there a way to force the static init?</p>

<p>I guess I could use reflections, I'm trying to avoid that at the moment.</p>

<p>EDIT what I am actually trying to do, is to build a set of derived classes (for unit testing). All classes derive <code>Base</code>. I want to avoid the need to create instances separately for each. I'm trying to get a generic solution, in each derived class code (only). Such a solution would be easy to copy &amp; paste.</p>

<pre><code>public class StaticTest {

    private static class Base{
        private static ArrayList&lt;Base&gt; _instances = null;
        private static ArrayList&lt;Boolean&gt; _regs = null;
        public static int _count = 0;
        public static void init(){
            _regs = new ArrayList&lt;&gt;();
            for (int i=0;i&lt;10;i++)
                _regs.add(false);
        }
        protected static boolean register(Base b)
        {
            if (_instances == null)
                _instances = new ArrayList&lt;&gt;();

            _regs.set(_count++, true);

            return _instances.add(b);
        }

        public static void printAll(){
            for (Boolean b: _regs)
                System.out.printf(""hello %s%n"", b.toString());
            for (Base b: _instances)
                System.out.printf(""hello %s%n"", b.toString());
        }
    }

    private static class Derived extends Base{
        public static boolean _reg = Base.register(new Derived());
    }

    public static void main(String[] args) {
        //System.out.print(Derived._reg ? ""0"" : ""1"");
        Base.init();
        System.out.printf(""Base._count = %d%n"",Base._count);
        Base.printAll();
    }

}
</code></pre>
",https://stackoverflow.com/questions/44215557/creating-auto-initialized-static-objects-in-java,"['java', 'static', 'initialization']",99,FALSE,0,1
How to test complex purchasing with phpunit?,"<p>I'm new at unit testing and I think I need test a purchase process,
but it complex.</p>

<p>In our project we have a purchasing process by user<br>
that includes two stages</p>

<ol>
<li>User make an order and user is redirected to paygate.<br>
We save the customer's email with that order.</li>
<li>Paygate send to us order info with payment status (success or fail)<br>
if success<br>
we run single complex sql query that using postgresql CTE and<br>
query creates a user if user doesn't exists, upserts some other rows,<br>
query also returning email address that using in email message that send 
to user if new user was created.</li>
</ol>

<p>I try test second stage.</p>

<p>Exapmles for testing contains tests for simple functions like sum(),<br>
I understand that complex process must be decomposed to simple pieces of code and every piece must be inependent from others.</p>

<p>But how I must test an sql transaction if every result of each query in transaction depends on results of previos query?</p>

<p>For example<br>
upsert user<br>
if user was inserted (if new)<br>
then add user to subscribers table<br>
if user registered from partner then add partner notification about this event<br>
and so on  </p>

<p>Previos logic written in single sql query.
How should I test that every query changed data right?  </p>

<p>Or should I rewrite cte queries to one-by-one in transaction?<br>
If so, how to understand was new user created or not from transaction?</p>

<p>query now looks like  </p>

<pre><code>WITH ""exists_user""  AS (  
    SELECT ""email"",0 ""created_user""  
    FROM ""user""   
    WHERE ""email""='email'  
),  
""inserted_user"" AS (  
     INSERT INTO ""user""(""email"")  
     VALUES('email')  
     WHERE NOT EXISTS (SELECT 1 FROM ""exists_user"")  
     RETURNING ""email"" ,1 ""created_user""  
)  
SELECT * FROM ""exists_user""  
UNION ALL  
SELECT * FROM ""inserted_user""  
</code></pre>
",https://stackoverflow.com/questions/43930788/how-to-test-complex-purchasing-with-phpunit,"['postgresql', 'unit-testing', 'common-table-expression']",40,FALSE,0,1
Integration testing with Python unittest: how to improve granularity?,"<p>I have a single end-to-end Selenium integration test which consists of several steps with each step setting certain state and passing the data over to the next step.</p>

<p>Test scenario:</p>

<pre><code>1. Create item.
2. Assign item to group.
3. Approve item.
...
4. Publish item.
</code></pre>

<p>The steps are not atomic and depend on each other. The test class extends from <code>unittest.TestCase</code> and contains a single <code>test_xyz()</code> method which wraps the methods for each step.</p>

<p>Currently, the final report only includes the pass/fail status for the wrapper <code>test_xyz()</code> method. I would like to have each step being treated as a 'test step' and have a separate entry in the test report.</p>

<p>It feels wrong to convert all the steps into <code>test_step1()</code>, <code>test_step2()</code> etc and then enforcing the execution order and data exchange since the steps are not self-contained tests.</p>

<p>Is there a way to mark certain methods as test steps so that they appear as separate entries in the test report? </p>

<p>Basically, all I want is improving the visual reporting so that it is more obvious from the report at which step the entire integration test failed. Is this achievable with <code>unittest</code>? What would be the best practice in organizing the code so that it fits into the unittest paradigm?</p>

<p>Not sure <code>unittest</code> is the best tool for integration tests, since this is not strictly speaking <em>unit testing</em>. Would switching to something like pytest make more sense for integration testing while still allowing 'free' HTML report generation? (I am currently using <a href=""http://nose.readthedocs.io/"" rel=""noreferrer"">nose</a> to run the test and to generate the HTML report with the corresponding <a href=""https://pypi.python.org/pypi/nose-html-reporting"" rel=""noreferrer"">nose plugin</a>.)</p>
",https://stackoverflow.com/questions/44750839/integration-testing-with-python-unittest-how-to-improve-granularity,"['python', 'integration-testing', 'pytest', 'python-unittest', 'nose']",8665,TRUE,6,1
SpringBootTest mock Authentication Principal with a custom User does not work,"<p>I am using Spring Boot 1.4.2 and I am new with Spring Boot. 
I have an Authentication Filter to set the current user information when the user log in. 
In an advice for the controller, I made the call to get the current userId as below: </p>

<pre><code>public static String getCurrentUserToken(){
    return ((AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUserId();
}
</code></pre>

<p>Here is my custom AuthenticatedUser:</p>

<pre><code>public class AuthenticatedUser implements Serializable {

private final String userName;
private final String userId;
private final String sessionId;

public AuthenticatedUser(String userName, String userId, String sessionId) {
    super();
    this.userName = userName;
    this.userId = userId;
    this.sessionId = sessionId;
}

public String getUserName() {
    return userName;
}

public String getUserId() {
    return userId;
}

public String getSessionId() {
    return sessionId;
}
</code></pre>

<p>}</p>

<p>Everything works fine. 
However, the filter does not work in integration testing and I need to mock a current user. 
I searched a lot on how to mock a user but none of them help me. I finally found out this guide  which is likely close to what I wanted: <a href=""https://aggarwalarpit.wordpress.com/2017/05/17/mocking-spring-security-context-for-unit-testing/"" rel=""nofollow noreferrer"">https://aggarwalarpit.wordpress.com/2017/05/17/mocking-spring-security-context-for-unit-testing/</a> 
Below is my testing class following that guideline:</p>

<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
public class PersonalLoanPreApprovalTest {

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

@Test
public void testRequestPersonalLoanPreApproval_Me() {
  AuthenticatedUser applicationUser = new 
  AuthenticatedUser(""test@abc.com"", ""2d1b5ae3"", ""123"");
  UsernamePasswordAuthenticationToken authentication = new ApiKeyAuthentication(applicationUser);
  SecurityContext securityContext = mock(SecurityContext.class);

  when(securityContext.getAuthentication()).thenReturn(authentication);
  SecurityContextHolder.setContext(securityContext);

  // error at this line
  when(securityContext.getAuthentication().getPrincipal()) .thenReturn(applicationUser); 

  // The controller for this api has the advice to get the userId
  MyResponse response = restTemplate.getForObject(url.toString(), MyResponse.class);
}
}
</code></pre>

<p>I got this error:</p>

<pre><code>org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
AuthenticatedUser cannot be returned by getAuthentication()
getAuthentication() should return Authentication
</code></pre>

<p>I spent couple days on this already, tried a lot of suggestions I found but still failed. I also tried to remove the line that cause error, but when the error gone, I still could not get the current user information in my controller advice.</p>

<p>Any suggestion is highly appreciated. </p>

<p><strong>UPDATE1:</strong> Just wanted to have my results with some modification in the code.</p>

<p>With @glitch suggestion, I changed the code to mock the authentication and user in my test method as below:</p>

<pre><code> @Test
 public void testRequestPersonalLoanPreApproval_Me() {
    AuthenticatedUser applicationUser = new AuthenticatedUser(""testtu_free@cs.com"", ""2d1b5ae3-cf04-44f5-9493-f0518cab4554"", ""123"");
    Authentication authentication = Mockito.mock(Authentication.class);
    SecurityContext securityContext = Mockito.mock(SecurityContext.class);
    Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
    SecurityContextHolder.setContext(securityContext);
    Mockito.when(authentication.getPrincipal()).thenReturn(applicationUser);      

  // The controller for this api has the advice to get the userId
  MyResponse response = restTemplate.getForObject(url.toString(), MyResponse.class);
}
}
</code></pre>

<p>I now can get rid of the error in the testing class. I debugged into the code, see that the securityContext has value when I am in the testing class. But when I jump to the code inside the controller advice, the below get returns null: </p>

<pre><code>SecurityContextHolder.getContext().getAuthentication().getPrincipal()
</code></pre>
",https://stackoverflow.com/questions/46615504/springboottest-mock-authentication-principal-with-a-custom-user-does-not-work,"['java', 'authentication', 'spring-boot', 'mockito']",17532,TRUE,5,2
Avoid long lists of arguments in constructor service Symfony,"<p>I've been using Symfony to develop my web applications but I keep running into one problem. I always end up with too much clutter in the constructor of my services since I want to be able to unit test my services properly.</p>

<h2>Theoretical use case</h2>

<p>Let's say I need a service which allows me to process an XML file and save it's contents into the database.</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8"" ?&gt;
&lt;users&gt;
    &lt;user&gt;
        &lt;id&gt;1234&lt;/id&gt;
        &lt;username&gt;Example User&lt;/username&gt;
        &lt;email&gt;user@example.com&lt;/email&gt;
        &lt;usergroup&gt;
            &lt;id&gt;567&lt;/id&gt;
            &lt;name&gt;Example User Group&lt;/name&gt;
        &lt;/usergroup&gt;
        &lt;permissions&gt;
            &lt;item&gt;ALLOWED_TO_CREATE&lt;/item&gt;
            &lt;item&gt;ALLOWED_TO_UPDATE&lt;/item&gt;
            &lt;item&gt;ALLOWED_TO_DELETE&lt;/item&gt;
            &lt;item&gt;ALLOWED_TO_view&lt;/item&gt;
        &lt;/permissions&gt;
    &lt;/user&gt;
&lt;/users&gt;
</code></pre>

<p>Already quite a few things come to mind which you need to inject into this service:</p>

<ul>
<li>DomCrawler (to read the XML file)</li>
<li>UserRepository (to get existing Users)</li>
<li>UserGroupRepository (to get existing UserGroups)</li>
<li>PermissionsRepository (to get existing permissions)</li>
<li>EntityManager (to persist en flush new/updated objects)</li>
</ul>

<p>The real XML file I'm working with contains much more data which requires me to inject many more repositories and other services which handle certain logic.</p>

<h2>Solution 1: Use Doctrine service</h2>

<p>Inject the Doctrine service directory into my service and get the repositories via <code>$doctrine-&gt;getRepository(User::class)</code></p>

<p><strong>Pros</strong></p>

<ul>
<li>Significatly reduces the amount of arguments</li>
</ul>

<p><strong>Cons</strong></p>

<ul>
<li>Unit testing becomes a lot harder since I don't know what the service accesses anymore which renders them useless</li>
</ul>

<h2>Solution 2: Use setter injection</h2>

<p>Remove all services and repositories from the constructor and create setter methods and call then in the services.yml</p>

<pre><code>services:
  AppBundle\Service\MyImportService:
    calls:
      - [setUserRepository, ['@app.user_repository']]
</code></pre>

<p><strong>Pros</strong></p>

<ul>
<li>Arguably easier to read</li>
</ul>

<p><strong>Cons</strong></p>

<ul>
<li>More code</li>
<li>Services no longer mandatory, optional validation may be required</li>
</ul>

<h2>Question</h2>

<p>What are solutions to make the argument lists in my services more maintainable in terms of readability and ability to unit test?</p>

<p>Is it even considered bad practise to have a long list of arguments?</p>
",https://stackoverflow.com/questions/45253478/avoid-long-lists-of-arguments-in-constructor-service-symfony,"['php', 'symfony', 'unit-testing', 'dependency-injection']",1203,TRUE,4,1
Does a standard structure of JUnit tests exist? How many assertions per test are usually prefered?,"<p>I will explain this better with an example:</p>

<p>Imagine I have a function that receives an array of X integers and an extra integer that contains a starting position, it calculates the average value for 10 numbers in the array starting from that position, but ignores <code>0</code> values and returns <code>-1000000</code> if the array doesn't contain 10 or more values from the starting position to the end:</p>

<pre><code>public double calculateAverage(ArrayList&lt;Integer&gt;, int startingPosition){
    //functionLogic
    return myAverage;
}
</code></pre>

<p>I am new to unit testing, but I would suggest doing the following tests here:</p>

<ul>
<li>Test with a 20 integer list and <code>5</code> as starting position. (should return the average value of the 10 numbers from <code>5</code> to <code>14</code>)</li>
<li>Test with a 20 integer list and <code>15</code> as starting position. (should return <code>-1000000</code>)</li>
<li>Test with a 9 integer list. (should return <code>-1000000</code>, no matter the starting position)</li>
<li>Test with a 20 integer in which half of the numbers are <code>0</code> and 5 as starting position. (should return the average of numbers between <code>5</code> and <code>14</code> without counting <code>0</code>s).</li>
<li>Test with a 20 integer in which half of the numbers are <code>0</code> and 15 as starting position. (should return <code>-1000000</code>)</li>
</ul>

<p><em>This tests might be not enough, or too many, or simply bad tests, please, feel free to comment on any improvement, as I am sure most of you know more about unitary tests than I do</em>.</p>

<p><strong>My question:</strong></p>

<p>Do I have to write 5 different JUnit test functions? Is it better to write only 1 with 5 assertions? Or do I dive it (for example) in groups of 2 and 3?</p>

<p>What's the recommended style here?</p>

<p>Thank you all for your patience.</p>
",https://stackoverflow.com/questions/41736581/does-a-standard-structure-of-junit-tests-exist-how-many-assertions-per-test-are,"['java', 'unit-testing', 'junit']",150,TRUE,4,2
Handling Apollo-wrapped descendants in unit tests that mount the React component,"<p>I've been working with ApolloJS in React (via <code>react-apollo</code>) for the past several months and have learned a number of the tricks and challenges associated with unit testing Apollo-wrapped components.</p>

<p>When testing a component that is directly wrapped with Apollo, I export and test the component before it is wrapped with HoC returned by <code>graphql</code>. When testing a component that has an Apollo-wrapped component as a descendant, I use Enzyme's <code>shallow</code> rendering whenever possible to prevent that descendant from mounting. If full-DOM rendering via <code>mount</code> is required, I use a <code>MockedProvider</code> from Apollo's test utils so that the descendants don't throw an error trying to access <code>this.context</code>.</p>

<p>I have not found a solution, however, for the following case: a component with Apollo-wrapped descendants needs to be tested using full-DOM rendering but I also need to make assertions involving the component instance (e.g. state, instance methods, etc). To avoid issues with descendants, I have to wrap the component in a mocked provider, but that means than any assertions on the <code>wrapper</code> are operating on the <code>MockedProvider</code> instance and not the component I want to be testing.</p>

<p>An example:</p>

<pre><code>import { mount } from 'enzyme'
import { MockedProvider } from 'react-apollo/lib/test-utils'

// This component has descendants that are wrapped in Apollo and
// thus need access to `this.context` provided by an Apollo provider
import Assignments from 'app/components/assignments

...

describe('&lt;Assignments /&gt;', function() {
  it('sets sorted assignments in initial state', function() {
    const assignments = [...]

    const wrapper = mount(
      &lt;MockedProvider&gt;
        &lt;Assignments assignments={assignments} /&gt;
      &lt;/MockedProvider&gt;
    )

    // This will fail because the wrapper is of the MockedProvider
    // instance, not the Assignments instance
    expect(wrapper.state('assignments')).to.eql([...])
  })
})
</code></pre>

<p>I've tried to find a way via Enzyme to access the component instance of a child rather than the root, which as far as I can tell is not supported. I've also been trying to find alternatives to needing the <code>MockedProvider</code> in these tests but have not found anything yet.</p>

<p>Has anyone figured out a workaround for this sort of situation, or is there a different approach I should be taking to deal with nested Apollo-wrapped components?</p>
",https://stackoverflow.com/questions/46205173/handling-apollo-wrapped-descendants-in-unit-tests-that-mount-the-react-component,"['reactjs', 'enzyme', 'apollo', 'react-apollo']",1151,TRUE,3,1
googletest &amp; cmake - Undefined symbols for architecture x86_64,"<p>I'm working on a simple c++ project and I wanted to use unit testing, specifically googletest. To get started, I based the structure of my project on <a href=""https://github.com/snikulov/google-test-examples"" rel=""nofollow noreferrer"">https://github.com/snikulov/google-test-examples</a>. When I cloned it and tested it, it worked perfectly. I then moved the required components to my project and I get the following linker error:</p>

<pre><code>Undefined symbols for architecture x86_64:
  ""Vector::Vector(int, float*)"", referenced from:
      cpp_vector_test_vector_operator_adder_Test::TestBody() in cpp_vector_test.cc.o
  ""Vector::~Vector()"", referenced from:
      cpp_vector_test_vector_operator_adder_Test::TestBody() in cpp_vector_test.cc.o
  ""Vector::operator==(Vector)"", referenced from:
      cpp_vector_test_vector_operator_adder_Test::TestBody() in cpp_vector_test.cc.o
  ""Vector::operator+(Vector)"", referenced from:
      cpp_vector_test_vector_operator_adder_Test::TestBody() in cpp_vector_test.cc.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code></pre>

<p>I've been working through this for a few hours with a day or two in between and have had no luck. My project can be found at <a href=""https://github.com/bi3mer/Bragi"" rel=""nofollow noreferrer"">https://github.com/bi3mer/Bragi</a>. I've been playing around with the cmake configuration for a while I tried running cmake like so:</p>

<pre><code>cmake -DBUILD_SHARED_LIBS=ON ..
</code></pre>

<p>and the regular:</p>

<pre><code>cmake ..
</code></pre>

<p>A particularly odd note that is throwing me off is that if I have my test code like so:</p>

<pre><code>#include ""Vector.h""
#include ""gtest/gtest.h""

TEST(cpp_vector_test, vector_operator_adder)
{
    EXPECT_EQ(true, true);
}
</code></pre>

<p>It will work fine. It is only once I try to instantiate my class that there is an error.</p>

<pre><code>#include ""Vector.h""
#include ""gtest/gtest.h""

TEST(cpp_vector_test, vector_operator_adder)
{
    Vector test = Vector(3); // throws error
    EXPECT_EQ(true, true);
} 
</code></pre>

<p>I've also looked other threads such as <a href=""https://stackoverflow.com/questions/17267306/gtest-undefined-symbols-for-architecture-x86-64-error-with-clang-and-stdvec"">gtest: Undefined symbols for architecture x86_64 error with clang++ and std::vector</a> but I have no idea where the configure script is coming from.</p>

<p>Based on everything that I've found it looks like there is a compiler mismatch going on, I'm just not sure how to fix it based on everything I've read. </p>

<p>I hope you can help, to clone:</p>

<pre><code>git clone https://github.com/bi3mer/Bragi.git
</code></pre>

<p>I figure this is easier than pasting in the files and everying. I hope you can help, I've included the output of when I try to build below. Thank you for the help.</p>

<pre><code>./build.sh 
-- The C compiler identification is AppleClang 8.0.0.8000042
-- The CXX compiler identification is AppleClang 8.0.0.8000042
-- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc
-- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++
-- Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Looking for pthread.h
-- Looking for pthread.h - found
-- Looking for pthread_create
-- Looking for pthread_create - found
-- Found Threads: TRUE  
-- Configuring done
-- Generating done
-- Build files have been written to: /Users/colan/Documents/work/Bragi/build
Scanning dependencies of target googletest
[ 10%] Creating directories for 'googletest'
[ 20%] Performing download step (git clone) for 'googletest'
Cloning into 'googletest'...
Already on 'master'
Your branch is up-to-date with 'origin/master'.
[ 30%] No patch step for 'googletest'
[ 40%] Performing update step for 'googletest'
Current branch master is up to date.
[ 50%] Performing configure step for 'googletest'
-- The C compiler identification is AppleClang 8.0.0.8000042
-- The CXX compiler identification is AppleClang 8.0.0.8000042
-- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc
-- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++
-- Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Found PythonInterp: //anaconda/bin/python (found version ""2.7.12"") 
-- Looking for pthread.h
-- Looking for pthread.h - found
-- Looking for pthread_create
-- Looking for pthread_create - found
-- Found Threads: TRUE  
-- Configuring done
-- Generating done
CMake Warning:
  Manually-specified variables were not used by the project:

    CMAKE_ARCHIVE_OUTPUT_DIRECTORY_DEBUG
    CMAKE_ARCHIVE_OUTPUT_DIRECTORY_RELEASE


-- Build files have been written to: /Users/colan/Documents/work/Bragi/build/ext/gtest/src/googletest-build
[ 60%] Performing build step for 'googletest'
Scanning dependencies of target gmock
[  9%] Building CXX object googlemock/CMakeFiles/gmock.dir/__/googletest/src/gtest-all.cc.o
[ 18%] Building CXX object googlemock/CMakeFiles/gmock.dir/src/gmock-all.cc.o
[ 27%] Linking CXX static library libgmock.a
[ 27%] Built target gmock
Scanning dependencies of target gmock_main
[ 36%] Building CXX object googlemock/CMakeFiles/gmock_main.dir/__/googletest/src/gtest-all.cc.o
[ 45%] Building CXX object googlemock/CMakeFiles/gmock_main.dir/src/gmock-all.cc.o
[ 54%] Building CXX object googlemock/CMakeFiles/gmock_main.dir/src/gmock_main.cc.o
[ 63%] Linking CXX static library libgmock_main.a
[ 63%] Built target gmock_main
Scanning dependencies of target gtest
[ 72%] Building CXX object googlemock/gtest/CMakeFiles/gtest.dir/src/gtest-all.cc.o
[ 81%] Linking CXX static library libgtest.a
[ 81%] Built target gtest
Scanning dependencies of target gtest_main
[ 90%] Building CXX object googlemock/gtest/CMakeFiles/gtest_main.dir/src/gtest_main.cc.o
[100%] Linking CXX static library libgtest_main.a
[100%] Built target gtest_main
[ 70%] No install step for 'googletest'
[ 80%] Completed 'googletest'
[ 80%] Built target googletest
Scanning dependencies of target Bragi_test
[ 90%] Building CXX object CMakeFiles/Bragi_test.dir/test/cpp_vector_test.cc.o
[100%] Linking CXX executable Bragi_test
Undefined symbols for architecture x86_64:
  ""Vector::Vector(int, float*)"", referenced from:
      cpp_vector_test_vector_operator_adder_Test::TestBody() in cpp_vector_test.cc.o
  ""Vector::~Vector()"", referenced from:
      cpp_vector_test_vector_operator_adder_Test::TestBody() in cpp_vector_test.cc.o
  ""Vector::operator==(Vector)"", referenced from:
      cpp_vector_test_vector_operator_adder_Test::TestBody() in cpp_vector_test.cc.o
  ""Vector::operator+(Vector)"", referenced from:
      cpp_vector_test_vector_operator_adder_Test::TestBody() in cpp_vector_test.cc.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[2]: *** [Bragi_test] Error 1
make[1]: *** [CMakeFiles/Bragi_test.dir/all] Error 2
make: *** [all] Error 2
UpdateCTestConfiguration  from :/Users/colan/Documents/work/Bragi/build/DartConfiguration.tcl
UpdateCTestConfiguration  from :/Users/colan/Documents/work/Bragi/build/DartConfiguration.tcl
Test project /Users/colan/Documents/work/Bragi/build
Constructing a list of tests
Done constructing a list of tests
Updating test list for fixtures
Added 0 tests to meet fixture requirements
Checking test dependency graph...
Checking test dependency graph end
test 1
    Start 1: test1
Could not find executable Bragi_test
Looked in the following places:
Bragi_test
Bragi_test
Release/Bragi_test
Release/Bragi_test
Debug/Bragi_test
Debug/Bragi_test
MinSizeRel/Bragi_test
MinSizeRel/Bragi_test
RelWithDebInfo/Bragi_test
RelWithDebInfo/Bragi_test
Deployment/Bragi_test
Deployment/Bragi_test
Development/Bragi_test
Development/Bragi_test

1: Test command: 
Unable to find executable: Bragi_test
1/1 Test #1: test1 ............................***Not Run   0.00 sec

0% tests passed, 1 tests failed out of 1

Total Test time (real) =   0.00 sec

The following tests FAILED:
      1 - test1 (Not Run)
Errors while running CTest
</code></pre>
",https://stackoverflow.com/questions/41453253/googletest-cmake-undefined-symbols-for-architecture-x86-64,"['c++', 'unit-testing', 'linker', 'x86', 'googletest']",1915,TRUE,3,1
Are DAOs still needed in Spring MVC with JPA/Hibernate,"<p>I know that this question has been asked countless times, but since most of the questions on this subject are 6-7 years old, I was hoping to see if there are any changes in the original arguments for/against this topic as newer versions of JPA came out. I know that this can be seen as primarily opinion based, but I am looking for a list of pros/cons.</p>

<p>Some people have argued that the entitymanager is a DAO in and of itself, and that a DAO layer in your application would be redundant. Most people would agree that the <code>EntityManager</code> covers basic CRUD operations very tightly...but there is a point that we should not be using <code>entitymanager.createQuery(...)</code> inside the service layer.</p>

<p>But now with the <code>@NamedQueries</code> annotation, we can simply add named queries to the model class and maintain a set of custom criteria queries for each entity model. For example, if we had a <code>User</code> class we can have something like</p>

<pre><code>@Entity
@NamedQueries({
  @NamedQuery(name=""User.findByUsername"", query=""SELECT u FROM User u WHERE u.username_lowercase = LOWER(:username)"")
})
public class User{

@Column
private String username;

}
</code></pre>

<p>By storing the custom criteria queries inside of the model classes, we can avoid re-writing the same queries over and over again in the service layer - which makes the DAO layer seem even more unnecessary now. </p>

<p>The reasons that I have found to include the DAO layer are now:</p>

<ul>
<li>You can change the persistence mechanism in the future more easily by having a central point that maintains data access (i.e generic DAO)</li>
<li>Easier time unit testing</li>
</ul>

<p>I was wondering if anyone could contribute to this list as I am not sure if I should be using a DAO layer in my application</p>
",https://stackoverflow.com/questions/47992509/are-daos-still-needed-in-spring-mvc-with-jpa-hibernate,"['java', 'spring', 'hibernate', 'spring-mvc', 'jpa']",502,TRUE,8,1
The balance of Single responsibility/unit testability and practicality,"<p>I'm still confused about unit testing. Suppose I have something as trivial as this:</p>

<pre><code>class x {
    zzz someMethod(some input...) {
        BufferedImage image = getter.getImageFromFile(...);

        // determine resize mode:
        int width = image.getWidth();
        int height = image.getHeight();

        Scalr.Mode resizeMode = (width &gt; height) ? Scalr.Mode.FIT_TO_WIDTH : Scalr.Mode.FIT_TO_HEIGHT;

        return ScalrWrapper.resize(image, resizeMode);
    }
}
</code></pre>

<p>Going by rules, <em>Scalr.Mode resizeMode =</em> should probably be a in a separate class for better unit testability of the aforementioned method, like so: </p>

<pre><code>class xxx {
    mode getResizeMode(int width, int height)
    {
       return (width &gt; height) ? Scalr.Mode.FIT_TO_WIDTH : Scalr.Mode.FIT_TO_HEIGHT;
    }
}

class x {
   zzz someMethod(some input...) {
        BufferedImage image = getter.getImageFromFile(...);

        // determine resize mode:
        int width = image.getWidth();
        int height = image.getHeight();

        Scalr.Mode resizeMode = xxx.getResizeMode(width, height);

        return ScalrWrapper.resize(image, resizeMode);
    }
}
</code></pre>

<p>But it looks like such an overkill... I'm not sure which one is better but I guess this way is better. Suppose I go this route, would it be even better to do it this way?</p>

<pre><code>class xxx {
    mode getResizeMode(Image image)
    {
        return (image.getWidth() &gt; image.getHeight()) ? Scalr.Mode.FIT_TO_WIDTH : Scalr.Mode.FIT_TO_HEIGHT;
    }
}

class x {
   void someMethod(some input...) {
        BufferedImage image = getter.getImageFromFile(...);

        // determine resize mode:
        Scalr.Mode resizeMode = xxx.getResizeMode(image);

        return ScalrWrapper.resize(image, resizeMode);
    }
}
</code></pre>

<p>From what I understand, the correct way is the one where getResizeMode accepts integers as it is decoupled from the type of data whose properties are width and height. However, personally to me, the use of getResizeMode(BufferedImage) actually justifies the creation of a separate class better as some more work is removed from the main method. And since I am not going to be using getResizeMode for any sort of data other than BufferedImage in my application anyway, there is no problem of reusability. Also, I don't think I should be doing getResizeMode(int, int) simply for reusability if I see no need for it due to YAGNI principle.
So my question is: would getResizeMode(BufferedImage) be a good way according to OOD in <strong>real world</strong>? I understand it's text book good OOD, but then I have been lead to believe that 100% text book OOD is impracticle in real world. So as I am trying to learn OOD, I just want to know which path I should follow.
...Or maybe I should I just leave everything in one method like in the very first code snippet?</p>
",https://stackoverflow.com/questions/42736363/the-balance-of-single-responsibility-unit-testability-and-practicality,"['unit-testing', 'oop', 'solid-principles']",473,TRUE,2,3
karma chrome not loading.its giving up after two attempts,"<p>I'm integrating Jasmine and karma for unit testing my ionic app.
I'm following this <a href=""http://gonehybrid.com/how-to-write-automated-tests-for-your-ionic-app-part-2/"" rel=""nofollow noreferrer"">blog</a>.</p>

<p>When i run the karma start command i keep getting this result.</p>

<p>23 02 2017 16:39:18.508:WARN [karma]: No captured browser, open 
23 02 2017 16:39:18.517:INFO [karma]: Karma v1.5.0 server started at <a href=""http://0.0.0.0:9876/"" rel=""nofollow noreferrer"">http://0.0.0.0:9876/</a>
23 02 2017 16:39:18.517:INFO [launcher]: Launching browser Chrome with unlimited concurrency
23 02 2017 16:39:18.536:INFO [launcher]: Starting browser Chrome
23 02 2017 16:40:18.537:WARN [launcher]: Chrome have not captured in 60000 ms, killing.
23 02 2017 16:40:18.910:INFO [launcher]: Trying to start Chrome again (1/2).
23 02 2017 16:41:18.911:WARN [launcher]: Chrome have not captured in 60000 ms, killing.
23 02 2017 16:41:19.357:INFO [launcher]: Trying to start Chrome again (2/2).</p>

<p>Tried with PhantomJS also</p>

<p>Same error</p>

<p>Launching browser PhantomJS with unlimited concurrency
23 02 2017 17:44:30.214:INFO [launcher]: Starting browser PhantomJS</p>

<p>23 02 2017 17:45:30.215:WARN [launcher]: PhantomJS have not captured in 60000 ms, killing.</p>

<p>23 02 2017 17:45:30.238:INFO [launcher]: Trying to start PhantomJS again (1/2).
23 02 2017 17:46:30.239:WARN [launcher]: PhantomJS have not captured in 60000 ms, killing.</p>

<p>23 02 2017 17:46:30.246:INFO [launcher]: Trying to start PhantomJS again (2/2).</p>

<p>23 02 2017 17:47:30.247:WARN [launcher]: PhantomJS have not captured in 60000 ms, killing.</p>

<p>23 02 2017 17:47:30.254:ERROR [launcher]: PhantomJS failed 2 times (timeout). Giving up.</p>

<p>Config </p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>// Karma configuration
// Generated on Thu Feb 23 2017 10:39:27 GMT+0530 (IST)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',


    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],


    // list of files / patterns to load in the browser
    files: [
      '../www/lib/ionic/js/ionic.bundle.js',
      '../www/js/**/*.js',
      '../tests/unit-tests/**/*.js',
      '../node_modules/angular-mocks/angular-mocks.js'
    ],



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


    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },


    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],


    // web server port
    port: 9876,


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


    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,


    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,


    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
   // browsers: ['PhantomJS'],
   browsers: ['Chrome'],
    // customLaunchers: {
    //   Chrome_no_sandbox: {
    //     base: 'Chrome',
    //     flags: ['--no-sandbox']
    //   }
    // },
     plugins:[
             'karma-jasmine',
             'karma-phantomjs-launcher',
             'karma-chrome-launcher'
             ],
    




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


    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity,
    
  })
}</code></pre>
</div>
</div>
</p>

<p>Please help</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/42414089/karma-chrome-not-loading-its-giving-up-after-two-attempts,"['angularjs', 'google-chrome', 'ionic-framework', 'jasmine', 'karma-jasmine']",4877,TRUE,2,3
Create object with name to inject into unit test,"<p>I'm unit testing a class that takes a factory as one of it's dependencies and uses this to build objects that the <code>SUT</code> effectively controls:</p>

<pre><code>class SystemUnderTest
{
    private readonly IFoo foo1;

    private readonly IFoo foo2;

    public SystemUnderTest(IFooFactory fooFactory)
    {
        this.foo1 = fooFactory.Build(""Bar1"");
        this.foo2 = fooFactory.Build(""Bar2"");
    }

    public IFoo Foo1
    {
        get 
        {
            return this.foo1;
        }
    }

    ...
}
</code></pre>

<p>The <code>SystemUnderTest</code> object has a singleton lifetime that is injected into multiple <code>ViewModels</code> that use it's properties/method to perform different actions, so this effectively rules out defining a <code>Provider</code> class so that I could inject <code>foo1</code> and <code>foo2</code> without interfacing with the factory within the constructor which is what I would normally do when facing this issue.</p>

<p>But by injecting the factory I am unable to figure out with <code>AutoFixture</code> how I could correctly configure the <code>fooFactory</code> to provide the correct <code>IFoo</code> and pass this as a method parameter into my test such as:</p>

<pre><code>[Theory]
[AutoData]
internal void Foo1_IsCorrectlyPopulated_Test(
    [Frozen] IFoo foo1,
    SystemUnderTest systemUnderTest)
{
    var actual = systemUnderTest.Foo1;

    Assert.Same(foo1, actual);
}
</code></pre>

<p>I understand that I can extend the <code>AutoData</code> attribute and provide my own customization to the Fixture such as:</p>

<pre><code>class SystemUnderTestAutoDataAttribute : AutoDataAttribute
{
    public SystemUnderTestAutoData()
    {
        var fooFactory = this.Fixture.Freeze&lt;IFooFactory&gt;();
        var foo1 = this.Fixture.Create&lt;IFoo&gt;();

        Mock.Get(fooFactory).Setup(m =&gt; m.Build(""Bar1"")).Returns(foo1);
    }
}
</code></pre>

<p>But I'm wondering if there is the ability to get the <code>foo1</code> object that I created within the attribute constructor and have this passed into the test method as a parameter? I understand that I could <code>Freeze</code> the <code>foo1</code> object but this means that I would need to have two attribute classes for <code>foo1</code> and <code>foo2</code> to supply the correct information to my test method and this falls over when I have to use both objects within my test case.</p>

<p>I was hoping that there was a way that I could create the object with a particular name (or some other matching method) and match that within the test case like (does not compile):</p>

<pre><code>[Theory]
[SystemUnderTestAutoData]
internal void Foo1_IsCorrectlyPopulated_Test(
    [Frozen(Matching.CreationName)] IFoo foo1,
    SystemUnderTest systemUnderTest)
{
    ...
}

class SystemUnderTestAutoDataAttribute : AutoDataAttribute
{
    public SystemUnderTestAutoData()
    {
        var fooFactory = this.Fixture.Freeze&lt;IFooFactory&gt;();
        var foo1 = this.Fixture.Create&lt;IFoo&gt;(creationName: @""foo1"");

        Mock.Get(fooFactory).Setup(m =&gt; m.Build(""Bar1"")).Returns(foo1);
    }
}
</code></pre>

<p>So that any matching registered instances with the name (or some other matching method) can be resolved as part of the test case parameters?</p>
",https://stackoverflow.com/questions/43210178/create-object-with-name-to-inject-into-unit-test,"['c#', 'unit-testing', 'dependency-injection', 'autofixture']",1941,TRUE,2,1
Use ASP.NET MVC Unity for Data Caching,"<p>I have a ASP.Net MVC project running on .NET 4.6.1 Framework.
I have recently added <a href=""https://github.com/devtrends/Unity.Mvc5"" rel=""nofollow noreferrer"">Unity.Mvc 5 IoC</a> framework for dependency injection</p>

<p>In order to have flexibility for unit testing and other, I moved my Unity Configuration to a separate class library so that I can call the Unity Register methods from Unit test projects and other as needed.</p>

<p>Here is my <a href=""https://i.stack.imgur.com/uKdnR.png"" rel=""nofollow noreferrer"">high-level solution design</a>.</p>

<p><strong>I would like to use the same class library to implement application cache.</strong></p>

<p>When I installed <a href=""https://www.nuget.org/packages/Unity.Mvc5/"" rel=""nofollow noreferrer"">Unity.Mvc5</a> from nuget package it added following references (I added some of them manually) :</p>

<ul>
<li>Microsoft.Practices.EnterpriseLibrary.Caching 5.0.505.0 </li>
<li>Enterprise Library Shared Library 5.0.505.0 </li>
<li>Microsoft.Practices.ServiceLocation 1.3.0.0 </li>
<li>Microsoft.Practices.Unity 4.0.0.0 </li>
<li>Microsoft.Practices.Unity.Configuration 4.0.0.0</li>
<li>Microsoft.Practices.Unity.Interception 2.1.505.0</li>
<li>Microsoft.Practices.Unity.Interception.Configuration 2.1.505.0</li>
<li>Microsoft.Practices.Unity.RegistrationByConvention 4.0.0.0</li>
</ul>

<p>I tried few articles <em>to implement Application Block Cache Management</em> so that I can cache data in my Service Implementer layers, but all those documentations are showing code examples which is expecting Unity 2.xxx version.</p>

<p>Here is my Unity Configuration</p>

<pre><code> public static class UnityConfig
    {
        public static void RegisterComponents()
        {
            var container = new UnityContainer();
            container.RegisterType&lt;UserManager&lt;User&gt;&gt;(new HierarchicalLifetimeManager());
            container.RegisterType&lt;IUserStore&lt;User&gt;, UserStore&lt;User&gt;&gt;(new HierarchicalLifetimeManager());
            container.RegisterType&lt;DbContext, OfficeGxDbContext&gt;(new HierarchicalLifetimeManager());
            container.RegisterType&lt;IAppSetting, AppSettingService&gt;();
            container.RegisterType&lt;ISubscription, SubscriptionService&gt;();
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        }
    }
</code></pre>

<p>In my <code>AppSettingService.cs</code> I have get all method</p>

<pre><code>public List&lt;AppSetting&gt; All()
        {
            using (var context = new MyDbContext())
            {
                //CachecKeyItem.AppSettingsAll
                return context.AppSettings.Where(x =&gt; !x.IsDeleted)
                    .Include(x =&gt; x.Module).ToList();
            }
        }
</code></pre>

<p><strong>I want to store this data in cache and reuse it</strong>. Similarly do this across all projects I have in my solution and if there is any <code>update</code> or <code>add</code> or <code>delete</code> for any <code>DB records</code>, I want the <code>cached object to refresh it</code> so that cached object is always in sync with DB data</p>

<p>I ended up doing something like this</p>

<pre><code>public interface ICacheService
    {
        T GetOrSet&lt;T&gt;(string cacheKey, Func&lt;T&gt; getItemCallback) where T : class;
    }
</code></pre>

<p>Service Implementor</p>

<pre><code> public class InMemoryCache : ICacheService
    {
        public T GetOrSet&lt;T&gt;(string cacheKey, Func&lt;T&gt; getItemCallback) where T : class
        {
            if (MemoryCache.Default.Get(cacheKey) is T item) return item;
            item = getItemCallback();
            MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(8));
            return item;
        }
    }
</code></pre>

<p>use like this</p>

<pre><code>_cacheService.GetOrSet(CachecKeyItem.AppSettingsAll, () =&gt; context.AppSettings
                    .Where(x =&gt; !x.IsDeleted)
                    .Include(x =&gt; x.Module).ToList());
</code></pre>

<p>Now my question is, when there is any change to data, like add/edit/delete, how do I refresh the cache in most efficient way? I know deleting the key would be one, is there a better way?</p>
",https://stackoverflow.com/questions/47011716/use-asp-net-mvc-unity-for-data-caching,"['asp.net-mvc', 'caching', 'enterprise-library', 'caching-application-block', 'unity-application-block']",817,FALSE,1,1
Using Angular2 TestBed to Mock a service with a non-concrete class interface parameter,"<p>I have a component that I am trying to setup and test using TestBed.</p>

<p>This component contains one class that has a parameter in the constructor that is an interface, not a concrete class. This interface is satisfied by whatever class I choose to use (either the real one, or a mok one for unit testing). But when I am constructing the component that uses this service in TestBed, I cannot figure out how to define that parameter to the TestBed configuration.</p>

<p>Here is the TestBed config for the component:</p>

<pre><code>describe('PanelContentAreaComponent', () =&gt; {
  let component: PanelContentAreaComponent;
  let fixture: ComponentFixture&lt;PanelContentAreaComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ PanelContentAreaComponent
          ],
      providers:[
        MenuCommandService, ProcedureDataService, IOpenService],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
    .compileComponents();
  }));
</code></pre>

<p>The service which is having trouble being constructed in TestBed is ProcedureDataService . It's definition is below:</p>

<pre><code>@Injectable()
export class ProcedureDataService {

serverOpenFile: OpenFile;

constructor(private _openService: IOpenService) {
    this.serverOpenFile = emptyFileStatus;
}
</code></pre>

<p>The one parameter in the constructor of the <code>ProcedureDataService</code> is <code>IOpenService</code> whose definition is :</p>

<pre><code>export interface IOpenService {
    openFile(fileType: string, dataType: string, filePath: string) ;
}
</code></pre>

<p>As you can see this is an interface, not a concrete class.</p>

<p>In my service unit test, we mock the IOpenService by implementing it as follows:</p>

<pre><code>export class mockOpenService implements IOpenService{

    constructor(){}

    openFile(fileType: string, dataType: string, filePath: string) {
        let fileContent: OpenFile;
... 
...
[fake the data with mok junk]
...
        fileContent = {
            'filePath': filePath,
            'fileName': name,
            'openSuccess': isSuccess,
            'error': errorMsg,
            'fileData': jsonData
        };

        return Observable.of(fileContent);

    }

}
</code></pre>

<p>This works great in the ProcedureDataService service unit test. And, of course, in the real code, we implement the IOpenService with the full implemented file open service that gets the data properly.</p>

<p>But in trying to use this service inside of a component I get the following error:</p>

<pre><code>PanelContentAreaComponent should create FAILED
        Failed: IOpenService is not defined
        ReferenceError: IOpenService is not defined
</code></pre>

<p>This makes sense, so then I am trying to figure out how to tell TestBed that I have a concrete class implementation of this IOpenService which I wish to use. I tried this, but it fails:</p>

<pre><code>describe('PanelContentAreaComponent', () =&gt; {
  let component: PanelContentAreaComponent;
  let fixture: ComponentFixture&lt;PanelContentAreaComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ PanelContentAreaComponent
          ],
      providers:[
        {provide: IOpenService, useClass: mockOpenService},
        MenuCommandService, ProcedureDataService, IOpenService],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
    .compileComponents();
  }));
</code></pre>

<p>The compiler is telling me:</p>

<pre><code>(31,19): error TS2693: 'IOpenService' only refers to a type, but is being used as a value here.
</code></pre>

<p>and I am still getting :</p>

<pre><code>PanelContentAreaComponent should create FAILED
        Failed: IOpenService is not defined
        ReferenceError: IOpenService is not defined
</code></pre>

<p>So how do I instruct <code>TestBed</code> that I have a specific class (<code>mockOpenService</code>) implementation of an interface parameter (<code>IOpenService</code>) needed for the service (<code>ProcedureDataService</code>) being provided to test this component (<code>PanelContentAreaComponent</code>)?</p>
",https://stackoverflow.com/questions/42492017/using-angular2-testbed-to-mock-a-service-with-a-non-concrete-class-interface-par,"['javascript', 'angular', 'testbed']",4124,TRUE,6,1
Unit tests (PHPUnit): create separate project just for testing?,"<p>I'm writing some unit tests (PHPUnit) for a project that will be used by another project. The project that I am testing has a class that will include files that will be present only in the other project. </p>

<p>Now how do I write a unit test for this class without having the files that it needs to include available? Would you recommend setting up a complete testing project with stub files (the file in question is a file that contains some settings) and running all the unit tests there? Or should I create directories and files using for example the <code>setUp()</code> method?</p>

<p><em>Edit:</em> </p>

<p><strong>To be more specific</strong>, I have a base project A, which is a website. I have a project B, which contains a class that generates a form. The form class will be installed in project A using Composer. The form class will in project A check for the existence of a dir with a settings file. If it exists, it will include it and load the settings in it. To test the form class, do you think I should create a project C (just for testing) which installs project B and in which I set up the directory with the settings file for testing? Or do you think it's a better way to go to create the directory with the settings file in project B itself? The latter seems a bit odd to me, as I don't want to have all this unit testing material available in project A when I composer-install project B in it.</p>
",https://stackoverflow.com/questions/44307435/unit-tests-phpunit-create-separate-project-just-for-testing,"['php', 'unit-testing', 'phpunit']",297,TRUE,0,2
How to unit test complex logic in RxJava operators?,"<p>I am struggling with how to test complex logic in RxJava streams that have many operators. I'm finding that if I have complex logic and many operators with complex logic strung together that unit testing the stream becomes a nightmare because there are so many combinations of cases to cover.</p>

<p>Here is an example of what I'm describing:</p>

<pre><code>        Observable&lt;ObjectA&gt; observable = myRepository
            .fetchA()
            .flatMap(new Func1&lt;ObjectA, Observable&lt;ObjectA&gt;&gt;() {
                @Override
                public Observable&lt;ObjectA&gt; call(final ObjectA object) {
                    if (object.isAvailable()) {
                        //do something
                        return myRepository
                                .fetchAnotherThing();
                    } else {
                        //do something else
                        return myRepositor
                                .fetchADifferentThing();
                    }
                }
            })
            .flatMap(new Func1&lt;ObjectA, Observable&lt;ObjectA&gt;&gt;() {
                @Override
                public Observable&lt;ObjectA&gt; call(final ObjectA object) {
                    if (object.isFull()) {
                        //do something
                        return myRepository
                                .doThingA();
                    } else {
                        //do something else
                        return myRepository
                                .doThingB();
                    }
                }
            });
</code></pre>

<p>If I want to write a unit test for this I would need to write at least 4 test methods so that I could cover all combinations of the conditional logic.</p>

<p>Usually when something like this happens I'd write a custom class to handle the logic and then unit test that class. So the above code might turn into something like this:</p>

<pre><code>public class MyFunc implements Func1&lt;ObjectA, Observable&lt;ObjectA&gt;&gt; {
    @Override
    public Observable&lt;ObjectA&gt; call(final ObjectA object) {
        //The logic that was formerly in an anonymous Func1 is now here
        if (object.isAvailable()) {
            //do something
            return myRepository.fetchAnotherThing();
        } else {
            //do something else
            return myRepository.fetchADifferentThing();
        }
    }
}

public class MyOtherFunc implements Func1&lt;ObjectA, Observable&lt;ObjectA&gt;&gt; {
    @Override
    public Observable&lt;ObjectA&gt; call(final ObjectA object) {
        //The logic that was formerly in an anonymous Func1 is now here
        if (object.isFull()) {
            //do something
            return myRepository.doThingA();
        } else {
            //do something else
            return myRepository.doThingB();
        }
    }
}
</code></pre>

<p>Now MyFunc and MyOtherFunc are now unit testable by themselves and I can verify that the logic is correct in isolation. Then my original code could be transformed into something like this:</p>

<pre><code>Observable&lt;ObjectA&gt; observable = myRepository
            .fetchA()
            .flatMap(myFunc)
            .flatMap(myOtherFunc);
</code></pre>

<p>That certainly looks more concise and alleviates the need for my unit test of the chain to handle many cases as it did before, but now the question is how do I test what's left?</p>

<p>If I mock the output of myFunc and myOtherFunc then it seem like I'm not really testing anything at all. Another option would be to use real implementations of myFunc and myOtherFunc but now I'm not doing a unit test anymore I'm doing an integration test and that comes with extra hassles.</p>

<p>Has anyone else struggled with this before and if so how did you solve your problems of testability?</p>
",https://stackoverflow.com/questions/45466448/how-to-unit-test-complex-logic-in-rxjava-operators,"['android', 'unit-testing', 'rx-java', 'rx-android']",339,FALSE,0,1
What is required on a build agent for doing more than simply building the project?,"<p>Successfully building an MVC project using a basic build agent, meaning an agent created using only the TFS 'Agent Pools' download and setup process.</p>

<p>From reading many SO posts and observation while trying to add Tasks to my Build Definition I have come to understand that a 'basic' Build Agent can build a project but seemingly do little else.  For example, I understand that to run unit tests on the Build Agent, Visual Studio will need to be installed.  But I had (naively) assumed at least MSBuild was installed on the Build Agent; it seems not.</p>

<p><strong>Question 1</strong>: Please confirm if MSBuild must be installed in order to add additional MSBuild tasks to my Build Definitions?  Can I install just MSBuild?
<strong>Question 1a</strong>: If MSBuild is not on the basic Build Agent, what is the Build Agent using to build projects?</p>

<p><strong>Question 2</strong>: If I want to do unit tests on the Build Agent, will the free VS version (Community 2017) be sufficient, or do I need to install the full version of VS? (I am running full VS/TFS onsite versions)  Some other forums suggested in prior year versions the free VS version (I believe called Express) was sufficient for unit testing on Build Agents.</p>

<p><strong>Question 3</strong>: Are these the only 2 'levels' of added packages I would ever need on a Build Agent, MSBuild or VS?  And if I only installed MSBuild at first, would I run into problems adding VS to the Build Agent later because it will install MSBuild over the previous MSBuild install? </p>
",https://stackoverflow.com/questions/46818495/what-is-required-on-a-build-agent-for-doing-more-than-simply-building-the-projec,"['msbuild', 'visual-studio-2017', 'build-agent']",155,TRUE,0,1
Testing - How this common scenario is classified and handled,"<p>I’m just diving into testing/test driven development in php, and am a bit confused about how to handle a very typical scenario in our legacy codebase. Our codebase does not have many classes, it’s very functional programming oriented.</p>

<p>In this example code, which is pseudocode, I want to write a test for getAndOrderUsersByAge(). As you can see it first gets all the users from our database (in a giant array lets say, because we don’t have objects/classes) then sorts them. This is of course a VERY common occurrence in our code, manipulating or analyzing data gotten from the database; not objects, but an array of database rows basically.</p>

<p>Note that I've added an error in the if statement to simulate an error I want my tests to catch.</p>

<pre><code>//gets all users in our db into an array, then sorts them by age
function getAndOrderUsersByAge(){
     //get all users from the db
     $all_users = getAllUsers();

     //sort
     $all_users_sorted = sortUsers($all_users)

     //notice I've made a mistake here on purpose, left the ""d"" off of ""$all_users_sorted""
     //so the function will always return false, a mistake...which I want tests to catch
     if(!empty($all_users_sorte){
         return $all_users_sorted;
     }
     else{
         return false;
     }
}
</code></pre>

<p>My questions are:</p>

<p>1.) Is testing the function getAndOrderUsersByAge() unit testing, integration testing, or …?</p>

<p>2.) In my (unit?) test(s) of getAndOrderUsersByAge(), I want to assume that getAllUsers (the function which gets things from the db) behaves correctly because I only want to test getAndOrderUsersByAge() right? I’m not really sure what “concept” this falls under when I’m reading the two books I have on testing. Is this where I would “mock”, e.g. create some fake data for getAllUsers() to return?</p>

<p>3.) What tests would you write for getAndOrderUsersByAge()? I think I would write one that ensures a non-empty array is returned when getAllUsers() returns a non-empty array, as this would catch the error I've created. I'm not sure what else though.</p>

<p>Any tips, recommended reading material, etc. is very welcomed.</p>
",https://stackoverflow.com/questions/47541884/testing-how-this-common-scenario-is-classified-and-handled,"['php', 'unit-testing', 'testing', 'integration-testing']",30,TRUE,0,1
Bamboo build plan fails with MS Test project,"<p>I have a  .NET 4.6.1 solution that has a Class Library and a Unit Test project. I setup my build plan in Bamboo to do a Continuous Integration build. The build task fails with the below error.</p>

<blockquote>
  <p>The type 'System.Attribute' is defined in an assembly that is not
  referenced. You must add a reference to assembly 'System.Runtime,
  Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.</p>
</blockquote>

<p>I tried building this locally using Visual Studio and it builds just fine. I also tried building using MS Build on my developer laptop from the command line and it builds without any errors.</p>

<p>I removed the Unit Testing project from my solution and I got a successful build.</p>

<p>There is also a warning in one of the previous steps about .NET Framework 4.6.1. I believe this has nothing to do with the previous error, but I wanted to put everything out there just in case.</p>

<blockquote>
  <p>C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(983,5):
  warning MSB3644: The reference assemblies for framework
  "".NETFramework,Version=v4.6.1"" were not found. To resolve this,
  install the SDK or Targeting Pack for this framework version or
  retarget your application to a version of the framework for which you
  have the SDK or Targeting Pack installed. Note that assemblies will be
  resolved from the Global Assembly Cache (GAC) and will be used in
  place of reference assemblies. Therefore your assembly may not be
  correctly targeted for the framework you intend.
  [D:\data\bamboo-agent-home\xml-data\build-dir\AIS-CTB-JOB1\Emc.Cryptography\Emc.Cryptography.csproj]</p>
</blockquote>
",https://stackoverflow.com/questions/47269103/bamboo-build-plan-fails-with-ms-test-project,"['bitbucket', 'bamboo']",186,FALSE,0,0
How to unit test a controller that creates a new public key and private key everytime its called?,"<p>My boss wants me to unit test this License controller for our ASP.NET application. </p>

<p>The problem im having is that normally
you go to the application create a license that license is tied to the current instance of a keygenerator and keypair (from portable=license library ) i have a static class called LicenseService that creates a keygenerator and keypair when called. So you generate a license and then go to the verification page, which is on the same instance of the keygenerator and keypair. So the verify will go through, if the license was created on another instance it won't verify (different public/private key) what would be a possible work around for this? </p>

<p>because Im unit testing a valid license and invalid license so i need to have created a license beforehand but each license is tied to a unique instance, so passing a license created with a different key pair to another instance (with its own keypair) will be invalid (even if the license itself is invalid).</p>

<p>here are some ideas i have </p>

<ol>
<li><p>hard code the keys (im testing locally so it shouldnt be too much of an issue) but i feel there is a security flaw with this</p></li>
<li><p>somehow force the controller and all subsequent instances of the controller to use one specific instance of the generator while having multiple key pairs (this seems very hard and im unsure as to how to approach it)</p></li>
</ol>

<p>this is the library btw</p>

<p><a href=""http://dev.nauck-it.de/projects/portable-licensing/wiki/GettingStarted"" rel=""nofollow noreferrer"">http://dev.nauck-it.de/projects/portable-licensing/wiki/GettingStarted</a></p>
",https://stackoverflow.com/questions/42865452/how-to-unit-test-a-controller-that-creates-a-new-public-key-and-private-key-ever,"['c#', 'asp.net', 'unit-testing', 'licensing']",981,FALSE,0,1
How to Integrate multiple unit test reports with SonarQube,"<p>I have couple of Maven projects in my build. Each project has its unit test cases. I would like to execute those test cases &amp; report the consolidated results on SonarQube Server. I am on SonarQube 5.6.</p>

<p>As there are multiple Cobertura reports to combine, I could not find a better way other than go with <a href=""https://docs.sonarqube.org/display/PLUG/Generic+Test+Coverage"" rel=""nofollow noreferrer"">https://docs.sonarqube.org/display/PLUG/Generic+Test+Coverage</a></p>

<p>I used <a href=""https://github.com/QualInsight/qualinsight-mojo-cobertura"" rel=""nofollow noreferrer"">https://github.com/QualInsight/qualinsight-mojo-cobertura</a> to generate report in generic format. </p>

<p>At sonar level, I do not have multiple modules defined.</p>

<p><strong>Questions</strong></p>

<ol>
<li><p>In my build there are couple of other projects developed using C#, JS/html. I want to see the consolidated report from all the projects (irrespective of language) integrated on SonarServer. Is using Generic Test Coverage the right  approach?</p></li>
<li><p>When I run the build then I can see the coverage.xml &amp; converted-coverage.xml files generated. I set the path sonar.genericcoverage.reportPaths &amp; sonar.genericcoverage.unitTestReportPaths as well. but nothing is coming up for unit testing on Sonar portal. I checked the logs &amp; get following </p></li>
</ol>

<blockquote>
  <p>INFO: Sensor GenericCoverageSensor
      INFO: Parsing Mycode\target\cobertura\ut\converted-coverage.xml
      INFO: Imported coverage data for 0 files
      INFO: coverage data ignored for 33 unknown files, including:
      src/main/java/com/app/AppInfoService.java
      src/main/java/com/app/Service.java
      src/main/java/com/app/F1Service.java
      src/main/java/com/app/JobService.java
      src/main/java/com/app/L1.java
      INFO: Imported IT coverage data for 0 files
      INFO: Imported Overall coverage data for 0 files
      INFO: Imported unit test data for 0 files
  What is missing here, Why sonar not able to parse the generic code coverage report.</p>
</blockquote>

<p>Any help is much appreciated.</p>

<p>Atul</p>
",https://stackoverflow.com/questions/43728413/how-to-integrate-multiple-unit-test-reports-with-sonarqube,"['sonarqube', 'sonar-runner', 'cobertura', 'sonarqube-scan', 'maven-cobertura-plugin']",972,FALSE,4,0
"Integration tests, but how much?","<p>A recent debate within my team made me wonder. The basic topic is that how much and what shall we cover with functional/integration tests (sure, they are not the same but the example is dummy where it doesn't matter).</p>

<p>Let's say you have a ""controller"" class something like:</p>

<pre><code>public class SomeController {
    @Autowired Validator val;
    @Autowired DataAccess da;
    @Autowired SomeTransformer tr;
    @Autowired Calculator calc;

    public boolean doCheck(Input input) {
        if (val.validate(input)) {
             return false;
        }

        List&lt;Stuff&gt; stuffs = da.loadStuffs(input);
        if (stuffs.isEmpty()) {
             return false;
        }

        BusinessStuff businessStuff = tr.transform(stuffs);
        if (null == businessStuff) {
            return false;
        }

       return calc.check(businessStuff);
    }
}
</code></pre>

<p>We need a lot of unit testing for sure (e.g., if validation fails, or no data in DB, ...), that's out of question.</p>

<p>Our main issue and on what we cannot agree is that how much integration tests shall cover it :-)</p>

<p>I'm on the side that we shall aim for less integration tests (test pyramid). What I would cover from this is only a single happy-unhappy path where the execution returns from the last line, just to see if I put these stuff together it won't blow up.</p>

<p>The problem is that it is not that easy to tell why did the test result in false, and that makes some of the guys feeling uneasy about it (e.g., if we simply check only the return value, it is hidden that the test is green because someone changed the validation and it returns false). Sure, yeah, we can cover all cases but that would be a heavy overkill imho.</p>

<p>Does anyone has a good rule of thumb for this kind of issues? Or a recommendation? Reading? Talk? Blog post? Anything on the topic?</p>

<p>Thanks a lot in advance!</p>

<p>PS: Sry for the ugly example but it's quite hard to translate a specific code part to an example. Yeah, one can argue about throwing exceptions/using a different return type/etc. but our hand is more or less bound because of external dependencies.</p>
",https://stackoverflow.com/questions/42489707/integration-tests-but-how-much,"['java', 'unit-testing', 'testing', 'automated-tests', 'integration-testing']",1849,TRUE,8,2
Nunit testing with Mock. Instance of Interface,"<p>I have the following (simplified) code.</p>

<pre><code>public class Controller
{
     private readonly IService _service;

     public Controller(IService service)
     {
         _service = service;
     }

     public async Task&lt;IHttpActionResult&gt; Create(MyObject object)
     {
         var result = _service.method(object);
         if (!result.Succeeded)
         {
            return this.GetErrorResult(object);
         }
     }
}
</code></pre>

<p>and SimpleInjector is used to inject the dependency between _service and its implementation class, like this:</p>

<pre><code>public static void Register(Container container)
{
    container.Register&lt;IService, Service&gt;();
}
</code></pre>

<p>As a note, injection and unit testing are new to me so I do not fully understand them, but am learning.</p>

<p>If I run the application through Swagger, all is working fine. </p>

<p>As a note, the <code>Register</code> function is called when I run the application through Swagger.</p>

<p>Now, I am trying to setup some unit tests using NUnit, and am Mocking the IService object like this:</p>

<pre><code>var Service = new Mock&lt;IService&gt;();
Controller _controller = new Controller(Service.Object);
_controller.Create(new MyObject object());
</code></pre>

<p>which seems to be correct to me so far - although I am not sure?</p>

<p>The problem is that for the unit test, <code>result</code> is always null - I think the is because there is a problem with my Mock of the interface - it does not seem to be finding the method - it never steps into it and does not show up int he debugger.</p>

<p>As a note, for the unit test, the <code>Register</code> method does not get called. I did try calling it to register the dependency, but it does not help.</p>

<p>As I said above, this is all new to me and I am on the edge of my understanding on all of this.</p>

<p>I am out of ideas and do not know where to look from here, so any help would be greatly appreciated.</p>

<p>EDIT:</p>

<p>The original question had the following:</p>

<pre><code>public async Task&lt;IHttpActionResult&gt; Create(string content)
</code></pre>

<p>which I have updated to:</p>

<pre><code>public async Task&lt;IHttpActionResult&gt; Create(MyObject object)
</code></pre>

<p>Can anyone advise how I can pass in a generic reference to <code>MyObject</code> on the setup, without having to make an instance of this class.</p>

<p>So basically I want to tell it that an instance of this class will be passed in, without creating that instance.</p>

<p>I have tried the following:</p>

<pre><code>Service.Setup(x =&gt; x.method(It.IsAny&lt;MyObject&gt;())

but it says cannot convert MethodGroup to MyObject
</code></pre>

<p>and here is the definition of IService:</p>

<pre><code>public interface IService
{
      IdentityResult method(ApplicationUser user, UserLoginInfo login);
}
</code></pre>
",https://stackoverflow.com/questions/41611795/nunit-testing-with-mock-instance-of-interface,"['c#', 'mocking', 'nunit', 'moq', 'simple-injector']",42610,TRUE,7,3
How to mock an EF6 context and/or the underlying database when the values to be tested reside in the database?,"<p>I'm trying to add unit testing to my projects that use EF6. The TDD approach works fine for simple methods that taken an input and return some output, but I'm not clear on how to make it work for methods that do read/write operations on the database. More specifically, I'm not entirely sure about how to create an in-memory representation of the database (for the test data) and then ""mock"" the context to point to that in-memory representation. </p>

<p>As an example, please consider the below class (not representative of the actual production code but demonstrates the problem) that reads a file line by line, references a bunch of tables to do some validation and then stores results to two separate database tables -</p>

<pre><code>class Importer { 
    private repository;
    private bool IsValid(string line) {
        //Refer to a bunch of database tables and return true or false. Below is just a random code that demonstrates this
        if(repository.Context.SomeTable1.Count(t =&gt; t.Prop1 == line[2]) &gt; 0 &amp;&amp;
            repository.Context.SomeTable2.First(t =&gt; t.Prop2 == line[3]).Prop3 != null &amp;&amp;
            ... 
            repository.Context.SomeTable10.Last(t =&gt; t.Prop5 == line[5]).Prop9 != null)
            return true;
        return false;
    }
    public Importer(IRepository repository) { this.repository = repository; }
    public void Process(string fileName) {
        ImportLog log = new ImportLog();
        foreach(var line in GetNextLine(fileName) { //GetNextLine reads the file and yield returns lines
            if(IsValid(line)) { //IsValid refers to a bunch of tables and returns true/false
                log.Imported++;
                FileTable fileTable = new fileTable();
                fileTable.Line = line;
                repository.Context.FileTables.Add(fileTable);
                repository.Context.Entry(fileTable).State = EntityState.Added;
                repository.Context.SaveChanges(); //Must save here, can't buffer because the file and lines are too large
            }
            else { log.Rejected++; }
        }
        repository.Context.ImportLogs.Add(log);
        repository.Context.Entry(log).State = EntityState.Added;
        repository.Context.SaveChanges();
    }
}
</code></pre>

<p>Now, the only real test that verifies that the class is working is to run the <code>Process</code> method and then check the database to ensure that <code>ImportLog</code> and <code>FileTable</code> tables contain correct values for the given file.</p>

<p>This brings us to my question - How do I create an in-memory representation of the database (that contains <code>ImportLog</code>, <code>FileTable</code>, <code>SomeTable1 to 10</code> tables and then point the repository.Context to that in-memory representation? Or am I going about it in a completely wrong manner?</p>

<p>Note: I suppose I could create mock CRUDs in the repository instead of just using the DBContext but that would be a momentous effort because the database has close to 100 tables. Just pointing the DBContext to a mocked database solves the problem most efficiently. Alternatively, I could create a real test database but I'm keeping that option only for if an in-memory database solution is not possible. </p>
",https://stackoverflow.com/questions/42007438/how-to-mock-an-ef6-context-and-or-the-underlying-database-when-the-values-to-be,"['c#', 'unit-testing', 'entity-framework-6']",949,TRUE,1,2
Refactoring implementation of multiple classes having common code (With DI),"<p>I have multiple subsystems inside 1 big system. So every subsystem has it's own BAL and DAL implementation. Now the BAL(s) have significant logic but the DAL basically had similar code so I refactored it into one generic DAL class which is now used across all the subsystems. Something like this:</p>

<p>Let's assume subsystem names as A and B</p>

<pre><code>public class DalA
{
    private IGenericDal genericDal;

    public DalA( IGenericDal injectedGenericDal)
    {
        this.genericDal = injectedGenericDal;
    }

    public bool DoSomeDBWorkForA()
    {
        return genericDal.CommonDalMethod();
    }
}


public class DalB
{
    private IGenericDal genericDal;

    public DalB(IGenericDal injectedGenericDal)
    {
        this.genericDal = injectedGenericDal;
    }

    public bool DoSomeDBWorkForB()
    {
       return genericDal.CommonDalMethod();
    }
}
</code></pre>

<p>Now the DI part of injecting generic DAL is important from unit testing point of view, so the BAL(s) have to inject the generic DAL object. So now the BAL is unnecessarily being aware of generic DAL object just because of the refactoring and DI requirements, which ideally it should not be (specially in case of refactoring).</p>

<p>Also one of my friends pointed out that the DAL(s) of subsystem A and B are doing nothing so we should probably get rid of them and call generic DAL itself, but in my opinion it reduces flexibility as tomorrow DAL of A might want to do some logging or some other special action which B or even C might not subscribe to. </p>

<p>So what do you guys think? Does anybody have a better refactored implementation where the DI, the separation of concerns (i.e. BAL of A is only aware of DAL of A and not generic DAL object) and flexibility (having different DAL(s) for all the subsystems) are intact.</p>

<p>One of the ways that I thought of was to have 2 constructors in DAL of A and B, so that from BAL we can call without injecting generic DAL and from Unit Test I can inject Generic DAL object.</p>
",https://stackoverflow.com/questions/41437922/refactoring-implementation-of-multiple-classes-having-common-code-with-di,"['c#', 'oop', 'dependency-injection']",148,TRUE,1,1
Web forms to Razor view migration of enterprise application,"<p>I am a developer on a large scale enterprise web application that is utilizing a rapidly aging architecture so we have been discussing how best to approach modernizing the app. Specifically it is an ASP.Net 4.0 web forms application with MVC kind of stapled on top but it's still using all ascx views. Additionally we are using a database framework called Entity Spaces which has basically gone by the wayside in favor of Entity Framework. We are getting ready to migrate the application up to .net 4.6 so we are at least running a modern version but we have aspirations to one day be able to do extensive unit testing and test automation on the app which is currently not really possible because of the architecture.</p>

<p>My question then is does anyone have any good information or resources on how best to approach this problem? For example say we have an ASP.Net 4.6 web app with 10 areas under it. Would it be possible to pull an area out into it's own project and refactor it to use Razor Views and Entity Framework but still run in the same domain alongside the rest of the areas that have not yet been overhauled? Taking and refactoring the whole application in one go will never sell to upper management but if we can do it one module (area) at a time it's probably feasible. Any information about technical possibilities or problems we might face would be really helpful. I can't imagine other large enterprise applications haven't faced a similar issue, but I have found very little information on how to approach this.</p>
",https://stackoverflow.com/questions/47800276/web-forms-to-razor-view-migration-of-enterprise-application,"['c#', 'asp.net', 'asp.net-mvc', 'web-applications']",407,TRUE,1,1
When would I actually be required to unit test private methods?,"<p>I'm writing unit tests for the implementation of an API I wrote myself in my company's application. Still new to this whole thing. When looking for answeres on how to unit test certain things I come across a certain pattern. It goes something like this:</p>

<p>Question:</p>

<blockquote>
  <p>I have this private method I need to unit test.</p>
</blockquote>

<p>Top voted answer:</p>

<blockquote>
  <p>Don't.</p>
</blockquote>

<p>I also came across <a href=""http://www.peterprovost.org/blog/2012/05/31/my-take-on-unit-testing-private-methods/"" rel=""nofollow noreferrer"">this article</a> arguing against unit testing private methods as well.</p>

<p>Basically how I'm implementing an API I'm given is I write the code first, then I write unit tests to ""break it the worst way possible"" (as my superior puts it). Once I notice something broke I fix it in the code. To me this seems like a mash-up of OOD and TDD. Is that a legit approach?</p>

<p>The reason I got so many <code>private</code> methods in the first place is that I'm required to break up larger chunks of code into methods. Since these methods are only supposed to be used within the scope of this API implementation I set them to <code>private</code>. Since the file structure established by my team requires me to write all the code into a single file corresponding to an API I can't separate these <code>private</code> methods into a new class and set them to <code>public</code>.</p>

<p>My superior expects me to test these <code>private</code> methods as well. But I'm beginning to doubt if this is even really necessary if the <code>Assert</code>s on the <code>public</code> methods all run successfully? </p>

<p>From my point of view, if my tests on the <code>public</code> methods return the values I expected, I infer that my <code>private</code> methods also work like I intended. </p>

<p>Or am I missing something?</p>
",https://stackoverflow.com/questions/41872901/when-would-i-actually-be-required-to-unit-test-private-methods,"['c#', 'unit-testing', 'tdd']",283,TRUE,1,2
Mapping resources to classes in C#/WPF,"<p>I have a bunch of <code>Shape</code>-classes (classic) like <code>Rectangle</code> and <code>Circle</code> in my first module.</p>

<p>In my second module, I have a GUI, made with WPF. I want to show a <code>ListBox</code> of all <code>Shape</code>-classes. The <code>ListBox</code> shall contain the localizable name of the shape, which is saved as a resource string, and an icon, saved as a resource image.</p>

<p>I want my whole code to be as modular as possible, e.g. if I add a new <code>Shape</code>-class, I want to change as few classes as possible.</p>

<p>My first approach would be to make a helper class in my GUI-module, which for each shape holds the <code>Shape</code>'s <code>Type</code>, its name as <code>string</code>, and its icon as a <code>Bitmap</code> (or similar). I would then initialize the list at one place, e.g.</p>

<pre><code>var shapeList = new List&lt;ShapeHelperClass&gt;
{
  new ShapeHelperClass(typeof(Rectangle), Resources.StringRectangle, Resources.IconRectangle),
  new ShapeHelperClass(typeof(Circle), Resources.StringCircle, Resources.IconCircle),
};
</code></pre>

<p>and bind this list to the <code>ListBox</code>. Now, if I rename my classes or my resources, nothing will break, and localization should work properly. But, of course, if adding a new <code>Shape</code>-class in the first module, I also need to update this list.</p>

<p>Another approach would be to use reflection to find all my <code>Shape</code> classes, and build the list out of that. However, I would still need some Dictionaries or something similar to map the classes to the Resources. I could find the resources if they follow a pattern, like ""Icon"" + ""Classname"". However, if no icon is found, this is only noticed at runtime.</p>

<p>So, my questions are:</p>

<ol>
<li>Is my first approach a good one, our could it be improved?</li>
<li>How can I make sure that a programmer who adds a new <code>Shape</code> also adds the new Resources and extends the mapping-list? Maybe by Unit-testing?</li>
</ol>
",https://stackoverflow.com/questions/43091537/mapping-resources-to-classes-in-c-wpf,"['c#', 'wpf', 'internationalization']",187,TRUE,0,1
Python Testing a CLI application with required arguments,"<p>First off: I am quite new to the field of testing. So there might be some things wrong in my understanding.</p>

<p>My situation is the following: I'm working on a framework-ish where the end-user has to inherit from a parent class I've predefined. They're required to override four abstract methods I've defined in the parent class, and write there magic code inside of these methods.</p>

<p>The framework offers three different modes to run in. Because I want to ensure no mistakes are being made I've added a positional CLI argument to set that mode. </p>

<p>Here is my problem: I'm trying to write a unittest for every module in my application. Because the parent class mentioned above has quite some code, I'd like to unittest this as well.</p>

<p>Needless to say, it will not run without providing the required positional argument.</p>

<p>I've looked around to see how I can provide this argument programmatically, but the internet tells me that a unittest should be able to run without any outside information (makes sense).</p>

<p>My question: How do I test such a module? Are there other types of tests that are suited for these kinds of problems?</p>

<p>Thank you in advance!</p>

<h2>UPDATE</h2>

<p>Here is a code example as requested in the comments. The actual mode variable is passed around a few other classes I've kept out of this example to keep it short. But the problem here is that if you run <code>python user.py</code> (which in my case PyCharm does for me when running the unittest) it requires the mode argument to be set. Unit testing the BaseClass also won't work, since the abstract methods are not overridden.</p>

<pre class=""lang-py prettyprint-override""><code>from abc import abstractmethod
from abc import ABC
import argparse

# base.py
class BaseClass(ABC):
    def __init__(self):
        self.args = self._parse_cli_args()

    def _parse_cli_args(self):
        self.parser = argparse.ArgumentParser(
            description='MyApp'
        )

        self.parser.add_argument(
            'mode',
            choices=[
                'mode1',
                'mode2',
                'mode3'
            ],
            metavar='MODE [mode1, mode2, mode3]'
        )

    # the methods i'd like to unittest
    def methodIWantToTest1(self):
        # some useful computations
        pass

    def methodIWantToTest2(self):
        # some useful computations
        pass

    def methodIWantToTest3(self):
        # some useful computations
        pass


    # methods that should be overridden by end User (UserClass below)
    @abstractmethod
    def abstractMethod1(self):
        pass

    @abstractmethod
    def abstractMethod2(self):
        pass

    @abstractmethod
    def abstractMethod3(self):
        pass

    @abstractmethod
    def abstractMethod4(self):
        pass

# user.py
class UserClass(BaseClass):
    def AbstractMethod4(self):
        super().abstractMethod4()
    #     users implementation here

    def AbstractMethod3(self):
        super().abstractMethod3()
    #     users implementation here

    def AbstractMethod2(self):
        super().abstractMethod2()
    #     users implementation here

    def AbstractMethod1(self):
        super().abstractMethod1()
        # users implementation here
</code></pre>
",https://stackoverflow.com/questions/46957063/python-testing-a-cli-application-with-required-arguments,"['python', 'python-3.x', 'unit-testing', 'testing']",47,FALSE,0,0
Specflow CodedUI Generator Plugin not generating feature files,"<p>Okay. So here is where I am at. I am using Specflow 2.2.0 to pair automated unit testing with our CodedUI testing effort. I am developing a plugin to add the CodedUI Test attribute to the Specflow Feature tests and I am running into some problems. Specflow is not recognizing my plugin to generate the CodedUI Test Attribute to Specflow feature files and I don't understand why because I have followed every instruction in the documentation as well as looked at other plugins on GitHub to make sure I am doing it right. </p>

<p>I have the plugin in its own class library project and upon build its dll autocopies to the packages folder in the Solution where Specflow is located. I have the assembly files edited to point to the generator. I have the initializers for the eventhandler. I have everything in the app.config of my CodedUI project correct as far as I can tell and I still get errors. Here is everything I have in regards to the plugin and the other relevant pieces:</p>

<p>Here is the code from my plugin that initializes the IGenerator Class:</p>

<pre><code>namespace SpecflowCUITPluginLib
{
    public class CodedUiPlugin : IGeneratorPlugin
    {
        public void Initialize(GeneratorPluginEvents generatorPluginEvents, GeneratorPluginParameters generatorPluginParameters)
        {
            generatorPluginEvents.CustomizeDependencies += this.GeneratorPluginEventsOnCustomizeDependencies;
        }
        private void GeneratorPluginEventsOnCustomizeDependencies(object sender, CustomizeDependenciesEventArgs customizeDependenciesEventArgs)
        {
            string unitTestProviderName =
              customizeDependenciesEventArgs.SpecFlowProjectConfiguration.SpecFlowConfiguration.UnitTestProvider;
            if (unitTestProviderName.Equals(""mstest"", StringComparison.InvariantCultureIgnoreCase)
              || unitTestProviderName.Equals(""mstest.2010"", StringComparison.InvariantCultureIgnoreCase))
            {
                customizeDependenciesEventArgs.ObjectContainer.RegisterTypeAs&lt;CodedUIGeneratorProvider, IUnitTestGeneratorProvider&gt;();
            }
        }
        #region IGeneratorPlugin Members
        public void RegisterConfigurationDefaults(TechTalk.SpecFlow.Generator.Configuration.SpecFlowProjectConfiguration specFlowConfiguration) { }
        public void RegisterCustomizations(BoDi.ObjectContainer container, TechTalk.SpecFlow.Generator.Configuration.SpecFlowProjectConfiguration generatorConfiguration)
        {
            container.RegisterTypeAs&lt;CodedUIGeneratorProvider, IUnitTestGeneratorProvider&gt;();
            container.RegisterTypeAs&lt;MsTest2010RuntimeProvider, IUnitTestRuntimeProvider&gt;();
        }
        public void RegisterDependencies(BoDi.ObjectContainer container) { }
        #endregion
    }
}
</code></pre>

<p>Here is the code from my Generator Provider that is located in a separate .cs  file:</p>

<pre><code>namespace SpecflowCUITPluginLib
{

    public class CodedUIGeneratorProvider : MsTest2010GeneratorProvider
    {
        public CodedUIGeneratorProvider(CodeDomHelper codeDomHelper)
            : base(codeDomHelper) { }
        private const string TestClassAttribute = @""Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute"";
        private const string CodedUiTestClassAttribute = @""Microsoft.VisualStudio.TestTools.UITesting.CodedUITestAttribute"";
        private const string DeploymentItemAttribute = ""Microsoft.VisualStudio.TestTools.UnitTesting.DeploymentItemAttribute"";
        public override void SetTestClass(TestClassGenerationContext generationContext, string featureTitle, string featureDescription)
        {
            base.SetTestClass(generationContext, featureTitle, featureDescription);
            foreach (CodeAttributeDeclaration declaration in generationContext.TestClass.CustomAttributes)
            {
                if (declaration.Name == TestClassAttribute)
                {
                    generationContext.TestClass.CustomAttributes.Remove(declaration);
                    break;
                }
            }
            generationContext.TestClass.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(CodedUiTestClassAttribute)));
            string filename = new Uri(this.GetType().Assembly.CodeBase).LocalPath;
            // Add deployment item in each test for the driver.
            generationContext.TestClass.CustomAttributes.Add(
                new CodeAttributeDeclaration(
                    new CodeTypeReference(DeploymentItemAttribute),
                    new CodeAttributeArgument(new CodePrimitiveExpression(""SpecflowCUITPluginLib.SpecFlowPlugin.dll""))));
        }
    }
}
</code></pre>

<p>Here is the line I added to the assembly file:</p>

<pre><code>[assembly: GeneratorPlugin(typeof(CodedUiPlugin))]
</code></pre>

<p><a href=""https://i.stack.imgur.com/dwGbK.png"" rel=""nofollow noreferrer"">Here is a screencap of my build settings for the plugin project</a></p>

<p>And here is my app.config from my CodedUI Project</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""utf-8""?&gt;
&lt;configuration&gt;
  &lt;configSections&gt;
    &lt;section name=""specFlow"" type=""TechTalk.SpecFlow.Configuration.ConfigurationSectionHandler, TechTalk.SpecFlow"" /&gt;
  &lt;/configSections&gt;
  &lt;specFlow&gt;
    &lt;unitTestProvider name=""MsTest"" /&gt;
    &lt;plugins&gt;
      &lt;add name=""SpecflowCUITPluginLib.SpecflowPlugin"" path="".\MedchartUITesting\packages\specflow2.2.0\tools"" type=""Generator"" /&gt;
    &lt;/plugins&gt;
  &lt;/specFlow&gt;
&lt;/configuration&gt;
</code></pre>

<p>And no matter what I do I get this error for my feature files : <code>#error Generation error: Unable to find plugin in the plugin search path: SpecflowCUITPluginLib.SpecflowPlugin. Please check http://go.specflow.org/doc-plugins for details.</code></p>

<p>Anyone see a solution or a problem because at this moment I am really at a loss as to where I should be looking for a solution.</p>
",https://stackoverflow.com/questions/45966782/specflow-codedui-generator-plugin-not-generating-feature-files,"['c#', 'cucumber', 'ui-automation', 'coded-ui-tests', 'specflow']",628,TRUE,0,1
Rails: Testing authorization (Pundit) with RSpec,"<p>I'd like to thoroughly test a Rails application authorization setup (Pundit) with RSpec.</p>

<ol>
<li><p>The <a href=""https://github.com/elabs/pundit#policy-specs"" rel=""noreferrer"">Pundit docs</a> and <a href=""http://www.thunderboltlabs.com/blog/2013/03/27/testing-pundit-policies-with-rspec"" rel=""noreferrer"">other respectful sources</a> suggest writing unit tests for Pundit policy classes. Are those tests testing behavior (good) or implementation details (bad)?</p></li>
<li><p>If we were actually testing behavior, shouldn't our tests still pass if we eventually switched from Pundit to another authorization gem or rolled our own authorization? </p></li>
<li><p>Suppose a call to the <code>authorize</code> method is accidentally removed from a controller action, leaving it open for public access. Pundit policy tests will keep passing. If we have no other tests covering this, our test suite may be all green while our app has a serious security vulnerability. How can we avoid this? Maybe write unit tests for Pundit controller classes, separate unit tests for controllers and mock the <code>authorize</code> method in the controller tests to ensure they are called?</p></li>
</ol>

<p><strong>Edit:</strong> On second thought, I had a lapse of judgment regarding the difference between implementation details and the public API for a class. Calling specific public methods, passing specific arguments and expecting specific return values is a requirement to unit-test (and to use) any class. Please disregard item 3 as
 my original argument is invalid.</p>

<ol start=""4"">
<li>Instead of testing Pundit policy classes, we could write controller or request specs that login with different user roles, call the controller actions and assert whether access was granted or denied. In this approach, the tests would keep passing even if we switched to another authorization gem. Also, they would fail if the <code>authorize</code> method is not called. However, these would be integration tests and should be slower that unit testing Pundit policy classes. Could that be a better way to test the authorization setup?</li>
</ol>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/44315565/rails-testing-authorization-pundit-with-rspec,"['ruby-on-rails', 'testing', 'rspec', 'tdd', 'pundit']",2578,TRUE,5,1
TDD - Unit tests failing due to assumptions in the arrange phase,"<p>I'm doing (or trying to do) TDD to develop my business logic for an application.</p>

<p>I have a collection in one class that I expose as <code>IReadOnlyList</code>, because I want to make it clear that adding/removing from the list is prohibited. Instead I expose <code>AddItem</code> and <code>RemoveItem</code> methods, so that I can execute some other code when an item is added or removed. See example below.</p>

<pre><code>public interface IBusinessItem { }
public interface IBusinessClass
{
    IReadOnlyList&lt;IBusinessItem&gt; Items { get; }

    void AddItem(IBusinessItem item);
    void RemoveItem(IBusinessItem item);
}
</code></pre>

<p>My problem arises when I try to follow the principle that my unit tests <a href=""https://stackoverflow.com/a/1542548/4351604"">should fail for one reason only</a>. Unit testing my <code>RemoveItem</code> requires that I make use of <code>AddItem</code> in my test arrange phase. Therefore, my test can fail either because the <code>RemoveItem</code> does not remove an item as expected, or because the <code>AddItem</code> didn't work as expected so <code>RemoveItem</code> throws:</p>

<pre><code>[Fact]
public void RemoveItemShouldRemoveItemFromItems()
{
    // Arrange
    var item = new MyBusinessItem();
    sut.AddItem(item);
    // Act
    sut.RemoveItem(item); // throws exception if sut.Items is empty
    // Assert
    Assert.Empty(sut.Items);
}
</code></pre>

<p>I'm thinking that my unit test would be less fragile if I could access <code>sut.Items.Add(item)</code>, instead of relying on <code>sut.AddItem(item)</code>, but I don't want to <a href=""https://softwareengineering.stackexchange.com/a/126577"">change my public interface just for testing purposes</a>.</p>

<p>I think this <a href=""https://stackoverflow.com/a/1093481/4351604"">answer</a> partially adresses my concerns. My interpretation of the answer (and one of <a href=""https://stackoverflow.com/users/126014/mark-seemann"">Mark</a>'s comments to the answer) is that it is fine to invoke other methods in the arrange phase. But I feel like this could end up with a lot of tests that fails for other reasons than what they are actually testing.</p>

<p><strong>My question here is</strong>: When doing TDD, is it acceptable to access the underlying <code>List.Add</code> (that is not part of my public interface) in order avoid dependency of the <code>AddItem</code> implementation in my <code>RemoveItem</code> tests?.</p>

<p>A few ways I can think of to access the underlying <code>List.Add</code>:</p>

<ul>
<li>Casting it in the test</li>
<li>Changing the underlying private field to protected and create a mock that inherits from my BusinessClass and exposes that field</li>
<li>Changing the underlying private field to internal and use the <code>InternalsVisibleTo</code> attribute</li>
</ul>
",https://stackoverflow.com/questions/46296411/tdd-unit-tests-failing-due-to-assumptions-in-the-arrange-phase,"['c#', 'unit-testing', 'testing', 'nunit', 'tdd']",181,FALSE,3,0
How Can I Unit Test Calling of iOS Application Delegate Methods?,"<p>I have an iOS application that integrates with the GitHub API. I am unit testing my <code>OAuth</code> requests, which requires testing the receipt of a code from the GitHub API that I will use to exchange for a token.</p>

<p>In my <code>AppDelegate.swift</code>, I have the following method, which is used to handle the callback from GitHub when the user authorizes my application to use their GitHub account:</p>

<pre class=""lang-swift prettyprint-override""><code>func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -&gt; Bool {
    return true
}
</code></pre>

<p>The steps are as follows:</p>

<ol>
<li>Open the application.</li>
<li>Using the URL for authorizing GitHub account access (<a href=""https://github.com/login/oauth/authorize"" rel=""nofollow noreferrer"">https://github.com/login/oauth/authorize</a>), an instance of <code>SFSafariViewController</code> is presented, allowing the user to press the 'Authorize' button.</li>
<li>GitHub uses the callback URL to my application that I provided when registering my application with GitHub, which sends a notification to open my app.</li>
<li>The method above is executed, where I retrieve the <code>code</code> parameter from <code>url</code>.</li>
</ol>

<p>However, I am stuck trying to find a way to test this without actually making a request to the GitHub API. I can create a <code>URL</code> instance that mimics what GitHub supplies my application with, but I would like to test this without making an actual request. </p>

<p>Is there a way to unit test this, or is this something that I shouldn't worry about since it's handled by the OS, and instead, only test my code for parsing the <code>code</code> parameter of a test <code>URL</code>?</p>

<p><strong>UPDATE</strong></p>

<p>After taking Jon's <a href=""https://stackoverflow.com/questions/41667280/how-can-i-unit-test-calling-of-ios-application-delegate-methods#41668489"">advice</a>, I created a test class to allow me to simulate the GitHub callback in action:</p>

<pre class=""lang-swift prettyprint-override""><code>class GitHubAuthorizationCallbackTests: XCTestCase {

    let delegate = AppDelegateMock()

    func test_AuthorizationCallbackFromGitHub_ApplicationOpensURL() {
        guard let url = URL(string: ""xxxxxxxxxxxxxx://?code=********************"") else { return XCTFail(""Could not construct URL"") }
        let isURLOpened = delegate.application(UIApplication.shared, open: url)
        XCTAssertTrue(isURLOpened, ""URL is not opened from GitHub authorization callback. Expected URL to be opened from GitHub authorization callback."")
    }

}
</code></pre>

<p>Then, I created <code>AppDelegateMock.swift</code> to be used instead of <code>AppDelegate.swift</code>, adding in the intended method to be called when the GitHub callback is executed to open my app:</p>

<pre class=""lang-swift prettyprint-override""><code>import UIKit

class AppDelegateMock: NSObject, UIApplicationDelegate {

    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -&gt; Bool {
        return true
    }

}
</code></pre>

<p>The test passes, allowing me to test the logic that I need to test for handling the <code>code</code> parameter that is returned from GitHub int he <code>url</code> parameter of the method.</p>
",https://stackoverflow.com/questions/41667280/how-can-i-unit-test-calling-of-ios-application-delegate-methods,"['ios', 'unit-testing', 'appdelegate']",2254,TRUE,3,1
Jersey Unit Test: in memory container vs grizzly,"<p>I'm trying to get my head around unit testing in Jersey.</p>

<p>The classes that do not depend on Jersey directly can be unit tested using standard JUnit. This one is OK.</p>

<p>But there are also Jersey (or, should I say JAX-RS?) dependent classes. In order to test these (inlc. correctness of the annotations, serialization, status codes, etc.) Jersey provides ""test framework"" that contains base <code>JerseyTest</code> class.</p>

<p>This is also fine and understandable.</p>

<p>Then, however, the official documentation specifies several types of supported containers in which subclasses of <code>JerseyTest</code> can be executed. </p>

<p>It seems like these containers can be divided into two types:</p>

<ol>
<li>Real containers</li>
<li>In-memory container</li>
</ol>

<p>From my current (newbie) perspective, all type #1 containers provide the same functionality. Therefore, let's take Grizzly as type #1 representative.</p>

<p>Now, it is clear that in-memory container (which is not a real container at all) is faster than Grizzly. Therefore, I'd like to use this container in order to test Jersey dependent classes. But this statement from <a href=""https://jersey.java.net/documentation/latest/test-framework.html"" rel=""nofollow noreferrer"">the official documentation</a> confuses me:</p>

<blockquote>
  <p>This containers does not support servlet and other container dependent
  features, but it is a perfect choice for simple unit tests.</p>
</blockquote>

<p>I tried to google for comparison of in-memory container with Grizzly, but did not find any definitive comparison. I also read <a href=""http://jersey.576304.n2.nabble.com/Best-Library-to-Unit-Test-Jersey-Restful-Web-Services-td7582641.html"" rel=""nofollow noreferrer"">this highly technical thread</a>, but the downsides of in-memory container are still not clear to me.</p>

<p>In this respect, I have two questions:</p>

<ol>
<li>What ""servlet and other container dependent features"" are (no need for a comprehensive list, but just general description)?</li>
<li>If I choose in-memory container, can I then encounter a situation of code that passes test, but fails in production (I will use Tomcat in production, if that matters)?</li>
</ol>

<p>Thanks</p>
",https://stackoverflow.com/questions/43790757/jersey-unit-test-in-memory-container-vs-grizzly,"['java', 'jersey', 'jersey-2.0', 'jersey-test-framework']",1104,TRUE,3,1
"Linker errors with codelite, unittest++ and g++ on linux","<p>I'm new to unit testing in c++, and writing c++ on Linux (Mint). I'm using CodeLite as my IDE. I have found several answers on stackoverflow about linker errors, but after hours of trying various solutions I have not succeeded in implementing a solution correctly.</p>

<p>I installed unittest++ through apt-get. The unittest++ header files were installed in /usr/include, so I added this to the Compiler linker options in Codelite (Right click project name->Settings, Compiler):
<a href=""https://i.stack.imgur.com/zxZQZ.png"" rel=""nofollow noreferrer"">Codelite screenshot</a></p>

<p>I then have a very simple program, which consists entirely of one main.cpp file:</p>

<pre><code>#include &lt;unittest++/UnitTest++.h&gt;
//See if unit tests are working
TEST(MyMath) {
    CHECK(false);
}

int main()
{
    UnitTest::RunAllTests();
    return 0;
}
</code></pre>

<p>Running the project at this point generates a stream of linker errors other users have experienced, for example:</p>

<p>main.cpp:4: undefined reference to <code>UnitTest::CurrentTest::Details()</code></p>

<p>At this point, my understanding is that I now need to tell the g++ compiler about the object files and link them to the unittest++ files. And this is where I'm stuck. The only .o file I see is in <em>Debug/main.cpp.o</em> and running the command <br>
    g++ main.cpp -o main.cpp.o -Lunittest++
as well as variations with the I and o flags, but all of them return the same linker errors I get when I try to compile. I've also tried to copy every g++ line in the forums and only get various errors.</p>

<p>I've tried to find a solution in the g++ man pages, read about the flags I've been using and did not infer a solution. I then quickly got buried in quantity of pages in the man entry. The documentation for CodeLite and unittest++ seems woefully out of date, so I posted here on stackoverflow as a last resort.</p>

<p>I'm fairly certain I'm just making a rookie mistake. If someone has feedback, I'd be grateful.</p>
",https://stackoverflow.com/questions/42657198/linker-errors-with-codelite-unittest-and-g-on-linux,"['c++', 'linker', 'g++', 'codelite', 'unittest++']",628,TRUE,2,1
How can I avoid calling Python interpreter many times from a Bash script?,"<p>I'm working on a project involving two main components, one with a Bash command-line interface and one with a Python API. For the purposes of this question, assume that neither of these components can be modified to use a different language for the interface.</p>

<p>I now need to write some scripts that use features of both components. I have two possible approaches in mind: (a) write Bash scripts invoking the Python interpreter for interfacing with the Python component, or, (b) write Python scripts using calls to <code>os.system</code> or something similar, which allows one to run Bash commands.</p>

<p>The problem with writing Bash scripts is that I often need to call a function from the Python component inside a loop, something like this:</p>

<pre><code>while read -r line ; do
    echo ""Now handling the next line of the file.""
    python -c ""from my_module import *; my_function('${line}')""
    # some bash commands
done &lt; some_file.txt
</code></pre>

<p>I don't like the overhead of calling the Python interpreter so many times, and also doing this same import so often. Is there any way to start up the interpreter and import the module once, and then dynamically call other functions in that context? Keep in mind that I will be using other Bash commands between Python function calls.</p>

<p>The problem with writing Python scripts is that any time we need to access the component with the command-line interface, we have to use calls to <code>os.system</code> or something similar. Some of the scripts only include calls to the command-line interface, meaning I would have a Python script with every line using <code>os.system</code>. I don't like this either.</p>

<p>These scripts, whether written in Python or Bash, will be used for unit testing, so readability, maintainability, and extensibility are higher priorities than pure speed. Furthermore, all of them should be written in the same language for consistency's sake.</p>

<p>I'm hoping that someone can guide me to the most elegant solution to this problem. Thanks in advance!</p>
",https://stackoverflow.com/questions/42686602/how-can-i-avoid-calling-python-interpreter-many-times-from-a-bash-script,"['python', 'bash', 'language-interoperability']",115,TRUE,2,1
How to mock concrete object in a template type exported from a dll?,"<p>I have an application <code>Application</code> object type exported from a dll (dynamic link library) like so,</p>

<pre><code>//App.h
class __declspec(dllexport) Application
{
    Utility utility;
public:
    Application();
    void Foo();
    void Bar();
    ~Application();
};
</code></pre>

<p>It ""has a"" utility that it uses for providing some crucial functionality, through its Foo and Bar exports. As the utility is concrete, I followed the <a href=""https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md#mocking-nonvirtual-methods"" rel=""nofollow noreferrer"">mock non-virtual methods using templates</a> given in GMock primer. So I've made my app look like the following,</p>

<pre><code>//App.h - modified
template &lt;class Utility&gt;
class __declspec(dllexport) Application
{
    Utility utility;
public:
    Application();
    void Foo();
    void Bar();
    ~Application();
};
</code></pre>

<p>Now that I've templatized my type, in production I will use, <code>Application&lt;ConcreteUtility&gt;</code> and for testing I wanted to use, <code>Application&lt;MockUtility&gt;</code>. the .cpp file for the app looks like the following now, specializing for <code>Application&lt;ConcreteUtility&gt;</code></p>

<pre><code>//.cpp
template class Application&lt;ConcreteUtility&gt;;
Application&lt;ConcreteUtility&gt;::Application() {/*construct app with the concrete utility*/}
Application&lt;ConcreteUtility&gt;::Foo() {/*implement Application's foo using the concrete utility*/}
Application&lt;ConcreteUtility&gt;::Bar {/*implement Application's bar using the concerete utility*/}
Application&lt;ConcreteUtility&gt;::~Application() {/*destroy the Application*/ }
</code></pre>

<p>I've written a unit test application, that will link to my application dll at load time (.h and .lib import library). As I'm using GMock framework I've mocked the utility like so,</p>

<pre><code>class MockUtility
{
public:
    /*mock all public methods of utility that the application could have possibly used*/
    MOCK_METHOD1(FuncUsingANetworkConnection, void(int));
    MOCK_METHOD0(FuncUsingADatabase, int());
    MOCK_METHOD0(FuncReadingAndWritingFromDisk, int());
    MOCK_METHOD2(FuncManipulatingWindowsRegistry, int(long, long));
    MOCK_METHOD0(FuncSomeMoreUnreliableResource, int());
};
</code></pre>

<p>Now, In my test fixture, I've instantiated, <code>Application&lt;MockUtility&gt;</code>. It compiles, but while linking it is not able to find the definitions for, <code>Application&lt;MockUtility&gt;::Application()</code> - the constructor, <code>Application&lt;MockUtility&gt;::Foo()</code> - the foo for <code>Application&lt;MockUtility&gt;</code> and <code>Application&lt;MockUtility&gt;::Bar()</code> and  <code>Application&lt;MockUtility&gt;::~Application()</code>. It starts to complain here. </p>

<p>I can see that it is indeed not defined anywhere, but how do I make this work ? I cannot refactor and extract an interface out of this utility, as it is too hairy. But I wanted to unit test this application dll's functionality somehow.</p>

<p>I did not want to pollute the App's implementation, with the unit testing stuff and writing an implementation separately for <code>Application&lt;MockUtility&gt;</code>. Even If I can do that, I cannot manage to bring all the changes in the app to this new implementation I write every time the app changes.</p>

<p>I'm not sure if this will make any sense but I will go ahead and ask: I want the compiler and linker to understand that <code>Application&lt;MockUtility&gt;</code> is just the  Application with the implementation for <code>utility</code> from the <code>MockUtility</code> I've written. </p>

<p>Is this thing even possible ? 
If not, how can I mock calls made on this <code>utility</code> object ?</p>
",https://stackoverflow.com/questions/47097608/how-to-mock-concrete-object-in-a-template-type-exported-from-a-dll,"['c++', 'unit-testing', 'templates', 'googlemock']",324,FALSE,2,0
"MVP and Android Handling Lifecycle events, where to do UI logic","<p>I am converting my application to use the MVP pattern. There is some debate between the developers on the proper use of MVP especially in regards to the Android lifecycle and where the UI related logic goes. There is no debate that any hard logic should be done in the presenter, and that the network</p>

<hr>

<p>In the case I need to do Anything for lifecycle functions, onresume, onPause, etc. Should I ...</p>

<ol>
<li>Call a mPresenter.onResumeEvent(); The presenter then does calls. IE
contract.restoreState(); contract.connectToService() etc.</li>
</ol>

<p><strong>or</strong></p>

<ol start=""2"">
<li>Do all the logic I need here and not involve the controller. IE
restoreState, start up loading spinners, etc.</li>
</ol>

<p>I view it as onResume is an event. All events should be processed by the Presenter. The counter arguments is, we do not want to write code that ""ping pongs,"" I.E. OnResume -> Presenter -> one line function that shows a spinner (or something close to that effect) </p>

<hr>

<p>Now a bit more granule.
Lets says I start my activity, and I need to show either an error or the data depending if the data is null. </p>

<p>I could either do..</p>

<pre><code>(presenter)
contract.setupUi(data);
</code></pre>

<p>then</p>

<pre><code>(view)
setupUi(Object data){
if(data != null){
//show data 
}
else{
//show error
}
</code></pre>

<p>Which has the UI controlling the state evoked from the presenter.</p>

<p>Or I could do</p>

<pre><code>(presenter)
if(data != null){
contract.showUI(data);
}
else{
contract.showError();
}
</code></pre>

<p>Which has the contract looking at all the states.</p>

<hr>

<p>Is the over all goal to have the Presenter Completely control everything about the application and treat the view as completely Dumb. Or is it just dividing up the code purely for testing purposes. Or is it both?</p>

<hr>

<p><strong>Recap.</strong> </p>

<ol>
<li>How should I handle the lifecycle -- treat it as an event or let the
view just do it.</li>
<li>Where should the view related logic go? Let the Presenter figure out
what is null and what UI to show. Or let the view take care of it?</li>
<li>What should my over all focus be? Controlling the app with the
presenter, unit testing, both?</li>
</ol>
",https://stackoverflow.com/questions/42564606/mvp-and-android-handling-lifecycle-events-where-to-do-ui-logic,"['android', 'design-patterns', 'mvp']",579,TRUE,2,1
C/C++ Project inluding folders containing separate build shells not able to include files from each other,"<p>I have a complex C++ Project folder which contains two folders.</p>

<ul>
<li>a C++ <strong>src</strong> folder with multiple sub-folders and CmakeList.txt file. The src folder contains main.cpp file.</li>
<li>a C++ build standard external folder <strong>ExtLib</strong> containing multipe subfolders and a <strong>build.sh</strong> script for its compilation and CmakeList.txt file. The .cpp files are linked (includes header(.h) files) to this ExtLib folder.</li>
</ul>

<p>The Project folder contains a main build.sh file which compiles the project and creates a build folder including debug and release configurations. It also contains a CmakeList.txt file which I suppose gets executed when build.sh file is executed. The task that I need to perform on this project is to create a new <strong>tests</strong> folder and add a file (<strong>runtests.cpp</strong>) which performs unit-testing (using catch unit-test) on the code written in the src folder .cpp files. </p>

<p><strong>Problem I face:</strong></p>

<ol>
<li><p>The first problem is when I am creating a source test file in my tests folder, and trying to include header files from src folder, the compiler throws a fatal error that no such (.h) files found.(from src folder). Also sometimes the problem occurs in the src folder files, as they are unable to locate ExtLib folder files.</p></li>
<li><p>The second question is, if by some how I am able to include files from other src or ExtLib folders successfully, how can I be able to run the test source file runtests.cpp for executing my test cases?</p></li>
</ol>

<p>The project heirarchy is shown below:</p>

<p><code>
TestProject 
│   build.sh
│   CMakeList.txt<br>
└───ExtLib
│   │   buildscript.sh
│   │   CMakeList.txt
│   └───subfolder1
│   └───subfolder2(containing sub-folders)
└───src
│   │   main.cpp
│   │   CMakeList.txt
│   └───folder1
│   └───folder2(containing sub-folders)
└───tests
    │   runtests.cpp
    │   catch.hpp
</code></p>

<p>Do I need to include a CMakelist.txt file for my tests folder too? How to make it if I have to? I am very new to this field. Hope you guys can help.
Thanks Rg</p>
",https://stackoverflow.com/questions/43231526/c-c-project-inluding-folders-containing-separate-build-shells-not-able-to-incl,"['c++', 'bash', 'unit-testing', 'cmake', 'catch-unit-test']",105,FALSE,1,0
Laravel package unit testing failing for helper function in config file (call to undefined method base_path()),"<p>Okay, So I'm trying to update a package that I used a good deal with Laravel 4 to be compatible with Laravel 5, since the original repository hasn't had any updates for a while and it needed a few tweaks to work with Laravel 5.</p>

<p>I have made the necessary changes, and created a <a href=""https://github.com/Anahkiasen/polyglot/pull/55"" rel=""nofollow noreferrer"">pull request</a> to the original repository. </p>

<p>I noticed the unit tests had failed, though, so I tried digging into it. I haven't done anything with PHPUnit so far, so I figured this would be a good learning experience.</p>

<p>I'm not asking for help with the error displayed on github. I managed to get past that error, but I achieved this by removing some tests, which of course isn't an actual solution, thus these changes are not committed. I will fix that once I have a better understanding of how unit testing works. </p>

<p>The problem I seem to be having is that one of Laravel's helper functions is being used in the default config file of the package, it is saying the function <code>base_path()</code> is undefined.</p>

<p>As I understand, PHPUnit works with classes and I would need to mock the function in order for it to be used. Can't seem to find a straight answer HOW to do that. </p>

<p>Since it's pointing a config variable to a folder which doesn't exist in my repository hierarchy, I'm not even sure what it should return.</p>

<p>The file that's causing the issue is the default config located in polyglot/config/polyglot.php</p>

<pre><code>return [

// Whether to swap out the facades (Router, Lang, etc) with
// Polyglot's, disable this if you need other packages to do the same
// Can specify an array of facades to swap, eg. ['Lang', 'URL']
'facades' =&gt; true,

// Locales
////////////////////////////////////////////////////////////////////

// The default locale if none is provided in the URL
// Leave empty to force the use of locales prefixes in URLs
'default' =&gt; 'en',

// The fallback locale for translations
// If null, the default locale is used
'fallback' =&gt; null,

// The available locales
'locales' =&gt; [],

// Gettext
////////////////////////////////////////////////////////////////////

// The domain of your translations, for gettext use
'domain' =&gt; 'messages',

// Where the PO/MO files reside

'folder' =&gt; base_path('resources/lang'),
// Format of the compiled files
'file' =&gt; '{domain}.po',

// Database
////////////////////////////////////////////////////////////////////

// The pattern Polyglot should follow to find the Lang classes
// Examples are ""Lang\{model}"", ""{model}Lang"", where {model}
// will be replaced by the model's name
'model_pattern' =&gt; '{model}Lang',
</code></pre>

<p>];</p>

<p>So, what is typical to do in this situation? Define the function manually? Include the helper file somehow? Or discard the use of the function and go with a solution using basic php directory references? Any help would be appreciated.</p>
",https://stackoverflow.com/questions/41706106/laravel-package-unit-testing-failing-for-helper-function-in-config-file-call-to,"['php', 'unit-testing', 'laravel-5.3']",1662,TRUE,1,2
Python Mock and Unit test best practices,"<p>I am very new to Python world and learning my way in it. I have Java and C# background and in Java/C# unit testing approach is very clear. We have a class under test and we inject all the mocked dependency with expectations to test code.</p>

<p>like:</p>

<p>Car class with a service fuelLevel
Test case: Car is showing low fuel indication, we can write a test.</p>

<pre><code>    FuelLevelService fsMock = mock(FuelLevelService .class);
    when(fsMock.getLevel()).thenReturn(LOW);
    Car car = Car(fsMock)
    car.start()
    assertTrue(car.warningIndicator());
    assertTrue(car.warning().contains(""Fuel level low Warning""));
</code></pre>

<p>In python i have read we can use monkey patching to set the dependent objects and we can test. </p>

<pre><code>    @mock.patch('models.fuel_service.getLevel')
    def test_main(self, fuel_service):
        fuel_service.return_value = 'LOW'
        Car car = Car(fuel_service)
        car.start()
        self.assertEqual(car.warningIndicator(), True)
</code></pre>

<p>I was going to use this approach. But my colleagues have rejected this idea and are proposing to instantiate the actual objects (FuellevelService) and set its value. I find it to be very cumbersome and not needed as in mock also we can do the same with just our expectations.</p>

<p>I am currently struggling to understand if i am wrong or in python my colleagues approach is regarded better pattern.</p>

<p>*Above i have given a simple example. In our project to create an instance object and setting its value is 10-25 lines of code [don't ask me why but that is how it is :)]  To create this object and set a value so it returns that same value looks extra maintenance to me. For this approach to create dependent object we will have many py files in module.</p>

<p>Another point is we are here only testing class under test (not dependency service class), class under test which will react on the returned value of the dependency service. We can can have both negative and positive tests to cover class under test. </p>

<p>For dependency service class in same way it should have its own tests to validate all its scenarios separability. So it will be class under test there. By doing this we will have clear separation and test will fail where there is bug.</p>
",https://stackoverflow.com/questions/46114540/python-mock-and-unit-test-best-practices,"['java', 'python', 'python-2.7', 'unit-testing', 'mocking']",1112,FALSE,1,1
User-defined types in Apache Derby as ENUM replacements,"<p>I'm using Apache Derby as an in-memory mock database for unit testing some code that works with MySQL using jOOQ.</p>

<p>The production database uses enums for certain fields (this is a given and out of scope of this question - I know enums are bad but I can't change this part now), so jOOQ generates code to handle the enums.</p>

<p>Unfortunately, Derby does not support enums and when I try to create the database in Derby (from jOOQ SQL generator), I get errors. </p>

<p>My solution was to user-defined types that mimic the enum by wrapping the relevant jOOQ generated enum Java class. So, for example, if I have an enum field <code>kind</code> in the table <code>stuffs</code>, jOOQ SQL generator creates Derby table creation SQL that talks about <code>stuffs_kind</code>. </p>

<p>To support this I created the class <code>my.project.tests.StuffsKindDebyEnum</code> that wraps the jOOQ generated enum type <code>my.project.model.StuffsKind</code>. I then run the following SQL through Derby, before running the jOOQ database creation SQL:</p>

<pre><code>CREATE TYPE stuffs_kind EXTERNAL NAME 'my.project.tests.StuffsKindDerbyEnum' LANGUAGE JAVA
</code></pre>

<p>When I then use jOOQ to insert new records, jOOQ generates SQL that looks somewhat like this:</p>

<pre><code>insert into ""schema"".""stuffs"" (""text"", ""kind"") 
  values (cast (? as varchar(32672)), cast(? as stuffs_kind)
</code></pre>

<p>But binds a string value to the <code>kind</code> argument (as expected), and it work for MySQL but with Derby I get an exception:</p>

<pre><code>java.sql.SQLDataException: An attempt was made to get a data value of type
  '""APP"".""STUFFS_KIND""' from a data value of type 'VARCHAR'
</code></pre>

<p>After looking at all kinds of ways to solve this problem (including trying to treat enums as simple VARCHARs), and before I give up on being able to test my jOOQ-using code, is there a way to get Derby to ""cast"" varchar into user-defined types? If could put some Java code that can handle that, it will not be a problem as I can simply do <code>StuffsKind.valueOf(value)</code> to convert a string to the correct enum type, but after perusing the (very minimal) Derby documentation, I can't figure out if it is even should be possible.</p>

<p>Any ideas are welcome!</p>
",https://stackoverflow.com/questions/45293986/user-defined-types-in-apache-derby-as-enum-replacements,"['java', 'enums', 'derby']",945,TRUE,1,1
libclang getting original struct parameter types,"<p>This appears to be a duplicate question (I found someone asking the same thing yesterday but I can't find it now), except that the other copy of this question provided an alternative answer that doesn't really address the problem.</p>

<p>I'm working on a small tool using libclang to summarize the struct and function declarations in a given header file, as part of a tool to build automatic Ruby bindings for unit testing.</p>

<p>I'm currently running my fledgling program on its own source file for testing purposes, and as I traverse this function declaration (for instance):</p>

<pre><code>enum CXChildVisitResult statementVisitor(CXCursor cursor, CXCursor parent, CXClientData client_data);
</code></pre>

<p>the return type node (which is an enum) contains basically what I'd expect, but all three of the parameters (which are all struct types) have CXType ""int"". According to what I've been able to find, it is pretty standard for compilers to treat structs as integer types and just replace member accesses with suitable offsets.</p>

<p>This seems bizarre to me, since knowing the actual struct type would be totally necessary for a tool to, for instance, determine whether a member access is being used in a valid way elsewhere in the AST. I tried to get a hold of the original source using clang_getCursorExtent, but this gives offsets into the post-preprocessed file, so I can't simply re-open the file for reading in order to get the text. More to the point, if I'm going to use libclang to find the parameter declarations, I'd like to use libclang to understand them as well. It feels a little silly to use a static code analysis library to help me identify which strings of C code I'll need to parse by hand.</p>

<p>Is there a cmd-line flag that I can pass along to clang to convince it to retain struct types, or some other way to get the parameter types as declared in the code?</p>
",https://stackoverflow.com/questions/46980902/libclang-getting-original-struct-parameter-types,"['c', 'struct', 'libclang']",295,FALSE,1,0
How do I write unit tests for subclass with parameterized base class,"<p>Given that I have a class in one assembly called GBase with a constructor that takes 2 parameters and a subclass of GBase (call it GDerived) that takes the same parameters, how do I separate these so that I can unit test the subclass?</p>

<p>In OtherAssembly:</p>

<pre><code>public class GBase
{
  public GBase(ParamType1 param1, ParamType2 param2)
  {
    ...
  }

  protected ParamType1 SomeProperty { get; set; }

// other stuff
}
</code></pre>

<p>In ThisAssembly:</p>

<pre><code>public class GDerived : GBase
{
  public GDerived(ParamType1 param1, ParamType2 param2)
      :base(param1, param2)
  {
    // new code 

    SomeProperty = newCalculatedValue;

    // other stuff
  }

// other stuff
}
</code></pre>

<p>The original GBase class is legacy code, as is the general structure of the program -- changing the structure is out of the question due to the codebase size (10k lines plus) - none of which has ever had a unit test written for it until very recently.</p>

<p>So now I want to write a test (using NUnit) for the subclass constructor to verify the correct properties are populated with the correct values. Note the test classes are in the same project as the tested classes.</p>

<pre><code>[TestFixture]
public class GDerivedTests
{
  [Test]
  public void GDerivedConstructor_ValidParams_PropertiesSetCorrectly()
  {
    var newGDerived = new GDerived(parameter1, parameter2);

    Assert.That(SomeProperty == parameter1;
  }
}
</code></pre>

<p>This is a very crude rep of what we have to deal with, and there are cases other than setting a property in the base class we need to test. I just don't even know for sure where to start. I have Michael Feathers' book Working Effectively with Legacy Code but it doesn't seem to cover this pervasive ""design pattern"", used extensively throughout the code we are dealing with. Is it because it's so simple any blinking idjyot should know how to deal with it, or is it because it's a rare case? Somehow I don't think it's either, but I could be wrong...</p>

<p>One possible method I thought of is to extract an interface for the base class and mock the base class constructor - but I'm not sure of the details on how to do that. Note we are all relative newbies at unit testing on the team, no experience to draw on. Not coding newbies, just unit test newbies.</p>

<p>TIA,
Dave</p>
",https://stackoverflow.com/questions/44640219/how-do-i-write-unit-tests-for-subclass-with-parameterized-base-class,"['c#', 'unit-testing', 'nunit-3.0']",1084,TRUE,1,1
Thin Out Controller in Asp.Net-Mvc-5 Specific Example,"<p>I have a question regarding the implementation of creating ""thin controllers"" in an Asp.net Mvc 5 application. I've researched this topic for the past couple of days, and I believe I'm at the point where I need a concrete example in order to connect the dots in my understanding.</p>

<p>So, I would like to make use of Unit tests in my application. I've looked at creating view model factories, and builders, skinny controller-fat model, but I'm not quire sure how to implement any of these design patterns that I've read about in this particular scenario. </p>

<p>Below you'll find 5 different actions that are found in my Manage controller. I fear that they smell and require some clean up for simplifying testing/unit testing. I understand that there is usually no ""right answer"" to these type of questions, so I would greatly appreciate all answers that aid in simplifying testing my application.</p>

<p>Here are my actions: </p>

<p>Action #1:</p>

<pre><code>[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = ""DM_Admin"")]

public async Task&lt;ActionResult&gt; Users_Create([DataSourceRequest] DataSourceRequest request, ManageUsersViewModel model)

{
    if (model != null &amp;&amp; ModelState.IsValid)
    {
        // instantiate new application user
        var user = new ApplicationUser
        {
            UserName = model.Email,
            Email = model.Email,
            FirstName = model.FirstName,
            LastName = model.LastName
        };

        // format the RolesList to type List&lt;string&gt; for entry  
        List&lt;string&gt; rolesToAssign = getRoleNameList(model);

        try
        {
            // persist user to User Db
            var createResult = await UserManager.CreateAsync(user, model.Password);
            if (createResult.Succeeded)
            {
                // persist user roles to User Db
                var rolesResult = await UserManager.AddToRolesAsync(user.Id, rolesToAssign.ToArray());
                if (rolesResult.Succeeded)
                {
                    return RedirectToAction(""ManageUsers"");
                }
                AddErrors(rolesResult);
            }
            else
            {
                AddErrors(createResult);
            }
        }
        catch (Exception ex)
        {
            ErrLog.LogError(ex, ""ManageController.Users_Create"");
        }
    }

    return Json(new[] { model }.AsQueryable().ToDataSourceResult(request, ModelState));
}
</code></pre>

<p>Action #2: </p>

<pre><code>[Authorize(Roles = ""DM_Admin"")]
public async Task&lt;ActionResult&gt; Users_Read([DataSourceRequest] DataSourceRequest request)

{
    List&lt;ManageUsersViewModel&gt; users = null;
List&lt;ApplicationUser&gt; allUsers = null;

try
{
    // get all Data Management roles
    var dmRoles = await RoleManager.Roles.Where(r =&gt; r.Name.Contains(""DM_"")).ToListAsync();

    // find all the users for each Data Management role
    foreach (var id in dmRoles.Select(r =&gt; r.Id).ToList())
    {
        if(allUsers == null)
        {
            allUsers = await UserManager.Users.Where(u =&gt; u.Roles.Any(r =&gt; r.RoleId == id)).ToListAsync();
        }
        else
        {
            allUsers.AddRange(await UserManager.Users.Where(u =&gt; u.Roles.Any(r =&gt; r.RoleId == id)).ToListAsync());
        }
    }

    // list of users may have repeats, so remove repeated users in list 
    allUsers = allUsers.Distinct().ToList();
    // instantiate view model with list of users and their respective roles
    users = allUsers.Select(u =&gt; new ManageUsersViewModel
    {
        Id = u.Id,
        FirstName = u.FirstName,
        LastName = u.LastName,
        Email = u.Email,
        Password = u.PasswordHash,
        ConfirmPassword = u.PasswordHash,
        RolesList = dmRoles.Where(r =&gt; r.Users.Any(user =&gt; user.UserId == u.Id)).Select(r =&gt; new RoleModel
                {
                    Id = r.Id,
                    Name = r.Name
                }).ToList()
    }).ToList();
}
catch (Exception ex)
{
    ErrLog.LogError(ex, ""ManageController.Users_Read"");
}

return Json(users.ToDataSourceResult(request));
}
</code></pre>

<p>Action #3:</p>

<pre><code>[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = ""DM_Admin"")]
public async Task&lt;ActionResult&gt; Users_Edit([DataSourceRequest] DataSourceRequest request, ManageUsersViewModel model)
{
    if (model != null &amp;&amp; ModelState.IsValid)
    {
        // format the RolesList to type List&lt;string&gt; with name and List&lt;string&gt; with Id for entry and comparison
        List&lt;string&gt; rolesToAssign = getRoleNameList(model);
        List&lt;string&gt; modelRoleIds = getRoleIdList(model);
    try
    {
        var currentUser = await UserManager.FindByIdAsync(model.Id);
        // create list of current user's roles to determine if they have been modified
        List&lt;string&gt; currentUserRoleIds = new List&lt;string&gt;();
        foreach (var role in currentUser.Roles)
        {
            currentUserRoleIds.Add(role.RoleId);
        }

        // persist user roles to User Db if changes have been made
        if (currentUserRoleIds.Except(modelRoleIds).Any() || modelRoleIds.Except(currentUserRoleIds).Any())
        {
            var updateRolesResult = await AssignRolesToUser(model.Id, rolesToAssign.ToArray());
            if (updateRolesResult.Succeeded)
            {
                return RedirectToAction(""ManageUsers"", new { Message = ManageMessageId.AccountUpdateSuccess });
            }
            AddErrors(updateRolesResult);
        }
        // persist user info to User Db if changes have been made
        else if(currentUser.Email != model.Email || currentUser.FirstName != model.FirstName || currentUser.LastName != model.LastName)
        {
            currentUser.UserName = model.Email;
            currentUser.Email = model.Email;
            currentUser.FirstName = model.FirstName;
            currentUser.LastName = model.LastName;

            var updateUserResult = await UserManager.UpdateAsync(currentUser);
            if (updateUserResult.Succeeded)
            {
                return RedirectToAction(""ManageUsers"", new { Message = ManageMessageId.AccountUpdateSuccess });
            }
            AddErrors(updateUserResult);
        }
        // persist user password to User Db if changes have been made
        else
        {
            var token = await UserManager.GeneratePasswordResetTokenAsync(currentUser.Id);
            var updatePasswordResult = await UserManager.ResetPasswordAsync(currentUser.Id, token, model.Password);
            if (updatePasswordResult.Succeeded)
            {
                return RedirectToAction(""ManageUsers"", new { Message = ManageMessageId.AccountUpdateSuccess });
            }
            AddErrors(updatePasswordResult);
        }
    }
    catch (Exception ex)
    {
        ErrLog.LogError(ex, ""ManageController.Users_Edit"");
    }
}

return Json(new[] { model }.AsQueryable().ToDataSourceResult(request, ModelState));
}
</code></pre>

<p>Action #4: </p>

<pre><code>[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = ""DM_Admin"")] 
public async Task&lt;ActionResult&gt; Users_Delete([DataSourceRequest] DataSourceRequest request, ManageUsersViewModel model)
{
    if (model != null &amp;&amp; ModelState.IsValid)
    {
        // format the RolesList to type List&lt;string&gt; for removal  
        List&lt;string&gt; rolesToRemove = getRoleNameList(model);
    try
    {
        // get the user to be deleted by id
        var user = await UserManager.FindByIdAsync(model.Id);

        // remove roles from user in User Db
        var removeRolesResult = await UserManager.RemoveFromRolesAsync(user.Id, rolesToRemove.ToArray());
        if (removeRolesResult.Succeeded)
        {
            // remove user from User Db
            var removeUserResult = await UserManager.DeleteAsync(user);
            if (removeUserResult.Succeeded)
            {
                return RedirectToAction(""ManageUsers"", new { Message = ManageMessageId.AccountDeleteSuccess });
            }
            AddErrors(removeUserResult);
        }
        else
        {
            AddErrors(removeRolesResult);
        }
    }
    catch (Exception ex)
    {
        ErrLog.LogError(ex, ""ManageController.Users_Delete"");
    }
}

return Json(new[] { model }.AsQueryable().ToDataSourceResult(request, ModelState));
}
</code></pre>

<p>Action #5: </p>

<pre><code>[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = ""DM_Admin"")] 
public async Task&lt;IdentityResult&gt; AssignRolesToUser(string id, string[] rolesToAssign)
{
    if (rolesToAssign != null)
    {
        try
        {
            // find the user to assign roles to
            var user = await UserManager.FindByIdAsync(id);
            if (user != null)
            {
                // check if the user currently has any roles
                var currentRoles = await UserManager.GetRolesAsync(user.Id);
                var rolesNotExist = rolesToAssign.Except(RoleManager.Roles.Select(x =&gt; x.Name)).ToArray();
            if (!(rolesNotExist.Count() &gt; 0))
            {
                // remove current roles from user, if any, in User Db
                var removeRolesResult = await UserManager.RemoveFromRolesAsync(user.Id, currentRoles.ToArray());
                if (!removeRolesResult.Succeeded)
                {
                    AddErrors(removeRolesResult);
                    return removeRolesResult;
                }

                // assign new roles to user in User Db
                var addRolesResult = await UserManager.AddToRolesAsync(user.Id, rolesToAssign);
                if (!addRolesResult.Succeeded)
                {
                    AddErrors(addRolesResult);
                }
                return addRolesResult;
            }
            else
            {
                ModelState.AddModelError("""", string.Format(""Roles '{0}' do not exist in the system"", string.Join("","", rolesNotExist)));
            }
        }
        else
        {
            ModelState.AddModelError("""", string.Format(""Unable to find user""));
        }
    }
    catch (Exception ex)
    {
        ErrLog.LogError(ex, ""ManageController.AssignRolesToUser"");
    }
}
else
{
    ModelState.AddModelError("""", string.Format(""No roles specified""));
}
return null;
}
</code></pre>

<p>I kept the Identity framework the same as how Microsoft sets it up when creating a default Mvc application, and because of this I'm not really sure how to go about refactoring the code.</p>

<p>I understand this is a longer post, so thank you so much for taking the time to read it and I hope to hear from you all soon. </p>

<p>**Note: I added 5 action methods because I believe they may be necessary to show in order to thin out the controller as a whole, along with giving a better understanding of whats going on. But please don't feel the need to provide examples for all of the actions listed. **</p>

<p>Thanks so much guys!
Snawwz </p>
",https://stackoverflow.com/questions/46545093/thin-out-controller-in-asp-net-mvc-5-specific-example,"['c#', 'design-patterns', 'model-view-controller', 'asp.net-mvc-5']",932,TRUE,0,2
Using Streams in C# for SSH library,"<p>I'm working on a Putty-like user-interactive SSH UI using C# and SSH.NET, an open-source library for making SSH connections.  The issue I've been having is that the way all the examples I've been able to find work, they appear to create a new connection, or execute in non-interactive mode, which means nothing executed in a prior command carries over to following commands.</p>
<p>I'm basically new to using streams - there are some methods in the SSH.NET library that appear to open a shell using streams, such that you can assign streams to stdin, stdout, and stderr, but in trying to use them, I can't find good information on how to setup the streams to feed them into the method calls.</p>
<ol>
<li>Do I feed in raw streams?</li>
<li>Do I use <code>MemoryStream</code> or <code>TextStream</code>?</li>
</ol>
<p>Here's the short definition of the <code>CreateShell</code> method in the <code>SshClient</code> class in SSH.NET:</p>
<pre><code>public Shell CreateShell(Stream input, Stream output, Stream extendedOutput)
{
    return CreateShell(input, output, extendedOutput, string.Empty, 0, 0, 0, 0, null, 1024);
}
</code></pre>
<p>And the long override version that one uses:</p>
<pre><code>public Shell CreateShell(Stream input, Stream output, Stream extendedOutput, string terminalName, uint columns, uint rows, uint width, uint height, IDictionary&lt;TerminalModes, uint&gt; terminalModes, int bufferSize)
{
    EnsureSessionIsOpen();

    return new Shell(Session, input, output, extendedOutput, terminalName, columns, rows, width, height, terminalModes, bufferSize);
}
</code></pre>
<p>And after setting up the correct streams to attach, how do I read and write to them?  Do I need to setup a <code>StreamReader</code> and/or <code>StreamWriter</code> to access the stream(s)?  I have already done this in order to read the <code>StdErr</code> after using the existing <code>SshCommand</code> object with the <code>.Execute()</code> method, but I'm not sure how to tie this to the pre-existing streams that I create.</p>
<hr />
<h2>ShellStream Class</h2>
<p>Finally, there is another option which seems to make the connection with a single <code>Stream</code> object - but I'm unsure if this is just being used for Unit Testing, or if it is viable for &quot;normal&quot; operations:</p>
<pre><code>public ShellStream CreateShellStream(string terminalName, uint columns, uint rows, uint width, uint height, int bufferSize, IDictionary&lt;TerminalModes, uint&gt; terminalModeValues)
{
    EnsureSessionIsOpen();

    return ServiceFactory.CreateShellStream(Session, terminalName, columns, rows, width, height, terminalModeValues, bufferSize);
}
</code></pre>
<p>The <code>ShellStream : Stream</code> class does look like a good candidate as well, with overrides to the base <code>Stream</code> class for <code>CanRead</code>, <code>CanSeek</code>, <code>CanWrite</code>, <code>Flush</code>, <code>Length</code>, <code>Read</code>, <code>Write</code>, etc.</p>
<p>Here is the base definition of the <code>ShellStream</code> class, with properties and the constructor:</p>
<pre><code>public class ShellStream : Stream
{
    private const string CrLf = &quot;\r\n&quot;;

    private readonly ISession _session;
    private readonly Encoding _encoding;
    private readonly int _bufferSize;
    private readonly Queue&lt;byte&gt; _incoming;
    private readonly Queue&lt;byte&gt; _outgoing;
    private IChannelSession _channel;
    private AutoResetEvent _dataReceived = new AutoResetEvent(false);
    private bool _isDisposed;

    /// &lt;summary&gt;
    /// Occurs when data was received.
    /// &lt;/summary&gt;
    public event EventHandler&lt;ShellDataEventArgs&gt; DataReceived;

    /// &lt;summary&gt;
    /// Occurs when an error occurred.
    /// &lt;/summary&gt;
    public event EventHandler&lt;ExceptionEventArgs&gt; ErrorOccurred;

    /// &lt;summary&gt;
    /// Gets a value that indicates whether data is available on the &lt;see cref=&quot;ShellStream&quot;/&gt; to be read.
    /// &lt;/summary&gt;
    /// &lt;value&gt;
    /// &lt;c&gt;true&lt;/c&gt; if data is available to be read; otherwise, &lt;c&gt;false&lt;/c&gt;.
    /// &lt;/value&gt;
    public bool DataAvailable
    {
        get
        {
            lock (_incoming)
            {
                return _incoming.Count &gt; 0;
            }
        }
    }

    /// &lt;summary&gt;
    /// Gets the number of bytes that will be written to the internal buffer.
    /// &lt;/summary&gt;
    /// &lt;value&gt;
    /// The number of bytes that will be written to the internal buffer.
    /// &lt;/value&gt;
    internal int BufferSize
    {
        get { return _bufferSize; }
    }


    /// &lt;summary&gt;
    /// Initializes a new &lt;see cref=&quot;ShellStream&quot;/&gt; instance.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;session&quot;&gt;The SSH session.&lt;/param&gt;
    /// &lt;param name=&quot;terminalName&quot;&gt;The &lt;c&gt;TERM&lt;/c&gt; environment variable.&lt;/param&gt;
    /// &lt;param name=&quot;columns&quot;&gt;The terminal width in columns.&lt;/param&gt;
    /// &lt;param name=&quot;rows&quot;&gt;The terminal width in rows.&lt;/param&gt;
    /// &lt;param name=&quot;width&quot;&gt;The terminal height in pixels.&lt;/param&gt;
    /// &lt;param name=&quot;height&quot;&gt;The terminal height in pixels.&lt;/param&gt;
    /// &lt;param name=&quot;terminalModeValues&quot;&gt;The terminal mode values.&lt;/param&gt;
    /// &lt;param name=&quot;bufferSize&quot;&gt;The size of the buffer.&lt;/param&gt;
    internal ShellStream(ISession session, string terminalName, uint columns, uint rows, uint width, uint height, IDictionary&lt;TerminalModes, uint&gt; terminalModeValues, int bufferSize)
    {
        _encoding = session.ConnectionInfo.Encoding;
        _session = session;
        _bufferSize = bufferSize;
        _incoming = new Queue&lt;byte&gt;();
        _outgoing = new Queue&lt;byte&gt;();

        _channel = _session.CreateChannelSession();
        _channel.DataReceived += Channel_DataReceived;
        _channel.Closed += Channel_Closed;
        _session.Disconnected += Session_Disconnected;
        _session.ErrorOccured += Session_ErrorOccured;

        _channel.Open();
        _channel.SendPseudoTerminalRequest(terminalName, columns, rows, width, height, terminalModeValues);
        _channel.SendShellRequest();
    }
</code></pre>
",https://stackoverflow.com/questions/46899576/using-streams-in-c-for-ssh-library,"['c#', 'stream', 'ssh.net']",1050,FALSE,0,0
How to selectively initialize module-level objects?,"<p>I have a Flask web app using SQLAlchemy. The database backing it in production is Postgres, but for the purpose of unit testing I would also like to be able to initialize it against SQLite.</p>

<p>I use <code>alembic</code> for database schema changes. For this reason, I've decided not to support SQLite for production, since making alembic support SQLite is more trouble than I want. However, I still want to be able to create the tables from scratch inside SQLite, for testing purposes; this doesn't invoke alembic, but just uses SQLAlchemy's <code>create_all()</code>.</p>

<p>I'm using declarative models, and in order to make alembic work better, I've set a naming convention for constraints as suggested in their documentation:</p>

<pre><code>naming = {
    ""ix"": 'ix_%(column_0_label)s',
    ""uq"": ""uq_%(table_name)s_%(column_0_name)s"",
    ""ck"": ""ck_%(table_name)s_%(constraint_name)s"",
    ""fk"": ""fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s"",
    ""pk"": ""pk_%(table_name)s"",
}

Base = declarative_base(metadata=MetaData(naming_convention=naming))

class Model1(Base):
    ...
</code></pre>

<p>This works fine inside Postgres, but fails in SQLite; apparently the naming convention is somehow incompatible. (This may be related to the fact that some of my models have <code>Boolean</code> columns, which are apparently handled differently across the two engines.)</p>

<p>Since I don't actually need SQLite for production and couldn't use alembic there if I did, I'm inclined to simply drop the naming convention in that case and let it use default names when running tests. However, since this is all done at the module top level (and has to be, in order to use <code>Base</code> as a base class), I can't find a way to make this distinction. Ideally, I could set some kind of flag in the test suite before importing the models, which would cause that module to create <code>Base</code> with a default metadata rather than having the naming convention enabled. But I can't find a way to do this communication at import time.</p>

<p>How can I pass data in to control the creation of the declarative base at import time? Alternatively, is there a way to easily make SQLite work with the naming convention enabled?</p>
",https://stackoverflow.com/questions/46394433/how-to-selectively-initialize-module-level-objects,"['python', 'python-3.x', 'sqlalchemy']",60,TRUE,0,1
Stub external service requests for functional tests with symfony di container,"<p><strong>question summary</strong></p>

<p>Is it possible to inject stubs/mocks to the symfony di container in my test cases to simulate different external api responses?</p>

<ul>
<li>test that my application sends an email if the api returns an error (i want to inject a stub for my http client class that returns a HTTP 500)</li>
<li>test that my application returns the correct result using 2 different APIs as source (i want to inject both HTTP Clients as stub with a specific result body)</li>
</ul>

<p><strong>details</strong></p>

<p>i want to write functional tests for an silex application that uses the symfony di container. The application uses multiple API's as backend to fullfill the client reuquests.</p>

<p>The code injects an abstracted http client to the api client where i'm able to inject a http api client stub.</p>

<pre><code>class AwesomeApiClient
   __construct(MyHttpClient $httpClient);

class MyApiHttpClient
</code></pre>

<p>This does work pretty good with unit testing.</p>

<p>Now i want to write functional tests.
I extended the silex <code>WebTestCase</code> and implemented the application initialization.
The MyApiHttpClient is injected with the symfony di container.</p>

<p>Now i want to do something like this:</p>

<pre><code># symfony di container does not allow this
$this-&gt;getDiContainer()-&gt;set('my_http_client', $myHttpClientStubInstance);
</code></pre>

<p>i want to configure my stub in every test so i'm able to test different (e.g. error, success) responses for the same request.</p>

<p>things i've tried:</p>

<p><strong>using setter injection at runtime</strong></p>

<p><code>$his-&gt;getDiContainer()-&gt;get('MyApiClient')-&gt;setHttpClient($myMock);</code></p>

<p>The DiContainer returns a new instance for everytime i call the get method. That does make absolutely sense. So this does not work.</p>

<p><strong>overriding the http client in the di container</strong></p>

<p><code>$this-&gt;getDiContainer-&gt;set('MyHttpClient', $myHttpClientStub);</code></p>

<p>Does not work because symfony does not allow to change definitions at runtime. Also it seems to take a definition, not an instance.</p>

<p><strong>PHP-VCR</strong></p>

<p>Does work with a few changes in my production code because it messes up the HTTP Headers in my curl header callbacks. Does not work for other services (rabbitmq...)</p>
",https://stackoverflow.com/questions/47236169/stub-external-service-requests-for-functional-tests-with-symfony-di-container,"['php', 'symfony', 'phpunit']",1365,TRUE,0,1
CmakeList - Not able to create correct CMakelist for C++ Project subfolders,"<p>I have a C++ Project folder which contains two folders.</p>

<ol>
<li><p>a C++ src folder with multiple sub-folders and CmakeList.txt file. The src folder contains main.cpp file. </p>

<pre><code>**Cmakelist.txt src folder**
project (TestProject)
# Include all global directories and the current directory
include_directories(${GLOBAL_INCLUDES} ""."")
link_directories(${GLOBAL_LIB_DIRS})
file(GLOB_RECURSE GLOBAL_SOURCES ""${CMAKE_CURRENT_SOURCE_DIR}"" ""*.cpp"")
add_executable(${PROJECT_NAME} ${GLOBAL_SOURCES})
target_link_libraries(${PROJECT_NAME} ${GLOBAL_LIBS})
set_target_properties(${PROJECT_NAME} PROPERTIES DEBUG_POSTFIX ""d"")
install(TARGETS ${PROJECT_NAME} DESTINATION ${INSTALL_DIR})
</code></pre></li>
<li><p>a C++ build standard external folder ExtLib containing multiple subfolders and a build.sh script for its compilation and CmakeList.txt file. The .cpp files from the src folder are linked (includes header(.h) files) to this ExtLib folder.</p></li>
</ol>

<p>The Project folder contains a main build.sh file which compiles the project and creates a build folder including debug and release configurations. It also contains a CmakeList.txt file which I suppose gets executed when build.sh file is executed. The task that I need to perform on this project is to create a new tests folder and add a file (RunAllTests.cpp) which performs unit-testing (using catch unit-test) on the code written in the src folder .cpp files.</p>

<p>Problem I face:</p>

<ul>
<li><p>The first problem is when I am creating a source test file in my tests folder, and trying to include header files from src folder, the compiler throws a fatal error that no such (.h) files found which means if i include a file in tests folder source file, which includes a header file from ExtLib folder - then i get error in linking files from ExtLib folder in tests folder files via src folder files. Are my all Cmakelist files correctly written?</p>

<pre><code>**Cmakelist.txt tests folder**
cmake_minimum_required(VERSION 3.5)
set_property(GLOBAL PROPERTY USE_FOLDERS ON)
include_directories(../src)
include_directories(../ExtLib)
link_directories(${GLOBAL_LIB_DIRS})
add_library(AConfigTest ./aconfigtest/AConfigTest.cpp)
add_library(AClientTest ./aclienttest/AClientTest.cpp)
add_library(AServerTest ./aservertest/AServerTest.cpp)
file(GLOB_RECURSE GLOBAL_SOURCES 
     ""${PROJECT_SOURCE_DIR}/src/AConfig/*.cpp""
     ""${PROJECT_SOURCE_DIR}/src/AClient/*.cpp"" 
     ""${PROJECT_SOURCE_DIR}/src/AServer/*.cpp""
     ""${PROJECT_SOURCE_DIR}/src/ErrorLogger.cpp""
)
add_executable(tests RunAllTests.cpp ${GLOBAL_SOURCES})
set_target_properties(tests PROPERTIES DEBUG_POSTFIX ""d"")
target_link_libraries(tests ${GLOBAL_LIBS} 
    AConfigTest
    AClientTest
    AServerTest
)
</code></pre></li>
<li><p>The second question is, if by some how I am able to include files from other src or ExtLib folders successfully, how can I be able to run the test source file RunAllTests.cpp for executing my test cases? Are my all Cmakelist files correctly written?</p></li>
</ul>

<p>I am stucked on this problem since 3 weeks, I desperately need a solution for this. Below is the compiler error:</p>

<p>Compiler error:</p>

<pre><code>make[2]: Entering directory '/home/Caspian/TestProject/build/linux/debug'
[ 56%] Building CXX object tests/CMakeFiles/tests.dir/RunAllTests.cpp.o
cd /home/Caspian/TestProject/build/linux/debug/tests &amp;&amp; /usr/bin/c++    -I/home/Caspian/TestProject/tests/../src -I/home/Caspian/TestProject/tests/../ExtLib  -g   -o CMakeFiles/tests.dir/RunAllTests.cpp.o -c /home/Caspian/TestProject/tests/RunAllTests.cpp
In file included from /home/Caspian/TestProject/tests/RunAllTests.cpp:14:0:
/home/Caspian/TestProject/tests/../src/AConfig/Config.h:16:29: fatal error: xxplatformlayer.h: No such file or directory
compilation terminated.
tests/CMakeFiles/tests.dir/build.make:62: recipe for target 'tests/CMakeFiles/tests.dir/RunAllTests.cpp.o' failed
make[2]: *** [tests/CMakeFiles/tests.dir/RunAllTests.cpp.o] Error 1
make[2]: Leaving directory '/home/Caspian/TestProject/build/linux/debug'
CMakeFiles/Makefile2:277: recipe for target 'tests/CMakeFiles/tests.dir/all' failed
make[1]: *** [tests/CMakeFiles/tests.dir/all] Error 2
make[1]: Leaving directory '/home/Caspian/TestProject/build/linux/debug'
Makefile:127: recipe for target 'all' failed
make: *** [all] Error 2
make failed.
</code></pre>

<p>The project heirarchy is shown below:</p>

<pre><code>/TestProject 
  │   build.sh
  │   CMakeList.txt
  /ExtLib
      │   build.sh
      │   CMakeList.txt
      │   debug
      │   release
      │   A/include/..(multiple subfolders and .cpp files)
  /src
      │   build.sh
      │   CMakeList.txt
      │   AServer(multiple subfolders and .cpp files)
      │   AClient(multiple subfolders and .cpp files)
      │   AConfigt(multiple subfolders and .cpp files)
  /tests
      │   CMakeList.txt
      │   RunAllTests.cpp
      │   aservertest/AServerTest.cpp (testing src AServer)
      │   aclienttest/AClientTest.cpp (testing src AClient)
      │   aconfigtest/AConfigTest.cpp (testing src AConfig)
</code></pre>
",https://stackoverflow.com/questions/43250341/cmakelist-not-able-to-create-correct-cmakelist-for-c-project-subfolders,"['c++', 'makefile', 'cmake', 'eclipse-cdt', 'catch-unit-test']",295,FALSE,0,0
Which is the correct authorization approach for fine grained entitlements on an API?,"<p>I am working on a site that has multiple layers of security.  The most basic level of security is handled by a custom Authorize attribute which verifies the user is in the correct role, etc.</p>

<p>We decorate the methods in our controller with the Authorize method and this prevents unauthorized users from accessing those calls.  </p>

<p>However, we also have some fine grained entitlement requirements.  A user from Company A should not be able to modify any of the users from Company B, for instance.  So while both the admins from Company A and Company B have permission to call 'UpdateUser' from the API, Company A should not be able to update one of Company B's users.</p>

<p>Currently, the restriction of access across companies is being handled inside of the controller.  The issue I have is that every new method we introduce includes either a copy and paste of the code or a very similar variation.</p>

<p>That said, I'm not certain it belongs in the service either (let's call it UserService).</p>

<p>So the options I have are:</p>

<ol>
<li><p>Do a check inside the controller to see if the user requesting the update is a part of the same company as the user being updated</p></li>
<li><p>Perform the same check inside of the service.</p></li>
<li><p>Any Suggestions from the community.</p></li>
</ol>

<p>The advantage to the second approach is that the code does not need to be repeated in the controllers.  When the same service method is called by multiple controllers the benefit is clear -- the underlying checks are consistent and the code isn't repeated.</p>

<p>The downside of the second approach is that now my services need to know about the authenticated user.  This presents something of a problem for unit testing.</p>

<p>What patterns are considered 'best practice' for these types of fine grained entitlements?</p>
",https://stackoverflow.com/questions/44026135/which-is-the-correct-authorization-approach-for-fine-grained-entitlements-on-an,"['c#', 'asp.net', 'asp.net-web-api', 'asp.net-web-api2']",216,FALSE,0,1
Common behavior in class-based unit test: inheritance or shared test fixtures?,"<p>I have several test classes to write, that I expect to have quite similar Setup and Teardown code (basically the same methods, but with different arguments). 
From what I understand of the unittest package, it seems that there are two methods for doing such:</p>

<ul>
<li>Create a base class inheriting from matlab.unittest.TestCase class, with the common code for Setup and Teardown. Then all my actual test cases classes would extend it.</li>
<li>Using the shared test fixtures pattern documented <a href=""https://fr.mathworks.com/help/matlab/matlab_prog/write-test-using-shared-fixtures.html"" rel=""nofollow noreferrer"">here</a>: the fixture would contain common setup/teardown code and be referenced in all test cases classes</li>
</ul>

<p>After reading Andy Campbell answer, I think it is worth giving some more context to the usecase and our TestSuite organization: the software we are testing in these tests can only be used throughout a simulation bench, meaning this is not actually speaking unit-testing in the sense that we do not test one function at a time. Our testing strategy is as follows:</p>

<ul>
<li>Play a simulation scenario with our simulator</li>
<li>Record simulation output (in a file or in workspace) </li>
<li>Launch unit-tests on previously recorded simulation output</li>
<li>At the end of the test sequence, publish additional results about the simulation</li>
</ul>

<p>Given that simulation are computationally expensive, we cannot afford to launch the simulation before each unittest. On the other hand, as we have one test class for each simulation scenario, the setup/teardown code shall be applied for each test class.</p>

<p>Which one would you advocate for ? The first one seems to me more natural and easier to understand, but I feel like it is maybe not the canonical way to do so.  On the other hand, I am not sure to completely grasp the notion of shared fixture.</p>
",https://stackoverflow.com/questions/42759516/common-behavior-in-class-based-unit-test-inheritance-or-shared-test-fixtures,"['matlab', 'unit-testing']",432,TRUE,-1,1
Firefox 55/54 browser throws exception OR does not returns back the control to selenium code for maven project after initialization in Windows-7 x64,"<p>I have set up an ANT project to write my UI automation framework using Selenium 3.4.0. I am using Gecko driver v18.0 for supporting latest FF browser v55.
java version I am using is 1.8. This project initializes the FF browser with ""desired capabilities"" object and completes the test. IDE used for this project is Eclipse (Enide 2015). The unit testing framework here is TestNG.</p>

<p>I tried to replicate the same in a maven project using 3.4.0 selenium &amp; Gecko driver v18.0. IDE I am using is IntelliJ. But here after the code executes the driver-initialize part, the browser window opens and then the control never comes back to selenium. The browser remains open for 10-15 min &amp; process keeps running in the background. I have to stop the run to come out of it. Unit testing framework for Maven project here JBehave.</p>

<p>So I did few hit and trails to see the compatibility between Selenium and Gecko driver for Firefox:</p>

<ol>
<li>Selenium 3.4.0 | Firefox v55 | Gecko Driver version - v15 for 32/64 bit |</li>
</ol>

<p><strong>Result:</strong>
After Initializing FF browser, control does not return back to Selenium.</p>

<ol start=""2"">
<li>Selenium 3.4.0 | Firefox v55 | Gecko Driver version - v16 for 32/64 bit |</li>
</ol>

<p><strong>Result:</strong>
org.openqa.selenium.SessionNotCreatedException: Unable to create new remote session. desired capabilities = Capabilities [{moz:firefoxOptions={binary=Optional.empty, args=[], legacy=false, logLevel=null, prefs={}, profile=null}}], required capabilities = Capabilities [{}]
Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
System info: host: 'XXXXX', ip: 'xxx.xxx.xx.xx', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_45'
Driver info: driver.version: FirefoxDriver</p>

<ol start=""3"">
<li>Selenium 3.5.1 | Firefox v55 | Gecko Driver version - v15-v19 for 32/64 bit |</li>
</ol>

<p><strong>Result:</strong>
org.openqa.selenium.SessionNotCreatedException: Unable to create new remote session. desired capabilities = Capabilities [{moz:firefoxOptions={binary=Optional.empty, args=[], legacy=false, logLevel=null, prefs={}, profile=null}}], required capabilities = Capabilities [{}]
Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
System info: host: 'XXXXX', ip: 'xxx.xxx.xx.xx', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_45'
Driver info: driver.version: FirefoxDriver</p>

<ol start=""4"">
<li>Selenium 2.53.1 | Firefox v55 | Gecko Driver version - v15 for 32/64 bit |</li>
</ol>

<p><strong>Result:</strong>
WebDriverException: Failed to connect to binary FirefoxBinary(C:\Program Files (x86)\Mozilla Firefox\firefox.exe) on port 7055</p>

<ol start=""5"">
<li>Selenium 2.53.1 | Chrome |</li>
</ol>

<p><strong>Result:</strong>
Test code executed successfully.</p>

<ol start=""6"">
<li>Selenium 3.5.1 | Firefox v54 | Gecko Driver version - v16 for 32/64 bit |</li>
</ol>

<p><strong>Result:</strong>
org.openqa.selenium.SessionNotCreatedException: Unable to create new remote session. desired capabilities = Capabilities [{moz:firefoxOptions={binary=Optional.empty, args=[], legacy=false, logLevel=null, prefs={}, profile=null}}], required capabilities = Capabilities [{}]
Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
System info: host: 'XXXXX', ip: 'xxx.xxx.xx.xx', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_45'
Driver info: driver.version: FirefoxDriver</p>

<p>I have read through most links mentioned below but it did not help-</p>

<ol>
<li><a href=""https://stackoverflow.com/questions/45864707/selenium-3-4-0-with-firefox-55"">Selenium 3.4.0 with Firefox 55</a></li>
<li><a href=""https://seleniumhq.wordpress.com/2017/08/09/firefox-55-and-selenium-ide/"" rel=""nofollow noreferrer"">https://seleniumhq.wordpress.com/2017/08/09/firefox-55-and-selenium-ide/</a></li>
<li><a href=""https://stackoverflow.com/questions/40106844/selenium-3-0-firefx-driver-fails-with-org-openqa-selenium-sessionnotcreatedexcep"">Selenium 3.0 Firefx Driver fails with org.openqa.selenium.SessionNotCreatedException: Unable to create new remote session</a></li>
<li><a href=""https://stackoverflow.com/questions/41735818/unable-to-create-new-remote-session-selenium-webdriver"">Unable to create new remote session - Selenium webdriver</a></li>
<li><a href=""https://github.com/mozilla/geckodriver/issues/749"" rel=""nofollow noreferrer"">https://github.com/mozilla/geckodriver/issues/749</a> </li>
<li><a href=""https://github.com/SeleniumHQ/selenium/issues/3630"" rel=""nofollow noreferrer"">https://github.com/SeleniumHQ/selenium/issues/3630</a></li>
</ol>

<p>For the first entry above (...which is Selenium 3.4.0, Firefox v55 and Gecko drover v15  for 32/64 bit windows), when I did Ctrl+Shift+J I got the below log-</p>

<p>1505982873005   addons.xpi  WARN    Error parsing extensions state: [Exception... ""Component returned failure code: 0x80520012 (NS_ERROR_FILE_NOT_FOUND) [amIAddonManagerStartup.readStartupData]""  nsresult: ""0x80520012 (NS_ERROR_FILE_NOT_FOUND)""  location: ""JS frame :: resource://gre/modules/addons/XPIProvider.jsm :: loadExtensionState :: line 1596""  data: no] Stack trace: </p>

<pre><code>loadExtensionState()@resource://gre/modules/addons/XPIProvider.jsm:1596 &lt; getInstallState()@resource://gre/modules/addons/XPIProvider.jsm:1631 &lt; checkForChanges()@resource://gre/modules/addons/XPIProvider.jsm:3152 &lt; startup()@resource://gre/modules/addons/XPIProvider.jsm:2246 &lt; callProvider()@resource://gre/modules/AddonManager.jsm:271 &lt; _startProvider()@resource://gre/modules/AddonManager.jsm:741 &lt; startup()@resource://gre/modules/AddonManager.jsm:908 &lt; startup()@resource://gre/modules/AddonManager.jsm:3122 &lt; observe()@jar:file:///C:/Program%20Files%20(x86)/Mozilla%20Firefox/omni.ja!/components/addonManager.js:65
</code></pre>

<p>While creating services from category 'profile-after-change', service for entry 'Notification Telemetry Service', contract ID '@mozilla.org/notificationTelemetryService;1' does not implement nsIObserver.
Warning: unrecognized command line flag --marionette
  nsBrowserContentHandler.js:726
PAC file installed from <a href=""http://autocache.hpecorp.net/"" rel=""nofollow noreferrer"">http://autocache.hpecorp.net/</a>
Property contained reference to invalid variable.  Error in parsing value for ‘color’.  Falling back to ‘inherit’.  browser.css:251:7560
DEPRECATION WARNING: Search service falling back to synchronous initialization. This is generally the consequence of an add-on using a deprecated search service API.</p>

<p>My target is to use this framework for UI testing against the latest stable version of IE, Chrome &amp; Firefox browser. Any help in this regard will be helpful.</p>
",https://stackoverflow.com/questions/46537549/firefox-55-54-browser-throws-exception-or-does-not-returns-back-the-control-to-s,"['selenium', 'selenium-webdriver', 'webdriver', 'ui-automation', 'geckodriver']",431,FALSE,0,1
compare two time series (simulation results),"<p>I want to do unit testing of simulation models and for that, I run a simulation once and store the results (a time series) as reference in a csv file (see an example <a href=""https://gist.github.com/thorade/60fb0d9594750e3140bab9cd1237af84"" rel=""noreferrer"">here</a>). Now when I change my model, I run the simulation again, store the new reults as a csv file as well and then I compare the results.</p>

<p>The results are usually not 100% identical, an example plot is shown below:<br>
The reference results are plotted in <strong>black</strong> and the new results are plotted in <strong>green</strong>.<br>
The difference of the two is plotted in the second plot, in <strong>blue</strong>.<br>
As can be seen, at a step the difference can become arbitrarily high, while everywhere else the difference is almost zero.</p>

<p>Therefore, I would prefer to use a different algorithms for comparison than just subtracting the two, but I can only describe my idea graphically: 
When plotting the reference line twice, first in a light color with a high line width and then again in a dark color and a small line width, then it will look like it has a <strong>pink tube</strong> around the centerline.  </p>

<p>Note that during a step that tube will not only be in the direction of the ordinate axis, but also in the direction of the abscissa. 
When doing my comparison, I want to know whether the green line stays within the pink tube.
<a href=""https://i.stack.imgur.com/Mp3rk.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/Mp3rk.png"" alt=""enter image description here""></a></p>

<p>Now comes my question: I do not want to compare the two time series using a graph, but using a python script. There must be something like this already, but I cannot find it because I am missing the right vocabulary, I believe. Any ideas? Is something like that in numpy, scipy, or similar? Or would I have to write the comparison myself?</p>

<p>Additional question: When the script says the two series are not sufficiently similar, I would like to plot it as described above (using matplotlib), but the line width has to be defined somehow in other units than what I usually use to define line width.  </p>
",https://stackoverflow.com/questions/46316442/compare-two-time-series-simulation-results,"['python', 'numpy', 'matplotlib', 'time-series', 'timeserieschart']",6100,TRUE,8,4
How to publish a library of Vue.js components?,"<p>I am working on a project containing a Vuex module and an abstract components that users can extend from. </p>

<p>I would love to publish this on NPM to clean up my codebase and pull this away from my project as a solid well tested module. I have specified the main file in <code>package.json</code> to load an index which imports everything I want to expose:</p>

<p><a href=""https://github.com/stephan-v/vue-search-filters/"" rel=""noreferrer"">https://github.com/stephan-v/vue-search-filters/</a></p>

<p>The index contains this at the moment:</p>

<pre><code>import AbstractFilter from './src/components/filters/abstract/AbstractFilter.vue';
import Search from './src/store/modules/search';

module.exports = {
    AbstractFilter,
    Search
};
</code></pre>

<p>For this to work I need to transpile this since a babel compiler normally won't transpile files imported from node_modules(Correct me if I am wrong here). Besides that I would probably be a good idea to do this so it can be used by different systems.</p>

<p>How do I transpile only the files that I need though with Webpack? Do I have to create a separate config for this?</p>

<p>What does a config like that look like? I know the vue-cli has a <code>build</code> command for one single file component but this is a bit different.</p>

<p>Any tips or suggestions on how to transpile something like this are welcome.</p>

<p><strong>Edit</strong></p>

<p>This seems like a good start as well:</p>

<p><a href=""https://github.com/Akryum/vue-share-components"" rel=""noreferrer"">https://github.com/Akryum/vue-share-components</a></p>

<p>The most import thing for Webpack users to notice is that you need to transpile your files in UMD which can be set by:</p>

<pre><code>libraryTarget: 'umd'
</code></pre>

<p>This will make sure your are transpiling for <code>Universal Module Definition</code>, meaning your code will work in different environments like AMD,CommonJS, as a simple script tag, etc.</p>

<p>Besides that it is import to provide the externals property in webpack:</p>

<pre><code>externals: {}
</code></pre>

<p>Here you can define which libraries your project users but should not be built into your <code>dist</code> file. For example you don't want the Vue library to be compiled / transpiled into the source of your NPM package.</p>

<p>I will research a bit more, so far the best options looks like to create a custom project myself If I want flexibility and unit testing.</p>

<p><strong>Webpack docs</strong></p>

<p>This is also a useful page which goes in depth about how to publish something with Webpack:</p>

<p><a href=""https://webpack.js.org/guides/author-libraries/#add-librarytarget"" rel=""noreferrer"">https://webpack.js.org/guides/author-libraries/#add-librarytarget</a></p>
",https://stackoverflow.com/questions/45298859/how-to-publish-a-library-of-vue-js-components,"['javascript', 'node.js', 'webpack', 'ecmascript-6', 'vue.js']",4721,TRUE,16,2
Why is EF saying my model has changed when it has not?,"<p>I keep getting the following error:</p>

<blockquote>
  <p>System.InvalidOperationException: The model backing the 'McContext'
  context has changed since the database was created. Consider using
  Code First Migrations to update the database
  (<a href=""http://go.microsoft.com/fwlink/?LinkId=238269"" rel=""nofollow noreferrer"">http://go.microsoft.com/fwlink/?LinkId=238269</a>).</p>
</blockquote>

<p>I am creating an .NET MVC 5 website using the latest Entity Framework from nuget, v6.1.3. I am attached to a local MDF file as I don't have SQL Server or Express installed locally. I am using the Code First model.</p>

<p>I spent hours yesterday and today combing through SO and WWW posts on this error, but have not found a solution that works. Most of them revolve around different types of Initializers, or short explanations about how code first requires migrations or initializers for model changes. But I am running the setup manually through the PM console. I have included my steps below.</p>

<p>Connection String:</p>

<pre><code>&lt;add name=""testSQLConnection"" connectionString=""Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\jwatts\Documents\Visual Studio 2015\Projects\MyProject\Databases\MyProject01.mdf;Integrated Security=True;Connect Timeout=30"" providerName=""System.Data.SqlClient"" /&gt;
</code></pre>

<p>The model:</p>

<pre><code>public class Family
{
    public Family() { }

    [Key, Index(IsUnique = true)]
    [Column(Order = 0)]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    [StringLength(128)]
    public string Name { get; set; }

    [StringLength(1024)]
    public string Description { get; set; }

    public DateTime Created { get; set; }

    public string CreatedBy { get; set; }

    public DateTime? Changed { get; set; }

    public string ChangedBy { get; set; }

    public DateTime? Deleted { get; set; }

    public string DeletedBy { get; set; }
}
</code></pre>

<p>The Context:</p>

<pre><code>public class McContext : DbContext
{
    public McContext() : base(""testSQLConnection"") { }

    public DbSet&lt;Family&gt; Families { get; set; }
}
</code></pre>

<p>The configuration:</p>

<pre><code>internal sealed class Configuration : DbMigrationsConfiguration&lt;Data.McContext&gt;
{
    public Configuration()
    {
        MigrationsDirectory = @""Data\Migrations"";
        AutomaticMigrationsEnabled = false;
        AutomaticMigrationDataLossAllowed = false;
    }

    protected override void Seed(McContext context)
    {
        context.Families.Add(new Family()
        {
            Name = ""My Family"",
            Description = ""The family"",
            Created = DateTime.Now,
            CreatedBy = ""system""
        });
        context.SaveChanges();
    }
}
</code></pre>

<p>Auto generated migration class:</p>

<pre><code>public partial class StartupConfig : DbMigration
{
    public override void Up()
    {
        CreateTable(
            ""dbo.Families"",
            c =&gt; new
                {
                    Id = c.Int(nullable: false, identity: true),
                    Name = c.String(nullable: false, maxLength: 128),
                    Description = c.String(maxLength: 1024),
                    Created = c.DateTime(nullable: false),
                    CreatedBy = c.String(),
                    Changed = c.DateTime(),
                    ChangedBy = c.String(),
                    Deleted = c.DateTime(),
                    DeletedBy = c.String(),
                })
            .PrimaryKey(t =&gt; t.Id)
            .Index(t =&gt; t.Id, unique: true);

    }

    public override void Down()
    {
        DropIndex(""dbo.Families"", new[] { ""Id"" });
        DropTable(""dbo.Families"");
    }
}
</code></pre>

<p>Unit test code:</p>

<pre><code>[TestMethod]
public void CreateTheContext_Test()
{
    using (var ctx = new McContext())
    {
        //error on this line below:
        var fam = ctx.Families.Where(f =&gt; f.Name.Contains(""My"")).FirstOrDefault();
        Assert.IsTrue(fam != null &amp;&amp; fam.Name.Contains(""My""));
    }   
}
</code></pre>

<p>Recreation steps:</p>

<ol>
<li>I started with a ""clean slate"" and deleted all database tables in my test database, and deleted all Data\Migrations.</li>
<li>Rebuilt the solution. (The base project and a unit testing project)</li>
<li>In Package Manager Console, ran ""<code>Add-Migration StartupConfig</code>""</li>
<li>A migration file is added to Data\Migrations called ""<code>{datetime}_StartupConfig.cs</code>"". See <code>StartupConfig</code> class above.</li>
<li>I built the project.</li>
<li>I ran ""<code>Update-Database -TargetMigration:StartupConfig</code>""</li>
<li>The PM console outputs 4 lines, including the ""Running Seed method"", and completes successfully.</li>
<li>I confirmed via SQL query that the ""<code>__MigrationHistory</code>"" and ""<code>Families</code>"" table have been added to the database, and each table has 1 record.</li>
<li>I ran the unit test and receive the error.</li>
</ol>

<p>I had a more complex model, but I began removing things one by one making things as simple as I could. But I can't get any simpler than this, and yet the error persists. Of note, for this particular project I have never gotten a successful query out of the unit test. </p>

<p>As I was typing out these recreation steps above, I was performing the steps at the same time, and got the same error.</p>

<p>I am at a loss as to what to try next? </p>
",https://stackoverflow.com/questions/46396305/why-is-ef-saying-my-model-has-changed-when-it-has-not,"['c#', 'sql-server', 'asp.net-mvc', 'entity-framework-6', 'asp.net-mvc-5.2']",1427,TRUE,2,2
Why I can not unit test method `getGoods(): Promise&lt;Good[]&gt;` (service fetching data via Http)?,"<p>I have service named GoodsDataService. It fetches some data via Http service. <a href=""https://github.com/sharikovvladislav/ng2-goods-list/blob/feature/add-logic/src/app/services/goods-data.service.ts#L9"" rel=""nofollow noreferrer"">Here is it</a>.</p>

<p>Constructor is:</p>

<pre><code>constructor(private http: Http) {}
</code></pre>

<p>Function <code>getGoods</code>. It is fetching data via Http service, get method:</p>

<pre><code>  getGoods(): Promise&lt;Good[]&gt; {
    return this.http.get(this.goodsUrl)
      .toPromise()
      .then(response =&gt; response.json().data as Good[])
      .catch(this.handleError);
  }
</code></pre>

<p>Notice <code>toPromise</code> method. I learned it from <a href=""https://angular.io/docs/ts/latest/tutorial/toh-pt6.html"" rel=""nofollow noreferrer"">this Angular official tutorial</a>.</p>

<p>Now about unit testing of <code>getGoods</code> method. Here is unit tests for GoodsDataService: <a href=""https://github.com/sharikovvladislav/ng2-goods-list/blob/feature/add-logic/src/app/services/goods-data.service.spec.ts"" rel=""nofollow noreferrer"">here</a>. <a href=""https://github.com/sharikovvladislav/ng2-goods-list/blob/feature/add-logic/src/app/services/goods-data.service.spec.ts#L51"" rel=""nofollow noreferrer"">This is how I test this method</a>:</p>

<pre><code>service.getGoods()
  .then(goods =&gt; {
    expect(goods.length).toEqual(10);
    expect(goods).toEqual([new Good()]);
  }); 
</code></pre>

<p><code>getGoods</code> makes http call, so <a href=""https://github.com/sharikovvladislav/ng2-goods-list/blob/feature/add-logic/src/app/services/goods-data.service.spec.ts#L31"" rel=""nofollow noreferrer"">I have to mock it</a>. Here is the code: </p>

<pre><code>const mockResponse = [
  {id: 11, name: 'Mr. Nice'},
  {id: 12, name: 'Narco'},
  {id: 13, name: 'Bombasto'},
  {id: 14, name: 'Celeritas'},
  {id: 15, name: 'Magneta'},
  {id: 16, name: 'RubberMan'},
  {id: 17, name: 'Dynama'},
  {id: 18, name: 'Dr IQ'},
  {id: 19, name: 'Magma'},
  {id: 20, name: 'Tornado'}
];

mockBackend.connections.subscribe((connection) =&gt; {
  connection.mockRespond(new Response(new ResponseOptions({
    body: JSON.stringify({data: mockResponse})
  })));
});
</code></pre>

<p>As the result I have green tests. But they can't be green because of this: <code>expect(goods).toEqual([new Good()]);</code>. Result must be red. Anyway, even if I put debugger in <code>then</code> success function (where is two of my expects situated) IDE will be stopped on the breakpoint, I will get this error:</p>

<blockquote>
  <p>Error: Uncaught (in promise): TypeError: Cannot read property 'length' of undefined</p>
</blockquote>

<p>So, despite of I mock real http request with some data I get <code>undefined</code> in success handler which I pass to <code>then</code> of promise returned by <code>getGoods</code> method.</p>

<h1>My thoughts and researches</h1>

<p>Maybe the problem is in <a href=""https://github.com/sharikovvladislav/ng2-goods-list/blob/feature/add-logic/src/app/services/goods-data.service.ts#L19"" rel=""nofollow noreferrer"">these lines</a>:</p>

<pre><code>...
.then(response =&gt; response.json().data as Good[])
...
</code></pre>

<p>If I put debugger there I see that <code>response.json().data</code> is <code>undefined</code> each time. By the way this code fires two times (not once). I think this can be explained by rxjs (http.get returns observable and subscription fires not only once. If I check <code>response.json()</code> value it is Promise. It is rejected. There is some error stacktrace in it.</p>

<p><a href=""https://i.stack.imgur.com/Qeiwu.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Qeiwu.png"" alt=""enter image description here""></a></p>

<p>Here is it:</p>

<pre><code>TypeError: Already read
    at eval (eval at &lt;anonymous&gt; (http://localhost:9876/base/src/test.ts:56782:13), &lt;anonymous&gt;:1:10)
    at http://localhost:9876/base/src/test.ts:56782:13
    at ZoneDelegate.invoke (http://localhost:9876/base/src/polyfills.ts:1546:26)
    at ProxyZoneSpec.Array.concat.ProxyZoneSpec.onInvoke (http://localhost:9876/base/src/test.ts:55337:39)
    at ZoneDelegate.invoke (http://localhost:9876/base/src/polyfills.ts:1545:32)
    at Zone.run (http://localhost:9876/base/src/polyfills.ts:1296:43)
    at http://localhost:9876/base/src/polyfills.ts:1972:57
    at ZoneDelegate.invokeTask (http://localhost:9876/base/src/polyfills.ts:1579:31)
    at ProxyZoneSpec.Array.concat.ProxyZoneSpec.onInvokeTask (http://localhost:9876/base/src/test.ts:55361:39)
    at ZoneDelegate.invokeTask (http://localhost:9876/base/src/polyfills.ts:1578:36)
</code></pre>

<p>How this code was created? I learned from <a href=""https://angular.io/docs/ts/latest/tutorial/toh-pt6.html"" rel=""nofollow noreferrer"">this off tutorial</a> and <a href=""https://blog.thoughtram.io/angular/2016/11/28/testing-services-with-http-in-angular-2.html"" rel=""nofollow noreferrer"">this great article</a>. May be the problem is somewhere here: looks like the article author using another way to fetch data (he using only subscription, without promises). May be thats why my tests does not work.</p>

<p>Probably, my problem relates to <a href=""https://stackoverflow.com/questions/34786358/what-does-this-error-mean-uncaught-typeerror-already-read"">What does this error mean — Uncaught TypeError: Already read?</a>. But how to handle it? </p>

<p>Note, that if I use service in another components - everything works like a charm! For example this code:</p>

<pre><code>ngOnInit() {
  this.goodsDataService.getGoods()
    .then((data) =&gt; {
      debugger;
    })
}
</code></pre>

<p>Shows correct data (array) in <code>data</code>.</p>

<p>The question: what I am doing wrong?</p>

<p>Any thoughts?</p>
",https://stackoverflow.com/questions/44232459/why-i-can-not-unit-test-method-getgoods-promisegood-service-fetching-d,"['angular', 'unit-testing', 'http', 'typescript', 'asynchronous']",131,FALSE,2,0
What are the pros and cons of replacing a list of conditionals(if/switch/ternary operators) with a predicate list?,"<p>Recently I've come across with a school of thought that advocates <strong>replacing conditionals(if/switch/ternary operators, same below) with something else</strong>(polymorphism, strategy, visitor, etc).</p>

<p>As I'd like to learn by trying new approaches, I've then revised some of my Javascript codes and immediately found a relevant case, which is basically the following list of ifs(which is essentially the same as a switch/nested ternary operators):</p>

<pre><code>function checkResult(input) {
    if (isCond1Met(input)) return result1;
    if (isCond2Met(input)) return result2;
    if (isCond3Met(input)) return result3;
    // More conditionals here...
    if (isCondNMet(input)) return resultN;
    return defaultResult;
};
</code></pre>

<p>Shortly after I've come up with trying a predicate list instead.</p>

<p>Assuming that checkResult always return a String(which applies to my specific case), the above list of ifs can be replaced with a list of predicates(it uses arrow function and find which are ES6+ features though):</p>

<pre><code>var resultConds = {
    result1: isCond1Met,
    result2: isCond2Met,
    result3: isCond3Met,
    // More mappings here...
    resultN: isCondNMet
};
var results = Object.keys(resultConds);

function checkResult(input) {
    return results.find(result =&gt; resultConds[result](input)) || defaultResult;
};
</code></pre>

<p>(On a side note: Whether checkResult should take resultConds and defaultResult as arguments should be a relatively minor issue here, same below)</p>

<p>If the above assumption doesn't hold, the list of predicates can be changed into this instead:</p>

<pre><code>var conds = [
    isCond1Met,
    isCond2Met,
    isCond3Met,
    // More predicates here...
    isCondNMet
];
var results = [
    result1,
    result2,
    result3,
    // More results here...
    resultN
];

function checkResult(input) {
    return results[conds.findIndex(cond =&gt; cond(input))] || defaultResult;
};
</code></pre>

<p>A bigger refactoring maybe this:</p>

<pre><code>var condResults = {
    cond1: result1,
    cond2: result2,
    cond3: result3,
    // More mappings here...
    condN: resultN,
};
var conds = Object.keys(condResults);

function checkResult(input) {
    return condResults[conds.find(cond =&gt; isCondMet[cond](input))] || defaultResult;
};
</code></pre>

<p>I'd like to ask what're the pros and cons(<strong>preferably with relevant experience and explanations</strong>) of replacing a list of conditionals with a predicate list, <strong>at least in such cases</strong>(e.g.: input validation check returning a non boolean result based on a list of conditionals)?</p>

<p>For instance, which approach generally leads to probably better:</p>

<ul>
<li>Testability(like unit testing)</li>
<li>Scalability(when there are more and more conditionals/predicates)</li>
<li>Readability(for those being familiar with both approaches to ensure sufficiently fair comparisons)</li>
<li>Usability/Reusability(avoiding/reducing code duplications)</li>
<li>Flexibility(for example, when the internal lower level logic for validating inputs changes drastically while preserving the same external higher level behavior)</li>
<li>Memory footprint/Time performance(specific to Javascript)</li>
<li>Etc</li>
</ul>

<p>Also, if you think the predicate list approach can be improved, please feel free to demonstrate the pros and cons of that improved approach.</p>

<p>Edit: As @Bergi mentioned that Javascript objects are unordered, the ES6+ Maps may be a better choice :)</p>
",https://stackoverflow.com/questions/42948150/what-are-the-pros-and-cons-of-replacing-a-list-of-conditionalsif-switch-ternary,"['javascript', 'conditional-statements', 'predicate']",357,TRUE,1,2
Unreferenced Assembly error when Entity Framework context implements interface,"<p>I have an Entity Framework context implementing a simple interface. These both live in a Data class library, which is referenced by another Core class library. The Data library has a reference to Entity Framework 6, and all EF specific code lives there. No other parts of the system have any EF references.</p>

<p>I've just introduced this interface to allow me to mock out a database connection and start unit testing both of these libraries, but I'm struggling to replace the concrete class with the new interface. Attempts at doing so are telling me I'm missing an Entity Framework reference in the Core library, which I'd rather avoid having.</p>

<p><strong>App (Core library)</strong></p>

<pre><code>// Not actual code, but 
public App()
{
    AppContext c = new AppContext(); // No errors, compiles and runs
    IAppContext i = new AppContext(); // Doesn't compile, unreferenced assembly
 }
</code></pre>

<p>The exact error is CS0012 - The type 'DbContext' is defined in an assembly that is not referenced. You must add a reference to assembly 'EntityFramework'.</p>

<p>I'm struggling to understand why this error only appears when the variable I'm assigning to is of the interface and not the concrete type. The interface setup is straightforward enough, and it doesn't bring in any EF references.</p>

<p><strong>Interface and Implementation (Data library)</strong></p>

<pre><code>// IAppContext.cs
public interface IAppContext
{
    DbSet&lt;Project&gt; Projects { get; set; }
    // A few more DbSets

    int SaveChanges();
}

// AppContext.Interface.cs
public partial class AppContext : IAppContext
{ }
</code></pre>

<p><strong>Intended Mock Usage</strong></p>

<pre><code>// TestContext.cs
public class TestContext : IAppContext
{
    // Mock up DbSets using Moq or equivalent
}
</code></pre>

<p>Eventually, this library wont be responsible for instantiating the context anyway, it will be passed in as a constructor parameter. I'd still like to know why this particular set up is throwing this error though, it doesn't make any sense to me.</p>

<p>I've created a minimal project with the same behaviour, including only the code listed above, and an empty class replacing the Context, which inherits System.Data.Entity.DbContext, and implements IAppContext. The Data library adds only the EntityFramework Reference. The Core library references only the Data library.</p>

<p>While slightly off-topic, if I'm going in the complete wrong direction here, and there's a better way of mocking this out, I'm all ears! This is the way I've mocked up an EF context in the past, although that was for a small project where everything was in a single assembly. </p>
",https://stackoverflow.com/questions/44497907/unreferenced-assembly-error-when-entity-framework-context-implements-interface,"['c#', 'entity-framework', 'mocking', 'undefined-reference']",94,FALSE,1,0
